@mu-crew/muster 0.0.0-stage → 3.0.0

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.
package/bin/muster ADDED
@@ -0,0 +1,3553 @@
1
+ #!/usr/bin/env python3
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import contextlib
6
+ import enum
7
+ import hashlib
8
+ import json
9
+ import math
10
+ import os
11
+ import re
12
+ import shutil
13
+ import socket
14
+ import subprocess
15
+ import sys
16
+ import tempfile
17
+ import time
18
+ import tomllib
19
+ import unicodedata
20
+ from collections.abc import Callable, Generator, Iterable, Mapping
21
+ from dataclasses import astuple, dataclass
22
+ from functools import cache
23
+ from pathlib import Path
24
+ from shlex import quote as sh_quote
25
+ from typing import TypeGuard
26
+
27
+ # Bumped by hand at release time; see RELEASING.md.
28
+ VERSION = "3.0.0"
29
+
30
+
31
+ class AgentState(enum.IntEnum):
32
+ """Agent states, ordered by urgency.
33
+
34
+ muster reads vtmux's native ``#{session_program_state}`` per session: the
35
+ OSC 7501 states blocked, error, working, done and idle, rolled up to the
36
+ strongest across the session's panes. Empty (a plain tmux, or no pane
37
+ reports) means no state; idle shows no state either. ``waiting`` and
38
+ ``crashed`` only come from murmur's snapshot.
39
+ """
40
+
41
+ idle = 0 # counted in a session's breakdown; a row never shows it
42
+ waiting = 1
43
+ working = 2
44
+ done = 3
45
+ blocked = 4
46
+ error = 5
47
+ crashed = 6
48
+
49
+ @classmethod
50
+ def parse(cls, raw: str) -> AgentState | None:
51
+ if raw not in OSC_7501_STATES:
52
+ return None
53
+ state = cls[raw]
54
+ # An idle session shows no state, as before; only counts mention idle.
55
+ return None if state is cls.idle else state
56
+
57
+
58
+ # The only values #{session_program_state} may carry; murmur-only waiting and
59
+ # crashed are not among them.
60
+ OSC_7501_STATES = frozenset({"blocked", "error", "working", "done", "idle"})
61
+
62
+ # THEME BEGIN: muster-state-glyphs
63
+ # Nerd Font glyphs, the same shapes murmur's dash uses per state.
64
+ STATE_GLYPH: dict[AgentState, str] = {
65
+ AgentState.crashed: "\uf057", # fa-times-circle
66
+ AgentState.error: "\uf071", # fa-exclamation-triangle
67
+ AgentState.blocked: "\uf075", # fa-comment
68
+ AgentState.done: "\uf058", # fa-check-circle
69
+ AgentState.working: "\uf04b", # fa-play
70
+ AgentState.waiting: "\uf252", # fa-hourglass-half
71
+ AgentState.idle: "\uf186", # fa-moon-o
72
+ }
73
+ # THEME END: muster-state-glyphs
74
+
75
+ ATTENTION_STATES = frozenset({AgentState.blocked, AgentState.error, AgentState.crashed})
76
+
77
+
78
+ # While set, every tmux call names this exact socket instead of following an
79
+ # alias ($TMUX, a symlink) that could be retargeted after a proof was made.
80
+ PINNED_SOCKET: str | None = None
81
+
82
+
83
+ @contextlib.contextmanager
84
+ def pinned_server(socket: str) -> Generator[None, None, None]:
85
+ global PINNED_SOCKET
86
+ previous, PINNED_SOCKET = PINNED_SOCKET, socket
87
+ try:
88
+ yield
89
+ finally:
90
+ PINNED_SOCKET = previous
91
+
92
+
93
+ def tmux_socket_args() -> tuple[str, ...]:
94
+ """``-S``/``-L`` args for an isolated server; empty for the default.
95
+
96
+ ``MUSTER_TMUX_SOCKET_PATH`` and ``MUSTER_TMUX_SOCKET_NAME`` exist for tests.
97
+ """
98
+ if PINNED_SOCKET:
99
+ return ("-S", PINNED_SOCKET)
100
+ if path := os.environ.get("MUSTER_TMUX_SOCKET_PATH"):
101
+ return ("-S", path)
102
+ if name := os.environ.get("MUSTER_TMUX_SOCKET_NAME"):
103
+ return ("-L", name)
104
+ return ()
105
+
106
+
107
+ def tmux_cmd(
108
+ *args: str, check: bool = True, capture: bool = True
109
+ ) -> subprocess.CompletedProcess[str]:
110
+ return subprocess.run(
111
+ ["tmux", *tmux_socket_args(), *args],
112
+ check=check,
113
+ text=True,
114
+ capture_output=capture,
115
+ )
116
+
117
+
118
+ def tmux_bytes(*args: str) -> subprocess.CompletedProcess[bytes]:
119
+ """tmux output as bytes: text mode turns a CR in a path into a newline."""
120
+ return subprocess.run(
121
+ ["tmux", *tmux_socket_args(), *args], check=False, capture_output=True
122
+ )
123
+
124
+
125
+ def server_running() -> bool:
126
+ return tmux_cmd("list-sessions", check=False).returncode == 0
127
+
128
+
129
+ def systemd_cgroup(proc_cgroup: str) -> str:
130
+ """The systemd cgroup path from ``/proc/<pid>/cgroup`` text, or "".
131
+
132
+ Hybrid hosts track units in the ``name=systemd`` v1 hierarchy; pure v2
133
+ hosts have only the ``0::`` line.
134
+ """
135
+ paths = dict(
136
+ line.split(":", 2)[1:]
137
+ for line in proc_cgroup.splitlines()
138
+ if line.count(":") >= 2
139
+ )
140
+ return paths.get("name=systemd", paths.get("", ""))
141
+
142
+
143
+ def in_user_manager(proc_cgroup: str) -> bool:
144
+ """True when the cgroup belongs to a unit of the user's systemd manager.
145
+
146
+ That is where a server inherits a service's lifetime, e.g. a shell in a
147
+ ``foot --server`` window. A login shell (ssh, tty) sits in logind's
148
+ ``session-N.scope`` instead, which survives logout as an abandoned scope
149
+ while ``user@UID.service`` is stopped once the last session ends, so a
150
+ server started there must stay put.
151
+ """
152
+ return "/user@" in systemd_cgroup(proc_cgroup)
153
+
154
+
155
+ def start_server_in_own_scope(new_session: tuple[str, ...]) -> bool:
156
+ """Start the tmux server in its own systemd scope; False if not done.
157
+
158
+ The server forks off whoever ran ``tmux`` and stays in that process's
159
+ cgroup. Under a user service, stopping or restarting that service kills
160
+ every session; a transient scope gives the server its own cgroup. Outside
161
+ the user manager (macOS, ssh and tty logins, containers) or when
162
+ systemd-run fails, this returns False and the caller runs plain tmux.
163
+ """
164
+ try:
165
+ proc_cgroup = Path("/proc/self/cgroup").read_text()
166
+ except OSError:
167
+ return False
168
+ if not (in_user_manager(proc_cgroup) and shutil.which("systemd-run")):
169
+ return False
170
+ # No expansion: tmux must get session names and paths containing "$"
171
+ # verbatim. systemd < 254 rejects the flag and we fall back.
172
+ cmd = ("systemd-run", "--user", "--scope", "--quiet", "--collect")
173
+ result = subprocess.run(
174
+ [*cmd, "--expand-environment=no", "tmux", *tmux_socket_args(), *new_session],
175
+ check=False,
176
+ capture_output=True,
177
+ )
178
+ return result.returncode == 0
179
+
180
+
181
+ # Room for three "glyph+count" groups; the header and every row share it.
182
+ STATE_WIDTH = 11
183
+ # Window and pane counts of a live session ("3w 5p").
184
+ COUNTS_WIDTH = 7
185
+ # Agents view columns after the label.
186
+ MUX_WIDTH = 4
187
+ STREAM_WIDTH = 16
188
+ HOST_WIDTH = 12
189
+ AGE_WIDTH = 4
190
+ # Every row starts with a marker, an icon (or state glyph) and a space.
191
+ PREFIX_WIDTH = 3
192
+
193
+
194
+ def cell_width(text: str) -> int:
195
+ """Terminal cells TEXT takes: wide (CJK) characters two, combining marks
196
+ and zero-width characters none."""
197
+ width = 0
198
+ for ch in text:
199
+ if unicodedata.combining(ch) or unicodedata.category(ch) in {"Cf", "Mn", "Me"}:
200
+ continue
201
+ width += 2 if unicodedata.east_asian_width(ch) in {"W", "F"} else 1
202
+ return width
203
+
204
+
205
+ def fit(text: str, width: int, *, keep: str = "end") -> str:
206
+ """TEXT in exactly WIDTH cells: padded, or cut with an ellipsis.
207
+
208
+ KEEP says what survives a cut: the start ("end": cut the end), the tail
209
+ ("start": cut the start, for paths), or both ends of a slash-separated
210
+ name ("middle": projects/…/demo).
211
+ """
212
+ if width <= 0:
213
+ return ""
214
+ if cell_width(text) <= width:
215
+ return text + " " * (width - cell_width(text))
216
+ if keep == "middle" and "/" in text:
217
+ # The leaf (last component) is what tells sessions apart: keep it
218
+ # whole and shorten the start; only a leaf too long for the column
219
+ # is cut itself.
220
+ leaf = text.rsplit("/", 1)[1]
221
+ room = width - cell_width(leaf) - 2 # "…/"
222
+ if room < 1:
223
+ return fit(leaf, width)
224
+ head = ""
225
+ for ch in text:
226
+ if cell_width(head + ch) > room:
227
+ break
228
+ head += ch
229
+ return fit(f"{head}\u2026/{leaf}", width)
230
+ if keep == "start":
231
+ out = ""
232
+ for ch in reversed(text):
233
+ if cell_width(ch + out) > width - 1:
234
+ break
235
+ out = ch + out
236
+ return fit("\u2026" + out, width)
237
+ out = ""
238
+ for ch in text:
239
+ if cell_width(out + ch) > width - 1:
240
+ break
241
+ out += ch
242
+ return fit(out + "\u2026", width)
243
+
244
+
245
+ @dataclass(frozen=True)
246
+ class Layout:
247
+ """Column plan for one terminal width. Rows and header both use it.
248
+
249
+ The list gets what the preview leaves: the preview sits right of the list
250
+ on wide screens, below it under 120 columns, and starts hidden (ctrl-/
251
+ shows it) under 80. The name column grows from 16 to 40 cells; on narrow
252
+ lists the counts column goes first, then the path; the state cell shrinks
253
+ to the strongest groups.
254
+ """
255
+
256
+ columns: int
257
+
258
+ @property
259
+ def preview(self) -> str:
260
+ if self.columns >= 120:
261
+ return "right"
262
+ return "down" if self.columns >= 80 else "hidden"
263
+
264
+ @property
265
+ def preview_window(self) -> str:
266
+ return {
267
+ "right": "right,55%,border-left",
268
+ "down": "down,45%,border-top",
269
+ "hidden": "down,45%,border-top,hidden",
270
+ }[self.preview]
271
+
272
+ @property
273
+ def row_width(self) -> int:
274
+ """Cells a row may take: the list's width less fzf's pointer gutter
275
+ and scrollbar, and its border and padding outside a popup."""
276
+ listed = self.columns
277
+ if self.preview == "right":
278
+ listed -= math.ceil(self.columns * 0.55) + 1
279
+ margin = 5 + (4 if fzf_border() == "rounded" else 0)
280
+ return max(listed - margin, 20)
281
+
282
+ @property
283
+ def name_width(self) -> int:
284
+ return min(max(int(self.row_width * 0.35), 16), 40)
285
+
286
+ @property
287
+ def _rest(self) -> int:
288
+ return self.row_width - PREFIX_WIDTH - self.name_width - 1
289
+
290
+ @property
291
+ def state_width(self) -> int:
292
+ wide = STATE_WIDTH + 1 + COUNTS_WIDTH + 1 + 12
293
+ return STATE_WIDTH if self._rest >= wide else 5
294
+
295
+ @property
296
+ def show_counts(self) -> bool:
297
+ return self._rest - self.state_width - 1 >= COUNTS_WIDTH + 1 + 12
298
+
299
+ @property
300
+ def path_width(self) -> int:
301
+ """Cells for the path (and its "+N" note); 0 drops the column."""
302
+ width = self._rest - self.state_width - 1
303
+ width -= (COUNTS_WIDTH + 1) * self.show_counts
304
+ return width if width >= 8 else 0
305
+
306
+ def agent_columns(
307
+ self, mux: bool, stream: bool, host: bool
308
+ ) -> tuple[bool, bool, bool]:
309
+ """Which of the agents view's mux, stream and host columns fit; host
310
+ goes first, then stream, then mux."""
311
+ room = self._rest - AGE_WIDTH
312
+
313
+ def need() -> int:
314
+ return (
315
+ (MUX_WIDTH + 1) * mux
316
+ + (STREAM_WIDTH + 1) * stream
317
+ + (HOST_WIDTH + 1) * host
318
+ )
319
+
320
+ if host and room < need():
321
+ host = False
322
+ if stream and room < need():
323
+ stream = False
324
+ if mux and room < need():
325
+ mux = False
326
+ return mux, stream, host
327
+
328
+
329
+ def terminal_columns() -> int:
330
+ """fzf's width for reloads and previews ($FZF_COLUMNS), else the
331
+ terminal's (the popup's, before fzf starts)."""
332
+ with contextlib.suppress(KeyError, ValueError):
333
+ return int(os.environ["FZF_COLUMNS"])
334
+ return shutil.get_terminal_size((160, 40)).columns
335
+
336
+
337
+ LAYOUT = Layout(160)
338
+
339
+
340
+ def set_layout(columns: int) -> None:
341
+ global LAYOUT
342
+ LAYOUT = Layout(columns)
343
+
344
+
345
+ DEFAULT_SPLIT = ""
346
+ CONFIG_PATH = Path(
347
+ os.environ.get("MUSTER_CONFIG")
348
+ or Path(os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config")
349
+ / "muster"
350
+ / "config.toml"
351
+ )
352
+ STATE_DIR = (
353
+ Path(os.environ.get("XDG_STATE_HOME") or Path.home() / ".local" / "state") / "muster"
354
+ )
355
+ LAST_FILE = STATE_DIR / "last"
356
+
357
+ # Picker-row source icons. Unrelated to STATE_GLYPH; these mark where an
358
+ # entry came from.
359
+ KIND_ICON = {
360
+ "default": "★",
361
+ "tmux": "●",
362
+ "rex": "■",
363
+ "zoxide": "◦",
364
+ "find": "·",
365
+ "agent": "◈",
366
+ }
367
+
368
+ # THEME BEGIN: muster-palette
369
+ CATPPUCCIN = {
370
+ "red": "#f38ba8",
371
+ "maroon": "#eba0ac",
372
+ "peach": "#fab387",
373
+ "teal": "#94e2d5",
374
+ "sky": "#89dceb",
375
+ "sapphire": "#74c7ec",
376
+ "lavender": "#b4befe",
377
+ "text": "#cdd6f4",
378
+ "subtext0": "#a6adc8",
379
+ "overlay0": "#6c7086",
380
+ "surface0": "#313244",
381
+ "base": "#1e1e2e",
382
+ }
383
+ # THEME END: muster-palette
384
+
385
+ # (foreground, bold) per row state. Working and waiting keep the kind colour.
386
+ STATE_STYLE: dict[AgentState | None, tuple[str, bool]] = {
387
+ AgentState.crashed: (CATPPUCCIN["red"], True),
388
+ AgentState.error: (CATPPUCCIN["maroon"], True),
389
+ AgentState.blocked: (CATPPUCCIN["peach"], True),
390
+ AgentState.done: (CATPPUCCIN["teal"], False),
391
+ }
392
+ KIND_FG: dict[str, str] = {
393
+ "default": CATPPUCCIN["lavender"],
394
+ "tmux": CATPPUCCIN["sky"],
395
+ "rex": CATPPUCCIN["teal"],
396
+ "zoxide": CATPPUCCIN["sapphire"],
397
+ "find": CATPPUCCIN["subtext0"],
398
+ "agent": CATPPUCCIN["lavender"],
399
+ }
400
+
401
+ FZF_BORDER_LABEL = " sessions "
402
+ UNDERLINE = "\x1b[4m"
403
+ RESET = "\x1b[0m"
404
+
405
+
406
+ class ConfigError(ValueError):
407
+ pass
408
+
409
+
410
+ @dataclass(frozen=True)
411
+ class SessionConfig:
412
+ name: str
413
+ path: str
414
+ startup: str = ""
415
+ split: str = DEFAULT_SPLIT
416
+
417
+
418
+ @dataclass(frozen=True)
419
+ class Config:
420
+ sessions: tuple[SessionConfig, ...]
421
+ blacklist: frozenset[str]
422
+ noisy_basenames: frozenset[str]
423
+ find_max_depth: int
424
+ preview_command: str
425
+ # When the picker is launched in `all` mode and the number of live tmux
426
+ # sessions is >= this threshold, the initial view auto-switches to `sessions`
427
+ # (pinned and live). 0 disables the auto-switch. The fzf reload binds
428
+ # (^a/^s/^f) are unaffected; the user can still pull up the merged
429
+ # view with ^a after the picker is open.
430
+ live_session_threshold: int = 0
431
+ # Pass `--exact` to fzf so query tokens match as literal substrings
432
+ # instead of fzf's default scattered-character fuzzy. Prefix a token
433
+ # with `'` to escape back to fuzzy for that token. Default true keeps
434
+ # the strict behavior; flip to false in the config for classic fuzzy.
435
+ fzf_exact: bool = True
436
+
437
+
438
+ # Picker-row schema. The first field is the rendered (ANSI-styled) display
439
+ # text fzf shows; the rest are payload fields parsed back out of the
440
+ # selected row. Reordering or adding to this list updates both `to_fzf_row`
441
+ # and `from_fzf_row` at once, so the producer and consumer can never drift.
442
+ FZF_ROW_FIELDS: tuple[str, ...] = (
443
+ "display", # synthetic: rendered text from visible_text()
444
+ "kind",
445
+ "session_name",
446
+ "path",
447
+ "startup",
448
+ "split",
449
+ "host", # agent rows: murmur host name
450
+ "pane", # agent rows: tmux pane id
451
+ "jump_target", # agent rows: murmur's opaque token for `murmur jump`
452
+ "here", # agent rows: "1" when the pane is on the tmux server muster talks to
453
+ "socket", # agent rows: the socket that proof was made against
454
+ "session_id", # live session rows: tmux's $N id, the only exact kill target
455
+ )
456
+
457
+
458
+ # First column of every row: where the invoking client is, and sessions other
459
+ # clients have attached.
460
+ CURRENT_MARK = "◆"
461
+ ATTACHED_MARK = "◇"
462
+
463
+
464
+ def marker_cell(marker: str) -> str:
465
+ if marker == "current":
466
+ return ansi_style(CURRENT_MARK, fg=CATPPUCCIN["text"], bold=True)
467
+ if marker == "attached":
468
+ return ansi_style(ATTACHED_MARK, fg=CATPPUCCIN["overlay0"])
469
+ return " "
470
+
471
+
472
+ ROW_ESCAPES = {"\\": "\\\\", "\t": "\\t", "\r": "\\r", "\n": "\\n"}
473
+ ROW_UNESCAPES = {v[1]: k for k, v in ROW_ESCAPES.items()}
474
+
475
+
476
+ def row_escape(value: str) -> str:
477
+ """One picker-row field with no tab, CR or LF left in it: a tab would
478
+ shift every later field, a line break would split the row."""
479
+ return re.sub(r"[\\\t\r\n]", lambda m: ROW_ESCAPES[m[0]], value)
480
+
481
+
482
+ def row_unescape(value: str) -> str:
483
+ """Undo row_escape, for a field read back from a row or an fzf {N}."""
484
+ return re.sub(r"\\(.)", lambda m: ROW_UNESCAPES.get(m[1], m[0]), value, flags=re.S)
485
+
486
+
487
+ def counts_cell(windows: int, panes: int) -> str:
488
+ """Window and pane counts ("3w 5p"); just the windows when both do not fit."""
489
+ both = f"{windows}w {panes}p"
490
+ if len(both) <= COUNTS_WIDTH:
491
+ return both
492
+ return f"{windows}w" if windows <= 99 else "99+w"
493
+
494
+
495
+ def state_cell(
496
+ counts: tuple[tuple[AgentState, int], ...], width: int = STATE_WIDTH
497
+ ) -> str:
498
+ """Per-state agent counts, strongest first, within WIDTH.
499
+
500
+ No state vanishes silently: groups that do not fit collapse into "+N", the
501
+ number of agents they hold. A count above 99 reads "99+".
502
+ """
503
+ groups = [f"{STATE_GLYPH[st]}{n if n <= 99 else '99+'}" for st, n in counts]
504
+ if len(" ".join(groups)) <= width:
505
+ return " ".join(groups)
506
+ for keep in range(len(groups) - 1, -1, -1):
507
+ rest = sum(n for _, n in counts[keep:])
508
+ cell = " ".join([*groups[:keep], f"+{rest}"])
509
+ if len(cell) <= width:
510
+ return cell
511
+ return f"+{sum(n for _, n in counts)}"
512
+
513
+
514
+ @dataclass(frozen=True)
515
+ class Entry:
516
+ kind: str
517
+ name: str
518
+ session_name: str
519
+ path: str = ""
520
+ startup: str = ""
521
+ split: str = ""
522
+ worst_state: AgentState | None = None
523
+ is_running: bool = False
524
+ # murmur's per-state agent counts for a session row, strongest first.
525
+ agent_counts: tuple[tuple[AgentState, int], ...] = ()
526
+ host: str = ""
527
+ pane: str = ""
528
+ jump_target: str = ""
529
+ here: str = ""
530
+ socket: str = ""
531
+ detail: str = "" # shown where a path would be (agent rows)
532
+ marker: str = "" # "current", "attached" or "": see marker_cell
533
+ text: str = "" # pre-rendered columns (agents view); replaces the layout
534
+ extra: str = "" # dim note after the path ("+2": windows in other dirs)
535
+ counts: str = "" # live sessions: counts_cell
536
+ session_id: str = ""
537
+
538
+ @property
539
+ def icon(self) -> str:
540
+ return KIND_ICON[self.kind]
541
+
542
+ @property
543
+ def display_path(self) -> str:
544
+ if self.detail:
545
+ return self.detail
546
+ if not self.path:
547
+ return ""
548
+ return tildify(self.path)
549
+
550
+ def visible_text(self) -> str:
551
+ note = self.extra
552
+ if self.text:
553
+ text = self.text
554
+ else:
555
+ layout = LAYOUT
556
+ # Text is escaped before it is fitted: the escaped form is what
557
+ # fzf shows, so that is what must fit (see to_fzf_row).
558
+ name = fit(row_escape(self.name), layout.name_width, keep="middle")
559
+ ws = self.worst_state
560
+ if self.agent_counts:
561
+ cell = state_cell(self.agent_counts, layout.state_width)
562
+ else:
563
+ cell = STATE_GLYPH[ws] if ws is not None else " "
564
+ text = f"{self.icon} {name} {fit(cell, layout.state_width)} "
565
+ if layout.show_counts:
566
+ text += fit(self.counts, COUNTS_WIDTH) + " "
567
+ room = layout.path_width - (len(note) + 1 if note else 0)
568
+ if not layout.path_width or room < 4:
569
+ note = ""
570
+ room = layout.path_width - (len(note) + 1 if note else 0)
571
+ if self.display_path and room > 0:
572
+ text += fit(row_escape(self.display_path), room, keep="start")
573
+ text = text.rstrip()
574
+ dim = " " + ansi_style(note, fg=CATPPUCCIN["overlay0"]) if note else ""
575
+ return marker_cell(self.marker) + self.styled(text) + dim
576
+
577
+ def styled(self, text: str) -> str:
578
+ # Agent states win over the kind colour: a blocked or crashed agent
579
+ # must still show when the session is also pinned or live.
580
+ if style := STATE_STYLE.get(self.worst_state):
581
+ fg, bold = style
582
+ return ansi_style(text, fg=fg, bg=CATPPUCCIN["surface0"], bold=bold)
583
+ style_kind = "tmux" if self.kind == "default" and self.is_running else self.kind
584
+ fg = KIND_FG.get(style_kind)
585
+ if fg is None:
586
+ return text
587
+ return ansi_style(text, fg=fg)
588
+
589
+ def to_fzf_row(self) -> str:
590
+ values = {
591
+ "display": self.visible_text(),
592
+ "kind": self.kind,
593
+ "session_name": self.session_name,
594
+ "path": self.path,
595
+ "startup": self.startup,
596
+ "split": self.split,
597
+ "host": self.host,
598
+ "pane": self.pane,
599
+ "jump_target": self.jump_target,
600
+ "here": self.here,
601
+ "socket": self.socket,
602
+ "session_id": self.session_id,
603
+ }
604
+ # The display is escaped piece by piece in visible_text, before its
605
+ # columns are fitted; escaping it again would widen it past the list.
606
+ return "\t".join(
607
+ values[name] if name == "display" else row_escape(values[name])
608
+ for name in FZF_ROW_FIELDS
609
+ )
610
+
611
+ @classmethod
612
+ def from_fzf_row(cls, row: str) -> dict[str, str]:
613
+ """Parse a tab-joined picker row back into a ``{field: value}`` dict.
614
+
615
+ Returns a dict rather than an ``Entry`` because the rendered display
616
+ text is one-way (ANSI styled) and downstream consumers only need the
617
+ payload fields. Raises ``ConfigError`` on field-count mismatch so
618
+ schema drift fails loudly in one place.
619
+ """
620
+ parts = row.split("\t")
621
+ if len(parts) != len(FZF_ROW_FIELDS):
622
+ raise ConfigError(
623
+ f"Invalid picker row: expected {len(FZF_ROW_FIELDS)} "
624
+ f"tab-separated fields, got {len(parts)}"
625
+ )
626
+ fields = dict(zip(FZF_ROW_FIELDS, parts, strict=True))
627
+ # The display is stored as shown (see to_fzf_row); the rest unescape.
628
+ return {k: v if k == "display" else row_unescape(v) for k, v in fields.items()}
629
+
630
+
631
+ @dataclass(frozen=True)
632
+ class EntryPayload:
633
+ """Typed view of the fields that survive an Entry's fzf round-trip.
634
+
635
+ ``Entry`` carries display-only fields (icon, is_running, rendered
636
+ text) that aren't worth re-deriving on selection. Anything the
637
+ ``connect_*`` path actually needs lives here, so consumers don't have
638
+ to reach into the dict-shaped output of :meth:`Entry.from_fzf_row`.
639
+ """
640
+
641
+ session_name: str
642
+ kind: str = ""
643
+ path: str | None = None
644
+ startup: str | None = None
645
+ split: str = DEFAULT_SPLIT
646
+ host: str = ""
647
+ pane: str = ""
648
+ jump_target: str = ""
649
+ here: str = ""
650
+ socket: str = ""
651
+ session_id: str = ""
652
+
653
+ @classmethod
654
+ def from_fzf_row(cls, row: str) -> EntryPayload:
655
+ fields = Entry.from_fzf_row(row)
656
+ return cls(
657
+ session_name=fields["session_name"],
658
+ kind=fields["kind"],
659
+ path=fields["path"] or None,
660
+ startup=fields["startup"] or None,
661
+ split=fields["split"] or DEFAULT_SPLIT,
662
+ host=fields["host"],
663
+ pane=fields["pane"],
664
+ jump_target=fields["jump_target"],
665
+ here=fields["here"],
666
+ socket=fields["socket"],
667
+ session_id=fields["session_id"],
668
+ )
669
+
670
+
671
+ def ansi_style(
672
+ text: str, *, fg: str | None = None, bg: str | None = None, bold: bool = False
673
+ ) -> str:
674
+ parts: list[str] = []
675
+ if bold:
676
+ parts.append("1")
677
+ if fg:
678
+ parts.append(f"38;2;{int(fg[1:3], 16)};{int(fg[3:5], 16)};{int(fg[5:7], 16)}")
679
+ if bg:
680
+ parts.append(f"48;2;{int(bg[1:3], 16)};{int(bg[3:5], 16)};{int(bg[5:7], 16)}")
681
+ if not parts:
682
+ return text
683
+ return f"\x1b[{';'.join(parts)}m{text}\x1b[0m"
684
+
685
+
686
+ def run(
687
+ cmd: list[str], *, check: bool = True, capture: bool = True
688
+ ) -> subprocess.CompletedProcess[str]:
689
+ return subprocess.run(cmd, check=check, text=True, capture_output=capture)
690
+
691
+
692
+ def exact_session_target(name: str) -> str:
693
+ return f"={name}"
694
+
695
+
696
+ def exact_pane_target(name: str, pane: str) -> str:
697
+ return f"={name}:{pane}"
698
+
699
+
700
+ def active_pane_target(name: str) -> str:
701
+ """The session's current window and active pane, whatever the base-index."""
702
+ return f"={name}:"
703
+
704
+
705
+ def tildify(path: str) -> str:
706
+ """Rewrite a leading home directory as ``~``; nothing else."""
707
+ home = str(Path.home()).rstrip("/")
708
+ if path == home:
709
+ return "~"
710
+ if home and path.startswith(home + "/"):
711
+ return "~" + path[len(home) :]
712
+ return path
713
+
714
+
715
+ def expand(path: str) -> str:
716
+ return str(Path(path).expanduser())
717
+
718
+
719
+ # Which row kind's icon marks each non-"all" view.
720
+ MODE_KIND = {"sessions": "tmux", "find": "find", "agents": "agent"}
721
+
722
+ # Leads the prompt while orchestrated (crew) agents are shown. The prompt is
723
+ # the toggle's only state: fzf hands it to a binding as $FZF_PROMPT, so it
724
+ # survives view switches (see fzf_action).
725
+ CREW_MARK = "crew "
726
+
727
+ # Prompt colour per state for the agents view's counts.
728
+ COUNT_FG: dict[AgentState, str] = {
729
+ **{state: fg for state, (fg, _) in STATE_STYLE.items() if state is not None},
730
+ AgentState.working: CATPPUCCIN["sky"],
731
+ AgentState.waiting: CATPPUCCIN["lavender"],
732
+ AgentState.idle: CATPPUCCIN["overlay0"],
733
+ }
734
+
735
+
736
+ def mode_glyph(mode: str) -> str:
737
+ # "all" is a synthetic mode that doesn't appear in KIND_ICON; the rest
738
+ # share their glyph with the per-entry kind icon for visual consistency.
739
+ return ">" if mode == "all" else KIND_ICON[MODE_KIND[mode]]
740
+
741
+
742
+ def prompt_text(
743
+ mode: str, crew: bool = False, counts: Mapping[AgentState, int] | None = None
744
+ ) -> str:
745
+ """The prompt: crew mark, view glyph, and in the agents view the number of
746
+ shown agents per state, strongest first."""
747
+ mark = CREW_MARK if crew else ""
748
+ shown = sorted((counts or {}).items(), key=lambda item: -item[0])
749
+ groups = " ".join(
750
+ ansi_style(f"{STATE_GLYPH[st]}{n}", fg=COUNT_FG[st]) for st, n in shown if n
751
+ )
752
+ return f"{mark}{mode_glyph(mode)} {groups}{' ' if groups else ''} "
753
+
754
+
755
+ def prompt_state(prompt: str) -> tuple[str, bool]:
756
+ """The (view, crew) a prompt built by prompt_text encodes."""
757
+ crew = prompt.startswith(CREW_MARK)
758
+ glyph = prompt.removeprefix(CREW_MARK)[:1]
759
+ views = {mode_glyph(mode): mode for mode in MODES}
760
+ return views.get(glyph, "all"), crew
761
+
762
+
763
+ @dataclass(frozen=True)
764
+ class AgentColumns:
765
+ mux: bool = False
766
+ stream: bool = False
767
+ host: bool = False
768
+
769
+
770
+ def header_text(
771
+ mode: str = "all",
772
+ *,
773
+ notice: str = "",
774
+ status: str = "",
775
+ columns: AgentColumns | None = None,
776
+ ) -> str:
777
+ """Header lines: murmur's session notice when a peer needs one, the key
778
+ legend, a status line (empty view, murmur missing), the column titles."""
779
+ items = [
780
+ ("all", "^a all"),
781
+ ("sessions", "^s sessions"),
782
+ ("agents", "^g crew" if mode == "agents" else "^g agents"),
783
+ ("find", "^f find"),
784
+ ]
785
+ legend = [
786
+ (label, CATPPUCCIN["sky" if view == mode else "subtext0"])
787
+ for view, label in items
788
+ ]
789
+ legend.append(("^x kill", CATPPUCCIN["subtext0"]))
790
+ if LAYOUT.preview == "hidden":
791
+ legend.append(("^/ preview", CATPPUCCIN["subtext0"]))
792
+ legend += [
793
+ (label, CATPPUCCIN["overlay0"]) for label in ("tab/s-tab move", "enter open")
794
+ ]
795
+ lines = [notice] if notice else []
796
+ lines += legend_lines(legend, LAYOUT.row_width - 2)
797
+ if status:
798
+ lines.append(" " + status)
799
+ nw = LAYOUT.name_width
800
+ if mode == "agents":
801
+ mux, stream, host = LAYOUT.agent_columns(
802
+ *(astuple(columns) if columns else (False, False, False))
803
+ )
804
+ titles = " " + fit("agent", nw)
805
+ if mux:
806
+ titles += " " + fit("mux", MUX_WIDTH)
807
+ if stream:
808
+ titles += " " + fit("stream", STREAM_WIDTH)
809
+ if host:
810
+ titles += " " + fit("host", HOST_WIDTH)
811
+ titles += " age"
812
+ else:
813
+ titles = f" {fit('session', nw)} {fit('state', LAYOUT.state_width)} "
814
+ if LAYOUT.show_counts:
815
+ titles += fit("windows", COUNTS_WIDTH) + " "
816
+ if LAYOUT.path_width:
817
+ titles += "path"
818
+ lines.append(f"{UNDERLINE}{titles.rstrip()}{RESET}")
819
+ return "\n".join(lines)
820
+
821
+
822
+ def legend_lines(items: list[tuple[str, str]], width: int) -> list[str]:
823
+ """The key legend, wrapped so no line is wider than WIDTH cells."""
824
+ lines: list[list[tuple[str, str]]] = [[]]
825
+ used = 0
826
+ for label, colour in items:
827
+ need = len(label) + (1 if lines[-1] else 0)
828
+ if lines[-1] and used + need > width:
829
+ lines.append([])
830
+ used, need = 0, len(label)
831
+ lines[-1].append((label, colour))
832
+ used += need
833
+ return [
834
+ " " + " ".join(ansi_style(label, fg=colour) for label, colour in line)
835
+ for line in lines
836
+ ]
837
+
838
+
839
+ def fzf_border(env: Mapping[str, str] = os.environ) -> str:
840
+ """Avoid a second border inside tmux's already-bordered popup."""
841
+ return "none" if env.get("TMUX") and not env.get("TMUX_PANE") else "rounded"
842
+
843
+
844
+ def sanitize_session_part(part: str) -> str:
845
+ # tmux normalizes dots in session names to underscores, and dotted target
846
+ # names are parsed as window/pane separators. Generate the normalized form
847
+ # ourselves so create and attach paths agree.
848
+ cleaned = re.sub(r"[^A-Za-z0-9_-]+", "-", part.replace(".", "_"))
849
+ return re.sub(r"-+", "-", cleaned).strip("-")
850
+
851
+
852
+ def session_name_for_path(path: str) -> str:
853
+ resolved = Path(path).expanduser().resolve()
854
+ home = Path.home().resolve()
855
+ try:
856
+ parts = resolved.relative_to(home).parts
857
+ except ValueError:
858
+ parts = tuple(
859
+ part for part in resolved.parts if part not in {resolved.anchor, "/"}
860
+ )
861
+ sanitized = [sanitize_session_part(part) for part in parts]
862
+ sanitized = [part for part in sanitized if part]
863
+ return "/".join(sanitized) or "session"
864
+
865
+
866
+ def display_name_for_path(path: str) -> str:
867
+ return Path(path).expanduser().name or session_name_for_path(path)
868
+
869
+
870
+ def zoxide_paths() -> list[str]:
871
+ if not shutil.which("zoxide"):
872
+ return []
873
+ result = run(["zoxide", "query", "--list"], check=False)
874
+ if result.returncode != 0:
875
+ return []
876
+ return [line.strip() for line in result.stdout.split("\n") if line.strip()]
877
+
878
+
879
+ def glob_escape(name: str) -> str:
880
+ """Make NAME match literally as a find -name pattern."""
881
+ return re.sub(r"([*?\[\\])", r"\\\1", name)
882
+
883
+
884
+ def find_paths(config: Config) -> list[str]:
885
+ home = str(Path.home())
886
+ if shutil.which("fd"):
887
+ cmd = ["fd", "-0", "-H", "-d", str(config.find_max_depth), "-t", "d"]
888
+ for name in sorted(config.blacklist):
889
+ cmd.extend(["-E", name])
890
+ cmd.extend([".", home])
891
+ else:
892
+ cmd = ["find", home, "-mindepth", "1", "-maxdepth", str(config.find_max_depth)]
893
+ # Prune blacklisted dirs so find never descends into them.
894
+ names = sorted(config.blacklist)
895
+ if names:
896
+ cmd.append("(")
897
+ for i, name in enumerate(names):
898
+ cmd.extend(["-o"] * (i > 0) + ["-name", glob_escape(name)])
899
+ cmd.extend([")", "-prune", "-o"])
900
+ cmd.extend(["-type", "d", "-print0"])
901
+ result = run(cmd, check=False)
902
+ if result.returncode != 0:
903
+ return []
904
+ # NUL-separated: a path may hold \x1e or other bytes splitlines() breaks on.
905
+ # A path with a newline cannot be one picker row, so it is not offered.
906
+ return [
907
+ p for p in result.stdout.split("\0") if p and "\n" not in p and "\r" not in p
908
+ ]
909
+
910
+
911
+ def is_useful_path(path: str, *, mode: str, config: Config) -> bool:
912
+ p = Path(path).expanduser()
913
+ parts = p.parts
914
+ basename = p.name
915
+
916
+ if basename.startswith("."):
917
+ return False
918
+ # `parts` includes the basename, so a single pass against the union of
919
+ # both deny-lists subsumes the per-basename and per-segment checks the
920
+ # earlier version did separately.
921
+ blocked = config.blacklist | config.noisy_basenames
922
+ if any(part in blocked for part in parts):
923
+ return False
924
+
925
+ # Both sides must be resolved: on distros where /home symlinks to
926
+ # /var/home, comparing a resolved path against a bare Path.home() makes
927
+ # relative_to() raise for *every* path under $HOME, silently disabling
928
+ # the dotdir and zoxide-depth filters below.
929
+ home = Path.home().resolve()
930
+ try:
931
+ rel = p.resolve().relative_to(home)
932
+ rel_parts = rel.parts
933
+ if any(part.startswith(".") for part in rel_parts):
934
+ return False
935
+ if mode == "zoxide" and len(rel_parts) > 2:
936
+ return False
937
+ except OSError:
938
+ # resolve() touches the filesystem: unreadable parent, deleted cwd
939
+ # while resolving a relative path, ELOOP on platforms that still
940
+ # report it. Treat an unresolvable path as "no extra filtering".
941
+ pass
942
+ except ValueError:
943
+ # relative_to() when the resolved path is outside $HOME.
944
+ pass
945
+
946
+ return True
947
+
948
+
949
+ def require_str_list(value: object, key: str, path: Path) -> list[str]:
950
+ if not isinstance(value, list):
951
+ raise ConfigError(f"{path}: {key} must be an array of strings")
952
+ items = [item for item in value if isinstance(item, str)]
953
+ if len(items) != len(value):
954
+ raise ConfigError(f"{path}: {key} must be an array of strings")
955
+ return items
956
+
957
+
958
+ # Configs from earlier names, read with a warning until moved: tms (pre-2.0)
959
+ # and tsesh (pre-3.0, the name before muster).
960
+ LEGACY_CONFIG_PATH = Path.home() / ".config" / "tmux" / "tms.toml"
961
+ PRE_RENAME_CONFIG_PATH = Path.home() / ".config" / "tsesh" / "config.toml"
962
+ DEFAULT_BLACKLIST = (".cache", ".config", ".local", "Library", "tmp")
963
+ DEFAULT_NOISY = ("node_modules", "target", "dist", "build", ".git")
964
+
965
+
966
+ def default_preview_command() -> str:
967
+ if shutil.which("eza"):
968
+ return "eza --all --git --icons --color=always {path}"
969
+ return "ls -la {path}"
970
+
971
+
972
+ def config_path() -> Path | None:
973
+ """The config to read: ours, the pre-rename one with a warning, or none."""
974
+ if CONFIG_PATH.exists():
975
+ return CONFIG_PATH
976
+ if "MUSTER_CONFIG" in os.environ:
977
+ return None
978
+ for legacy in (PRE_RENAME_CONFIG_PATH, LEGACY_CONFIG_PATH):
979
+ if legacy.exists():
980
+ print(f"muster: reading {legacy}; move it to {CONFIG_PATH}", file=sys.stderr)
981
+ return legacy
982
+ return None
983
+
984
+
985
+ @cache
986
+ def load_config() -> Config:
987
+ path = config_path()
988
+ if path is None:
989
+ return Config(
990
+ sessions=(),
991
+ blacklist=frozenset(DEFAULT_BLACKLIST),
992
+ noisy_basenames=frozenset(DEFAULT_NOISY),
993
+ find_max_depth=2,
994
+ preview_command=default_preview_command(),
995
+ )
996
+ try:
997
+ with path.open("rb") as handle:
998
+ data = tomllib.load(handle)
999
+ except OSError as exc:
1000
+ raise ConfigError(f"Failed to read config: {path}: {exc}") from exc
1001
+ except tomllib.TOMLDecodeError as exc:
1002
+ raise ConfigError(f"Invalid TOML in {path}: {exc}") from exc
1003
+
1004
+ blacklist = require_str_list(
1005
+ data.get("blacklist", list(DEFAULT_BLACKLIST)), "blacklist", path
1006
+ )
1007
+ noisy_basenames = require_str_list(
1008
+ data.get("noisy_basenames", list(DEFAULT_NOISY)), "noisy_basenames", path
1009
+ )
1010
+ find_max_depth = data.get("find_max_depth", 2)
1011
+ preview_command = data.get("preview_command") or default_preview_command()
1012
+ sessions = data.get("sessions", [])
1013
+ live_session_threshold = data.get("live_session_threshold", 0)
1014
+ fzf_exact = data.get("fzf_exact", True)
1015
+ if not isinstance(find_max_depth, int) or find_max_depth < 0:
1016
+ raise ConfigError(f"{path}: find_max_depth must be a non-negative integer")
1017
+ if not isinstance(preview_command, str) or not preview_command:
1018
+ raise ConfigError(f"{path}: preview_command must be a non-empty string")
1019
+ if not isinstance(sessions, list):
1020
+ raise ConfigError(f"{path}: sessions must be an array")
1021
+ if (
1022
+ not isinstance(live_session_threshold, int)
1023
+ or isinstance(live_session_threshold, bool)
1024
+ or live_session_threshold < 0
1025
+ ):
1026
+ raise ConfigError(
1027
+ f"{path}: live_session_threshold must be a non-negative integer"
1028
+ )
1029
+ if not isinstance(fzf_exact, bool):
1030
+ raise ConfigError(f"{path}: fzf_exact must be a boolean")
1031
+
1032
+ out: list[SessionConfig] = []
1033
+ for session in sessions:
1034
+ if not isinstance(session, dict):
1035
+ raise ConfigError(f"{path}: each session must be an object")
1036
+ name = session.get("name")
1037
+ session_path = session.get("path")
1038
+ if not isinstance(name, str) or not name:
1039
+ raise ConfigError(f"{path}: session.name must be a non-empty string")
1040
+ if not isinstance(session_path, str) or not session_path:
1041
+ raise ConfigError(f"{path}: session.path must be a non-empty string")
1042
+ startup = session.get("startup", "")
1043
+ if not isinstance(startup, str):
1044
+ raise ConfigError(f"{path}: session.startup must be a string")
1045
+ split = session.get("split", DEFAULT_SPLIT)
1046
+ if split not in {DEFAULT_SPLIT, "vertical", "horizontal"}:
1047
+ raise ConfigError(
1048
+ f"{path}: session.split must be '', 'vertical', or 'horizontal'"
1049
+ )
1050
+ out.append(
1051
+ SessionConfig(name=name, path=session_path, startup=startup, split=split)
1052
+ )
1053
+
1054
+ return Config(
1055
+ sessions=tuple(out),
1056
+ blacklist=frozenset(blacklist),
1057
+ noisy_basenames=frozenset(noisy_basenames),
1058
+ find_max_depth=find_max_depth,
1059
+ preview_command=preview_command,
1060
+ live_session_threshold=live_session_threshold,
1061
+ fzf_exact=fzf_exact,
1062
+ )
1063
+
1064
+
1065
+ def effective_initial_mode(mode: str, live: Mapping[str, object]) -> str:
1066
+ """Resolve the picker's *opening* mode, applying the live-session threshold.
1067
+
1068
+ Only `all` (the default landing view) is eligible for auto-switching; if
1069
+ the caller explicitly asked for a specific mode we honor it. The threshold
1070
+ is read from config and 0 disables the behavior. fzf's reload binds use
1071
+ the original mode strings, so `^a` still pulls up the merged view.
1072
+ """
1073
+ if mode != "all":
1074
+ return mode
1075
+ threshold = load_config().live_session_threshold
1076
+ if threshold <= 0:
1077
+ return mode
1078
+ if len(live) >= threshold:
1079
+ return "sessions"
1080
+ return mode
1081
+
1082
+
1083
+ def build_path_entries(
1084
+ *,
1085
+ kind: str,
1086
+ paths: list[str],
1087
+ configured_paths: set[str],
1088
+ mode: str,
1089
+ config: Config,
1090
+ ) -> list[Entry]:
1091
+ configured_real_paths = {os.path.realpath(path) for path in configured_paths}
1092
+ seen_paths: set[str] = set()
1093
+ entries: list[Entry] = []
1094
+ for path in paths:
1095
+ full = expand(path)
1096
+ real = os.path.realpath(full)
1097
+ if (
1098
+ real in configured_real_paths
1099
+ or real in seen_paths
1100
+ or not is_useful_path(full, mode=mode, config=config)
1101
+ ):
1102
+ continue
1103
+ seen_paths.add(real)
1104
+ entries.append(
1105
+ Entry(
1106
+ kind=kind,
1107
+ name=display_name_for_path(full),
1108
+ session_name=session_name_for_path(full),
1109
+ path=full,
1110
+ )
1111
+ )
1112
+ return entries
1113
+
1114
+
1115
+ def murmur_command() -> str | None:
1116
+ return shutil.which(os.environ.get("MUSTER_MURMUR", "murmur"))
1117
+
1118
+
1119
+ def rex_command() -> str | None:
1120
+ cmd = os.environ.get("MUSTER_REX", "rex")
1121
+ return shutil.which(cmd) if cmd else None
1122
+
1123
+
1124
+ def in_rex(env: Mapping[str, str] = os.environ) -> bool:
1125
+ """True when running in a Rex pane (and not inside tmux)."""
1126
+ return (
1127
+ not env.get("TMUX")
1128
+ and env.get("TERM_PROGRAM") == "rex"
1129
+ and bool(env.get("REX_BLOCK") or env.get("REX_SESSION"))
1130
+ )
1131
+
1132
+
1133
+ def rex_target(env: Mapping[str, str] = os.environ) -> str:
1134
+ return env.get("REX_SESSION") or env.get("REX_BLOCK") or ""
1135
+
1136
+
1137
+ def rex_local_env() -> dict[str, str]:
1138
+ env = dict(os.environ)
1139
+ env.pop("REX_SERVER", None)
1140
+ return env
1141
+
1142
+
1143
+ RAISE_REX_JXA = (
1144
+ 'ObjC.import("AppKit"); '
1145
+ 'const a = $.NSRunningApplication.runningApplicationsWithBundleIdentifier("com.superlogical.rex"); '
1146
+ "if (a.count > 0) a.objectAtIndex(0).activateWithOptions("
1147
+ "$.NSApplicationActivateAllWindows | $.NSApplicationActivateIgnoringOtherApps);"
1148
+ )
1149
+
1150
+
1151
+ def raise_rex_app() -> None:
1152
+ """Best-effort raise of Rex.app on macOS when jumping from outside Rex."""
1153
+ if sys.platform != "darwin" or os.environ.get("TERM_PROGRAM") == "rex":
1154
+ return
1155
+ with contextlib.suppress(OSError):
1156
+ subprocess.run(
1157
+ ["osascript", "-l", "JavaScript", "-e", RAISE_REX_JXA],
1158
+ stdin=subprocess.DEVNULL,
1159
+ stdout=subprocess.DEVNULL,
1160
+ stderr=subprocess.DEVNULL,
1161
+ check=False,
1162
+ )
1163
+
1164
+
1165
+ def rex_call(
1166
+ *args: str, timeout: float | None = None
1167
+ ) -> subprocess.CompletedProcess[str] | None:
1168
+ """Run ``rex --autostart=false ARGS`` against this machine's server,
1169
+ output captured; None when rex is missing, cannot start, or times out."""
1170
+ exe = rex_command()
1171
+ if exe is None:
1172
+ return None
1173
+ try:
1174
+ return subprocess.run(
1175
+ [exe, "--autostart=false", *args],
1176
+ env=rex_local_env(),
1177
+ stdin=subprocess.DEVNULL,
1178
+ capture_output=True,
1179
+ text=True,
1180
+ timeout=timeout,
1181
+ check=False,
1182
+ )
1183
+ except (OSError, subprocess.TimeoutExpired):
1184
+ return None
1185
+
1186
+
1187
+ def json_object(text: str) -> dict:
1188
+ """TEXT as a JSON object, or {} for anything else."""
1189
+ try:
1190
+ value = json.loads(text)
1191
+ except ValueError:
1192
+ return {}
1193
+ return value if isinstance(value, dict) else {}
1194
+
1195
+
1196
+ def rex_json(*args: str, timeout: float | None = 2) -> dict:
1197
+ """``rex_call`` read as a JSON object, {} on any failure."""
1198
+ proc = rex_call(*args, timeout=timeout)
1199
+ return json_object(proc.stdout) if proc is not None and proc.returncode == 0 else {}
1200
+
1201
+
1202
+ def rex_report(proc: subprocess.CompletedProcess[str] | None, what: str) -> int:
1203
+ """Report a failed rex call (PROC None or nonzero); returns 1."""
1204
+ if proc is None:
1205
+ why = "rex is not installed" if rex_command() is None else "could not run rex"
1206
+ else:
1207
+ lines = proc.stderr.strip().splitlines()
1208
+ why = lines[0] if lines else f"exit {proc.returncode}"
1209
+ report_failure(f"{what}: {why}")
1210
+ return 1
1211
+
1212
+
1213
+ def rex_has_app() -> bool:
1214
+ """Whether this machine has a Rex.app to show a session in: a Rex.app
1215
+ running here (see rex_local_app_ids), or with $REX_CLIENT set, that app
1216
+ client by label or ID. A headless server (Linux, no app yet) has none."""
1217
+ want = os.environ.get("REX_CLIENT")
1218
+ if not want:
1219
+ return bool(rex_local_app_ids())
1220
+ clients = rex_json("--timeout", "1s", "client", "ls", "--json").get("clients")
1221
+ for entry in clients if isinstance(clients, list) else []:
1222
+ info = entry.get("info") if isinstance(entry, dict) else None
1223
+ if not isinstance(info, dict) or info.get("kind") != "app":
1224
+ continue
1225
+ if info.get("label") == want or str(entry.get("client_id", "")).endswith(want):
1226
+ return True
1227
+ return False
1228
+
1229
+
1230
+ def rex_sessions() -> list[tuple[str, str]]:
1231
+ """Live local Rex sessions as (session_id, label). [] when Rex is
1232
+ unavailable, and when no Rex.app is connected: rex has no terminal attach,
1233
+ so a session there is one no pick could show."""
1234
+ items = rex_json("--timeout", "1s", "ls", "--json").get("sessions")
1235
+ sessions = [
1236
+ (sid, clean_field(item.get("label")) or sid)
1237
+ for item in (items if isinstance(items, list) else [])
1238
+ if isinstance(item, dict) and (sid := clean_field(item.get("session_id")))
1239
+ ]
1240
+ return sessions if sessions and rex_has_app() else []
1241
+
1242
+
1243
+ def rex_session_info(target: str) -> dict:
1244
+ """``rex session inspect`` of the session holding TARGET (a session or
1245
+ block id), or {}."""
1246
+ if not target:
1247
+ return {}
1248
+ return rex_json("--timeout", "1s", "session", "inspect", target, "--json")
1249
+
1250
+
1251
+ def rex_session_windows(target: str) -> tuple[str, list[str]]:
1252
+ """(session_id, window ids in order) of the Rex session holding TARGET,
1253
+ or ("", []) when Rex cannot say."""
1254
+ info = rex_session_info(target)
1255
+ windows = info.get("windows")
1256
+ ids = [
1257
+ w["window_id"]
1258
+ for w in (windows if isinstance(windows, list) else [])
1259
+ if isinstance(w, dict) and isinstance(w.get("window_id"), str)
1260
+ ]
1261
+ return clean_field(info.get("session_id")), ids
1262
+
1263
+
1264
+ def pid_runs_rex_app(pid: object) -> bool:
1265
+ """Whether PID is a Rex.app process on this machine. A Rex.app on another
1266
+ machine reaches this server through ssh, so its client's pid is sshd's."""
1267
+ if not isinstance(pid, int) or pid <= 0:
1268
+ return False
1269
+ try:
1270
+ out = subprocess.run(
1271
+ ["ps", "-p", str(pid), "-o", "command="],
1272
+ stdin=subprocess.DEVNULL,
1273
+ capture_output=True,
1274
+ text=True,
1275
+ timeout=2,
1276
+ check=False,
1277
+ ).stdout
1278
+ except (OSError, subprocess.TimeoutExpired):
1279
+ return False
1280
+ return "Rex.app/" in out
1281
+
1282
+
1283
+ def rex_local_app_state() -> tuple[list[str], bool]:
1284
+ """(local app client IDs, whether other app clients share the server).
1285
+
1286
+ Another machine's Rex.app attached to this server over ssh is left out of
1287
+ the local list: a session shown there would be on someone else's screen."""
1288
+ clients = rex_json("--timeout", "1s", "client", "ls", "--json").get("clients")
1289
+ ids = []
1290
+ apps = 0
1291
+ for entry in clients if isinstance(clients, list) else []:
1292
+ if not isinstance(entry, dict):
1293
+ continue
1294
+ info = entry.get("info")
1295
+ if not isinstance(info, dict) or info.get("kind") != "app":
1296
+ continue
1297
+ apps += 1
1298
+ principal = entry.get("principal")
1299
+ pid = principal.get("pid") if isinstance(principal, dict) else None
1300
+ if pid_runs_rex_app(pid) and (cid := clean_field(entry.get("client_id"))):
1301
+ ids.append(cid)
1302
+ return ids, apps > 1
1303
+
1304
+
1305
+ def rex_local_app_ids() -> list[str]:
1306
+ """Client IDs of the Rex.app clients running on this machine."""
1307
+ return rex_local_app_state()[0]
1308
+
1309
+
1310
+ def rex_select_session(session_id: str, window_id: str = "") -> int:
1311
+ """Show SESSION_ID (and WINDOW_ID) in this machine's Rex.app, then raise it.
1312
+
1313
+ Only a Rex.app running here will do, whatever else is attached to the
1314
+ server. $REX_CLIENT names one explicitly and skips that check. When other
1315
+ app clients share the server, `-C` pins the select to the local one."""
1316
+ client = os.environ.get("REX_CLIENT") or ""
1317
+ if not client:
1318
+ local, shared = rex_local_app_state()
1319
+ if not local:
1320
+ report_failure(
1321
+ f"rex session.select {session_id}: Rex.app is not connected to this"
1322
+ " machine's Rex server; set $REX_CLIENT to name the one to use"
1323
+ )
1324
+ return 1
1325
+ if len(local) > 1:
1326
+ report_failure(
1327
+ f"rex session.select {session_id}: several Rex.app run on this machine;"
1328
+ " set $REX_CLIENT to the label of the one to use"
1329
+ )
1330
+ return 1
1331
+ if shared:
1332
+ client = local[0]
1333
+
1334
+ proc = rex_call(
1335
+ *(["-C", client] if client else []),
1336
+ "do",
1337
+ "session.select",
1338
+ f"session_id={session_id}",
1339
+ *([f"window_id={window_id}"] if window_id.startswith("window:") else []),
1340
+ )
1341
+ if proc is None or proc.returncode != 0:
1342
+ return rex_report(proc, f"rex session.select {session_id}")
1343
+ raise_rex_app()
1344
+ return 0
1345
+
1346
+
1347
+ def rex_open_tmux_tab(label: str, target: str) -> int:
1348
+ """Open a new Rex tab attached to tmux TARGET and switch Rex.app to it."""
1349
+ here = rex_target()
1350
+ proc = rex_call(
1351
+ "window",
1352
+ "new",
1353
+ *(["-s", here] if here else []),
1354
+ "--json",
1355
+ label.lstrip("-") or "tmux",
1356
+ "--",
1357
+ "tmux",
1358
+ *tmux_socket_args(),
1359
+ "attach-session",
1360
+ "-t",
1361
+ target,
1362
+ )
1363
+ if proc is None or proc.returncode != 0:
1364
+ return rex_report(proc, "rex window new")
1365
+ session_id = rex_session_windows(here)[0]
1366
+ if session_id:
1367
+ rex_select_session(
1368
+ session_id, clean_field(json_object(proc.stdout).get("window_id"))
1369
+ )
1370
+ return 0
1371
+
1372
+
1373
+ def rex_create_and_select(
1374
+ name: str, path: str, startup: str | None = None, split: str = ""
1375
+ ) -> int:
1376
+ """Create a named Rex session rooted at PATH, run STARTUP in its shell,
1377
+ apply SPLIT as tmux would, and select it."""
1378
+ real_path = os.path.realpath(path)
1379
+ safe_name = name.lstrip("-") or "session"
1380
+ proc = rex_call("new", safe_name, "-c", real_path, "--json")
1381
+ if proc is None or proc.returncode != 0:
1382
+ return rex_report(proc, f"rex new {safe_name}")
1383
+ data = json_object(proc.stdout)
1384
+ windows = data.get("initial_windows")
1385
+ first = (
1386
+ windows[0]
1387
+ if isinstance(windows, list) and windows and isinstance(windows[0], dict)
1388
+ else {}
1389
+ )
1390
+ blocks = first.get("block_ids")
1391
+ block = clean_field(blocks[0]) if isinstance(blocks, list) and blocks else ""
1392
+ if startup and block:
1393
+ # Typed into the interactive shell, as tmux's send-keys: the pane
1394
+ # outlives the program.
1395
+ rex_call("send", "-b", block, "--", f"{startup}\r")
1396
+ if split in ("vertical", "horizontal") and block:
1397
+ direction = "right" if split == "vertical" else "below"
1398
+ rex_call("split", "-b", block, f"--split={direction}", "-c", real_path)
1399
+ session_id = clean_field(data.get("session_id"))
1400
+ if not session_id:
1401
+ return 0
1402
+ return rex_select_session(session_id, clean_field(first.get("window_id")))
1403
+
1404
+
1405
+ def rex_session_preview(session_id: str) -> bool:
1406
+ info = rex_session_info(session_id)
1407
+ if not info:
1408
+ return False
1409
+ windows = info.get("windows")
1410
+ active = info.get("active_window_id")
1411
+ focused = ""
1412
+ print(f"rex session: {clean_field(info.get('label')) or session_id}")
1413
+ for win in windows if isinstance(windows, list) else []:
1414
+ if not isinstance(win, dict):
1415
+ continue
1416
+ wid = win.get("window_id")
1417
+ mark = "*" if wid == active else " "
1418
+ print(f" {mark} {clean_field(win.get('label')) or str(wid or '')}")
1419
+ if wid == active and isinstance(win.get("focused_block_id"), str):
1420
+ focused = win["focused_block_id"]
1421
+ if focused:
1422
+ cap = rex_call("--timeout", "1s", "capture", "-b", focused, "--trim", timeout=2)
1423
+ if cap is not None and cap.returncode == 0 and cap.stdout.strip():
1424
+ print()
1425
+ print(cap.stdout.rstrip())
1426
+ return True
1427
+
1428
+
1429
+ # Compatibility with murmur releases that predate its Rex fixes. Delete both
1430
+ # once muster can require a murmur whose `jump` handles Rex itself.
1431
+
1432
+
1433
+ def murmur_jump_env(env: Mapping[str, str] = os.environ) -> dict[str, str]:
1434
+ """The environment for ``murmur jump``. murmur 3.1.0 detects a Rex pane
1435
+ only by $REX_SESSION, which Rex no longer sets; without it a jump
1436
+ attaches tmux inside this (floating) pane. $REX_BLOCK stands in: ``rex
1437
+ -s`` accepts a block ID. (murmur 3.1.1 reads $REX_BLOCK itself.)"""
1438
+ out = dict(env)
1439
+ if in_rex(env) and not out.get("REX_SESSION") and out.get("REX_BLOCK"):
1440
+ out["REX_SESSION"] = out["REX_BLOCK"]
1441
+ return out
1442
+
1443
+
1444
+ def murmur_jump_in_rex(run: Callable[[], int]) -> int:
1445
+ """RUN a ``murmur jump``, then select the tab it opened. murmur 3.1.1
1446
+ and older open a tmux agent in a new Rex tab without selecting it, so a
1447
+ closing floating picker leaves Rex.app on the old window. A Rex agent
1448
+ adds no window: murmur selects it itself."""
1449
+ if not in_rex():
1450
+ return run()
1451
+ before = rex_session_windows(rex_target())[1]
1452
+ code = run()
1453
+ if code == 0:
1454
+ session_id, after = rex_session_windows(rex_target())
1455
+ new = [w for w in after if w not in before]
1456
+ if session_id and new:
1457
+ rex_select_session(session_id, new[-1])
1458
+ return code
1459
+
1460
+
1461
+ def _reject_constant(name: str) -> object:
1462
+ raise ValueError(f"non-finite number in murmur's JSON: {name}")
1463
+
1464
+
1465
+ RENDER_STATES = {"crashed", "error", "blocked", "done", "working", "waiting", "idle"}
1466
+
1467
+
1468
+ def _is_str(value: object) -> bool:
1469
+ # A NUL cannot be a tmux argument or a path: it would raise at the call.
1470
+ return isinstance(value, str) and "\x00" not in value
1471
+
1472
+
1473
+ def _is_str_or_none(value: object) -> bool:
1474
+ return value is None or _is_str(value)
1475
+
1476
+
1477
+ def _is_bool(value: object) -> bool:
1478
+ return isinstance(value, bool)
1479
+
1480
+
1481
+ def _is_pane_id(value: object) -> bool:
1482
+ return isinstance(value, str) and re.fullmatch(r"%[0-9]+", value) is not None
1483
+
1484
+
1485
+ def is_object(value: object) -> TypeGuard[dict[str, object]]:
1486
+ """A JSON object: a dict whose keys are all strings."""
1487
+ return isinstance(value, dict) and all(isinstance(k, str) for k in value)
1488
+
1489
+
1490
+ def _is_server(value: object) -> bool:
1491
+ if not is_object(value):
1492
+ return False
1493
+ kind = value.get("kind")
1494
+ if kind == "default" or kind == "rex":
1495
+ return True
1496
+ return (
1497
+ isinstance(kind, str)
1498
+ and kind in {"label", "path"}
1499
+ and _is_str(value.get("value"))
1500
+ and bool(value["value"])
1501
+ )
1502
+
1503
+
1504
+ def _is_time(value: object) -> bool:
1505
+ if value is None:
1506
+ return True
1507
+ if isinstance(value, bool):
1508
+ return False
1509
+ if isinstance(value, int):
1510
+ return -(2**63) <= value < 2**63
1511
+ return isinstance(value, float) and math.isfinite(value)
1512
+
1513
+
1514
+ def _is_state(value: object) -> bool:
1515
+ return isinstance(value, str) and value in RENDER_STATES
1516
+
1517
+
1518
+ # Every pane field muster consumes, with its type check. One bad pane rejects
1519
+ # the whole snapshot: half-trusting a malformed document is worse than the
1520
+ # plain #{session_program_state} view. A tmux pane id must be %N: it reaches
1521
+ # tmux as a target, where "notes" or "%1; ..." would mean something else. A Rex
1522
+ # pane ("block:...") is never on muster's server, so only `murmur jump` uses it.
1523
+ PANE_FIELDS = {
1524
+ "pane": lambda v: _is_str(v) and bool(v),
1525
+ "local": _is_bool,
1526
+ "host": _is_str,
1527
+ "server": _is_server,
1528
+ "session_name": _is_str_or_none,
1529
+ "window_name": _is_str_or_none,
1530
+ "render_state": _is_state,
1531
+ "label": _is_str,
1532
+ "visible": _is_bool,
1533
+ "jump_target": lambda v: _is_str(v) and bool(v),
1534
+ "updated_at": _is_time,
1535
+ "attached_pane": lambda v: v is None or _is_pane_id(v),
1536
+ "workstream": _is_str_or_none,
1537
+ }
1538
+
1539
+
1540
+ def valid_pane(pane: object) -> bool:
1541
+ if not is_object(pane):
1542
+ return False
1543
+ if not all(k in pane and check(pane[k]) for k, check in PANE_FIELDS.items()):
1544
+ return False
1545
+ server = pane["server"]
1546
+ return (is_object(server) and server.get("kind") == "rex") or _is_pane_id(
1547
+ pane["pane"]
1548
+ )
1549
+
1550
+
1551
+ def valid_peer(peer: object) -> bool:
1552
+ """A peer as the session notice reads it; fetched_at and target are
1553
+ optional (target is the ssh target, which can differ from the name)."""
1554
+ return (
1555
+ is_object(peer)
1556
+ and _is_str(peer.get("name"))
1557
+ and _is_bool(peer.get("needs_session"))
1558
+ and _is_time(peer.get("fetched_at"))
1559
+ and _is_str_or_none(peer.get("target"))
1560
+ )
1561
+
1562
+
1563
+ def utf8_clean(data: object) -> bool:
1564
+ """Every string in a parsed document, keys included, encodes as UTF-8.
1565
+
1566
+ JSON may carry a lone surrogate (``"\\ud800"``) that no output stream
1567
+ can write; one such string rejects the snapshot rather than a later print.
1568
+ """
1569
+ try:
1570
+ json.dumps(data, ensure_ascii=False).encode("utf-8")
1571
+ except UnicodeEncodeError:
1572
+ return False
1573
+ return True
1574
+
1575
+
1576
+ @dataclass(frozen=True)
1577
+ class Snapshot:
1578
+ panes: list[dict]
1579
+ peers: list[dict]
1580
+
1581
+
1582
+ # Why a murmur snapshot could not be read, as the agents view words it.
1583
+ NO_MURMUR = "murmur not installed"
1584
+ OLD_MURMUR = "murmur too old for the agent view"
1585
+ SLOW_MURMUR = "murmur did not answer in time"
1586
+
1587
+
1588
+ # Views that read murmur's snapshot.
1589
+ MURMUR_MODES = frozenset({"all", "sessions", "agents"})
1590
+
1591
+ # A ``status --json --cached`` started early by prefetch_murmur: the process
1592
+ # and the murmur it runs.
1593
+ _PENDING_STATUS: tuple[subprocess.Popen[str], str] | None = None
1594
+
1595
+
1596
+ def _start_status(exe: str) -> subprocess.Popen[str]:
1597
+ return subprocess.Popen(
1598
+ [exe, "status", "--json", "--cached"],
1599
+ stdin=subprocess.DEVNULL,
1600
+ stdout=subprocess.PIPE,
1601
+ stderr=subprocess.DEVNULL,
1602
+ text=True,
1603
+ )
1604
+
1605
+
1606
+ def prefetch_murmur(mode: str) -> None:
1607
+ """Start murmur's snapshot read now, so node starts up while muster asks
1608
+ tmux; murmur_snapshot collects the answer. A no-op for a view without
1609
+ murmur, without murmur installed, or with a read already started."""
1610
+ global _PENDING_STATUS
1611
+ if mode not in MURMUR_MODES or _PENDING_STATUS is not None:
1612
+ return
1613
+ exe = murmur_command()
1614
+ if exe is None:
1615
+ return
1616
+ with contextlib.suppress(OSError):
1617
+ _PENDING_STATUS = (_start_status(exe), exe)
1618
+
1619
+
1620
+ # murmur's ambient collect skips a peer attempted within its floor (30s, less
1621
+ # up to half its 20s jitter), so a peer fetched more recently than this is not
1622
+ # due and starting a collect for it is a wasted node process.
1623
+ PEER_FRESH_MS = 20_000
1624
+
1625
+
1626
+ def peers_due(peers: list[dict], now_ms: float | None = None) -> bool:
1627
+ """Whether a ``collect --floored`` could fetch any peer: one that is
1628
+ stale, never fetched, or fetched longer ago than PEER_FRESH_MS."""
1629
+ now_ms = time.time() * 1000 if now_ms is None else now_ms
1630
+ for peer in peers:
1631
+ fetched = peer.get("fetched_at")
1632
+ if peer.get("stale") is True or not isinstance(fetched, (int, float)):
1633
+ return True
1634
+ if now_ms - fetched >= PEER_FRESH_MS:
1635
+ return True
1636
+ return False
1637
+
1638
+
1639
+ def _lower_priority() -> None:
1640
+ with contextlib.suppress(OSError):
1641
+ os.nice(10)
1642
+
1643
+
1644
+ def murmur_snapshot() -> tuple[Snapshot | None, str]:
1645
+ """murmur's agent panes and peers, or None and the reason there are none.
1646
+
1647
+ One cache-only read (``status --json --cached``: it never reaches a peer),
1648
+ under a short timeout; started by prefetch_murmur when a caller could.
1649
+ Capability is probed by the call itself: it must succeed and the panes
1650
+ must carry the derived fields muster consumes (``render_state``,
1651
+ ``jump_target``; murmur publishes ``jump_target`` from the release that
1652
+ added ``murmur jump``). Version numbers are never compared. On success,
1653
+ when some peer is due a fetch, a detached low-priority ``collect`` warms
1654
+ the cache for the next open.
1655
+ """
1656
+ global _PENDING_STATUS
1657
+ exe = murmur_command()
1658
+ pending, _PENDING_STATUS = _PENDING_STATUS, None
1659
+ if exe is None:
1660
+ return None, NO_MURMUR
1661
+ timeout = float(os.environ.get("MUSTER_MURMUR_TIMEOUT", "1"))
1662
+ try:
1663
+ proc = pending[0] if pending and pending[1] == exe else _start_status(exe)
1664
+ try:
1665
+ stdout, _ = proc.communicate(timeout=timeout)
1666
+ except subprocess.TimeoutExpired:
1667
+ proc.kill()
1668
+ proc.communicate()
1669
+ return None, SLOW_MURMUR
1670
+ data = (
1671
+ json.loads(stdout, parse_constant=_reject_constant)
1672
+ if proc.returncode == 0
1673
+ else None
1674
+ )
1675
+ except (OSError, ValueError):
1676
+ return None, OLD_MURMUR
1677
+ if not utf8_clean(data):
1678
+ return None, OLD_MURMUR
1679
+ panes = data.get("panes") if isinstance(data, dict) else None
1680
+ peers = data.get("peers", []) if isinstance(data, dict) else None
1681
+ if not isinstance(panes, list) or not all(valid_pane(p) for p in panes):
1682
+ return None, OLD_MURMUR
1683
+ if not isinstance(peers, list) or not all(valid_peer(p) for p in peers):
1684
+ return None, OLD_MURMUR
1685
+ if peers_due(peers):
1686
+ with contextlib.suppress(OSError):
1687
+ subprocess.Popen(
1688
+ [exe, "collect", "--quiet", "--floored"],
1689
+ stdin=subprocess.DEVNULL,
1690
+ stdout=subprocess.DEVNULL,
1691
+ stderr=subprocess.DEVNULL,
1692
+ start_new_session=True,
1693
+ preexec_fn=_lower_priority,
1694
+ )
1695
+ return Snapshot(panes, peers), ""
1696
+
1697
+
1698
+ def named_socket(name: str) -> str | None:
1699
+ """The physical socket a tmux -L NAME reaches now.
1700
+
1701
+ Resolved like a -S path: a symlink in tmux's socket directory is an alias
1702
+ that can be retargeted after a proof is made (see pinned_server).
1703
+ """
1704
+ conventional = conventional_tmux_dir()
1705
+ return os.path.realpath(os.path.join(conventional, name)) if conventional else None
1706
+
1707
+
1708
+ def conventional_tmux_dir() -> str | None:
1709
+ """Where tmux keeps its named sockets, as murmur derives it."""
1710
+ try:
1711
+ base = os.path.realpath(os.environ.get("TMUX_TMPDIR") or "/tmp")
1712
+ return os.path.join(base, f"tmux-{os.getuid()}")
1713
+ except OSError:
1714
+ return None
1715
+
1716
+
1717
+ # The socket own_socket() resolved when this process started (see
1718
+ # pin_own_server): None until then.
1719
+ START_SOCKET: str | None = None
1720
+
1721
+
1722
+ def pin_own_server() -> None:
1723
+ """Resolve muster's server once, before murmur is read, and talk to it.
1724
+
1725
+ Every later proof compares against this one physical path, and every tmux
1726
+ call names it with -S, so an alias (-L name, $TMUX, a symlink) retargeted
1727
+ mid-run can neither pass a proof nor redirect a call. Without a server yet
1728
+ the socket does not exist; then calls keep the plain arguments, so tmux can
1729
+ create its socket directory when it starts one.
1730
+ """
1731
+ global START_SOCKET, PINNED_SOCKET
1732
+ START_SOCKET = resolve_own_socket()
1733
+ if START_SOCKET and os.path.exists(START_SOCKET):
1734
+ PINNED_SOCKET = START_SOCKET
1735
+
1736
+
1737
+ def own_socket() -> str | None:
1738
+ """The socket muster's own tmux calls reach, or None when unknown."""
1739
+ return START_SOCKET or resolve_own_socket()
1740
+
1741
+
1742
+ def resolve_own_socket() -> str | None:
1743
+ """The physical socket muster's tmux calls would reach now.
1744
+
1745
+ Same precedence as the calls themselves: the MUSTER_TMUX_SOCKET_* test
1746
+ overrides, then the socket in $TMUX (a bare tmux follows it), then the
1747
+ default socket.
1748
+ """
1749
+ if path := os.environ.get("MUSTER_TMUX_SOCKET_PATH"):
1750
+ return os.path.realpath(path)
1751
+ if name := os.environ.get("MUSTER_TMUX_SOCKET_NAME"):
1752
+ return named_socket(name)
1753
+ if ambient := os.environ.get("TMUX"):
1754
+ return os.path.realpath(ambient.split(",")[0])
1755
+ return named_socket("default")
1756
+
1757
+
1758
+ def server_socket(server: object) -> str | None:
1759
+ """The socket a murmur ``server`` value names; None if it is not understood."""
1760
+ if not is_object(server):
1761
+ return None
1762
+ kind, value = server.get("kind"), server.get("value")
1763
+ if kind == "default":
1764
+ return named_socket("default")
1765
+ if kind == "label" and isinstance(value, str) and value:
1766
+ return named_socket(value)
1767
+ if kind == "path" and isinstance(value, str) and value:
1768
+ return os.path.realpath(value)
1769
+ return None
1770
+
1771
+
1772
+ def is_own_server(server: object) -> bool:
1773
+ """True only when SERVER provably is the server muster talks to."""
1774
+ own, other = own_socket(), server_socket(server)
1775
+ return own is not None and own == other
1776
+
1777
+
1778
+ def clean_field(value: object) -> str:
1779
+ """A murmur string made safe for one tab-separated row field."""
1780
+ return re.sub(r"[\t\r\n]+", " ", str(value or ""))
1781
+
1782
+
1783
+ def age_text(updated_ms: object, now_ms: float | None = None) -> str:
1784
+ if not isinstance(updated_ms, (int, float)) or isinstance(updated_ms, bool):
1785
+ return ""
1786
+ now = time.time() * 1000 if now_ms is None else now_ms
1787
+ seconds = max(0, int((now - updated_ms) / 1000))
1788
+ for unit, size in (("d", 86400), ("h", 3600), ("m", 60)):
1789
+ if seconds >= size:
1790
+ return f"{seconds // size}{unit}"
1791
+ return f"{seconds}s"
1792
+
1793
+
1794
+ ATTENTION_ROW_STATES = {"crashed", "error", "blocked", "done"}
1795
+
1796
+
1797
+ def murmur_saw_own_server() -> bool:
1798
+ """Whether murmur's ambient tmux is the server muster queries.
1799
+
1800
+ murmur computes ``attached_pane`` with a bare tmux, which follows $TMUX (or
1801
+ the default socket); the MUSTER_TMUX_SOCKET_* overrides apply to muster only.
1802
+ A pane id seen behind an override is not evidence of the pane murmur meant.
1803
+ """
1804
+ if ambient := os.environ.get("TMUX"):
1805
+ murmur_socket = os.path.realpath(ambient.split(",")[0])
1806
+ else:
1807
+ murmur_socket = named_socket("default") or ""
1808
+ return bool(murmur_socket) and own_socket() == murmur_socket
1809
+
1810
+
1811
+ def attached_session(pane_id: str) -> str | None:
1812
+ """The session of a local pane on muster's own server, or None.
1813
+
1814
+ murmur reports a remote agent's ``attached_pane``: a pane here that holds
1815
+ the ssh session to it. murmur read it with the same ambient tmux muster
1816
+ uses, so it counts only if this server really has that pane.
1817
+ """
1818
+ result = tmux_bytes("display-message", "-p", "-t", pane_id, "#{session_name}")
1819
+ if result.returncode != 0:
1820
+ return None
1821
+ return os.fsdecode(result.stdout).removesuffix("\n") or None
1822
+
1823
+
1824
+ def inside_own_server() -> bool:
1825
+ """Whether the invoking client is on the server muster's tmux calls reach.
1826
+
1827
+ Only then may muster move the client itself; outside tmux, or from a client
1828
+ of another server, an agent is murmur's to reach.
1829
+ """
1830
+ ambient = os.environ.get("TMUX")
1831
+ return bool(ambient) and own_socket() == os.path.realpath(ambient.split(",")[0])
1832
+
1833
+
1834
+ def current_location() -> tuple[str, str]:
1835
+ """(pane id, session name) of the invoking client: resolved before fzf
1836
+ starts (see resolve_invoker) and handed to reloads through the environment,
1837
+ or, on a cached open, found after fzf started and left in the picker's
1838
+ directory (see build_fresh).
1839
+ """
1840
+ if "MUSTER_CURRENT_PANE" in os.environ:
1841
+ return (
1842
+ os.environ.get("MUSTER_CURRENT_PANE", ""),
1843
+ os.environ.get("MUSTER_CURRENT_SESSION", ""),
1844
+ )
1845
+ if directory := picker_dir():
1846
+ with contextlib.suppress(OSError):
1847
+ pane, _, session = (directory / "invoker").read_text().partition("\t")
1848
+ return pane, session
1849
+ return "", ""
1850
+
1851
+
1852
+ def pane_state(pane: dict) -> AgentState:
1853
+ return AgentState[str(pane["render_state"])]
1854
+
1855
+
1856
+ def agent_entry(pane: dict, *, detail: str = "", text: str = "") -> Entry:
1857
+ """An agent row: the payload every view shares, with the all view's
1858
+ DETAIL or the agents view's pre-rendered TEXT."""
1859
+ is_here = bool(pane.get("local")) and is_own_server(pane.get("server"))
1860
+ pane_id = clean_field(pane.get("pane"))
1861
+ current = is_here and pane_id == current_location()[0]
1862
+ return Entry(
1863
+ kind="agent",
1864
+ name=clean_field(pane.get("label")),
1865
+ session_name=clean_field(pane.get("session_name")),
1866
+ worst_state=pane_state(pane),
1867
+ is_running=True,
1868
+ host=clean_field(pane.get("host")),
1869
+ pane=pane_id,
1870
+ jump_target=clean_field(pane.get("jump_target")),
1871
+ here="1" if is_here else "",
1872
+ socket=(own_socket() or "") if is_here else "",
1873
+ marker="current" if current else "",
1874
+ detail=detail,
1875
+ text=text,
1876
+ )
1877
+
1878
+
1879
+ def agent_entries(
1880
+ panes: list[dict], live: Mapping[str, object], *, crew: bool = False
1881
+ ) -> tuple[list[Entry], dict[str, dict[AgentState, int]]]:
1882
+ """Attention rows for the all view, and per-session state counts.
1883
+
1884
+ panes[] already arrives most-urgent first; it is not re-sorted. Only panes
1885
+ on the tmux server muster talks to count toward a live session's row.
1886
+ """
1887
+ counts: dict[str, dict[AgentState, int]] = {}
1888
+ rows: list[Entry] = []
1889
+ attached_cache: dict[str, str | None] = {}
1890
+ for pane in panes:
1891
+ state = pane_state(pane)
1892
+ is_here = bool(pane.get("local")) and is_own_server(pane.get("server"))
1893
+ session = clean_field(pane.get("session_name"))
1894
+ counted = session if is_here else None
1895
+ if (
1896
+ not pane.get("local")
1897
+ and pane.get("attached_pane")
1898
+ and murmur_saw_own_server()
1899
+ ):
1900
+ # A remote agent counts under the local session holding its ssh pane.
1901
+ attached = str(pane["attached_pane"])
1902
+ if attached not in attached_cache:
1903
+ attached_cache[attached] = attached_session(attached)
1904
+ counted = attached_cache[attached]
1905
+ if counted and counted in live:
1906
+ per = counts.setdefault(counted, {})
1907
+ per[state] = per.get(state, 0) + 1
1908
+ if str(pane.get("render_state")) in ATTENTION_ROW_STATES and (
1909
+ crew or pane.get("visible")
1910
+ ):
1911
+ where = f"{session}:{clean_field(pane.get('window_name'))}".strip(":")
1912
+ parts = [agent_mux(pane), clean_field(pane.get("host")), where]
1913
+ parts.append(age_text(pane.get("updated_at")))
1914
+ rows.append(
1915
+ agent_entry(pane, detail=" \u00b7 ".join(p for p in parts if p))
1916
+ )
1917
+ return rows, counts
1918
+
1919
+
1920
+ def agent_mux(pane: dict) -> str:
1921
+ """Which multiplexer owns this pane: ``rex`` or ``tmux``."""
1922
+ server = pane.get("server")
1923
+ return "rex" if isinstance(server, dict) and server.get("kind") == "rex" else "tmux"
1924
+
1925
+
1926
+ def agent_stream(pane: dict) -> str:
1927
+ """Which piece of work: mu's workstream, else the tmux session; blank when
1928
+ it would repeat the label."""
1929
+ stream = clean_field(pane.get("workstream") or pane.get("session_name"))
1930
+ return "" if stream == clean_field(pane.get("label")) else stream
1931
+
1932
+
1933
+ def agent_view_entries(
1934
+ panes: list[dict], *, crew: bool
1935
+ ) -> tuple[list[Entry], AgentColumns, dict[AgentState, int]]:
1936
+ """Rows of the agents view: every agent murmur marks visible (all of them
1937
+ with CREW), in murmur's order, with the columns they need and the count of
1938
+ shown agents per state."""
1939
+ shown = [p for p in panes if crew or p.get("visible")]
1940
+ columns = AgentColumns(
1941
+ mux=bool(shown),
1942
+ stream=any(agent_stream(p) for p in shown),
1943
+ host=any(not p.get("local") for p in shown),
1944
+ )
1945
+ mux_on, stream_on, host_on = LAYOUT.agent_columns(
1946
+ columns.mux, columns.stream, columns.host
1947
+ )
1948
+ counts: dict[AgentState, int] = {}
1949
+ rows: list[Entry] = []
1950
+ for pane in shown:
1951
+ state = pane_state(pane)
1952
+ counts[state] = counts.get(state, 0) + 1
1953
+ label = clean_field(pane.get("label"))
1954
+ label = fit(row_escape(label), LAYOUT.name_width, keep="middle")
1955
+ cells = [f"{STATE_GLYPH[state]} {label}"]
1956
+ if mux_on:
1957
+ cells.append(fit(agent_mux(pane), MUX_WIDTH))
1958
+ if stream_on:
1959
+ cells.append(fit(row_escape(agent_stream(pane)), STREAM_WIDTH))
1960
+ if host_on:
1961
+ host = clean_field(pane.get("host"))
1962
+ where = "here" if pane.get("local") else f"\u2192 {host}"
1963
+ cells.append(fit(row_escape(where), HOST_WIDTH))
1964
+ cells.append(age_text(pane.get("updated_at")))
1965
+ rows.append(agent_entry(pane, text=" ".join(cells).rstrip()))
1966
+ return rows, columns, counts
1967
+
1968
+
1969
+ # murmur's ControlPath: warming a socket here is what lets it collect again.
1970
+ MURMUR_CONTROL_PATH = "~/.ssh/control/%r@%h:%p"
1971
+
1972
+
1973
+ def session_notice(peers: list[dict]) -> str:
1974
+ """murmur's notice for peers that need an interactive session, or "".
1975
+
1976
+ As murmur words it (paint.ts sessionNotice): up to three gated peers,
1977
+ oldest first, when the oldest was last reached, and the command that warms
1978
+ an ssh socket for it, built from its ssh target (a peer name may differ).
1979
+ """
1980
+ gated = sorted(
1981
+ (p for p in peers if p["needs_session"]),
1982
+ key=lambda p: p.get("fetched_at") or 0,
1983
+ )
1984
+ if not gated:
1985
+ return ""
1986
+ oldest = gated[0]
1987
+ names = ", ".join(clean_field(p["name"]) for p in gated[:3])
1988
+ fetched = oldest.get("fetched_at")
1989
+ if fetched is None:
1990
+ seen = "never"
1991
+ elif time.time() * 1000 - fetched < 60_000:
1992
+ seen = "just now"
1993
+ else:
1994
+ seen = age_text(fetched)
1995
+ target = clean_field(oldest.get("target") or oldest["name"])
1996
+ command = f"ssh -MNf -S {MURMUR_CONTROL_PATH} {target}"
1997
+ peach = CATPPUCCIN["peach"]
1998
+ return (
1999
+ ansi_style(
2000
+ f"{STATE_GLYPH[AgentState.blocked]} {names}: re-auth needed",
2001
+ fg=peach,
2002
+ bold=True,
2003
+ )
2004
+ + ansi_style(f" (last seen {seen}) \u2014 ", fg=peach)
2005
+ + ansi_style(command, fg=peach, bold=True)
2006
+ )
2007
+
2008
+
2009
+ @dataclass(frozen=True)
2010
+ class View:
2011
+ entries: list[Entry]
2012
+ header: str
2013
+ prompt: str
2014
+
2015
+
2016
+ def agents_view(crew: bool) -> View:
2017
+ snapshot, problem = murmur_snapshot()
2018
+ if snapshot is None:
2019
+ status = ansi_style(problem, fg=CATPPUCCIN["peach"])
2020
+ return View(
2021
+ [], header_text("agents", status=status), prompt_text("agents", crew)
2022
+ )
2023
+ rows, columns, counts = agent_view_entries(snapshot.panes, crew=crew)
2024
+ status = ""
2025
+ if not rows:
2026
+ hidden = sum(1 for p in snapshot.panes if not p.get("visible"))
2027
+ status = f"No human agents (+{hidden} crew: ctrl-g)" if hidden else "No agents"
2028
+ status = ansi_style(status, fg=CATPPUCCIN["subtext0"])
2029
+ header = header_text(
2030
+ "agents",
2031
+ notice=session_notice(snapshot.peers),
2032
+ status=status,
2033
+ columns=columns,
2034
+ )
2035
+ return View(rows, header, prompt_text("agents", crew, counts))
2036
+
2037
+
2038
+ _MERGE_ORDER = (
2039
+ AgentState.idle,
2040
+ AgentState.done,
2041
+ AgentState.waiting,
2042
+ AgentState.working,
2043
+ AgentState.error,
2044
+ AgentState.blocked,
2045
+ AgentState.crashed,
2046
+ )
2047
+
2048
+
2049
+ def merge_rank(state: AgentState) -> int:
2050
+ """Urgency when merging native and murmur states: blocked outranks error."""
2051
+ return _MERGE_ORDER.index(state)
2052
+
2053
+
2054
+ def build_entries(
2055
+ mode: str, live: Mapping[str, AgentState | None] | None = None
2056
+ ) -> list[Entry]:
2057
+ return build_view(mode, live).entries
2058
+
2059
+
2060
+ def build_view(
2061
+ mode: str,
2062
+ live: Mapping[str, AgentState | None] | None = None,
2063
+ *,
2064
+ crew: bool = False,
2065
+ ) -> View:
2066
+ prefetch_murmur(mode)
2067
+ if mode == "agents":
2068
+ return agents_view(crew)
2069
+ config = load_config()
2070
+ configured_sessions = config.sessions
2071
+ configured_paths = {expand(session.path) for session in configured_sessions}
2072
+ # One list-sessions call; vtmux keeps #{session_program_state} current.
2073
+ if live is None:
2074
+ live = backend().live_sessions()
2075
+ live_names = set(live)
2076
+ attached = getattr(live, "attached", frozenset())
2077
+ current_session = current_location()[1]
2078
+ ids = getattr(live, "ids", {})
2079
+ states = dict(live)
2080
+ entries: list[Entry] = []
2081
+ session_counts: dict[str, dict[AgentState, int]] = {}
2082
+ notice = ""
2083
+ snapshot = murmur_snapshot()[0] if mode in {"all", "sessions"} else None
2084
+ if snapshot is not None:
2085
+ notice = session_notice(snapshot.peers)
2086
+ agent_rows, session_counts = agent_entries(snapshot.panes, live, crew=crew)
2087
+ for name, per in session_counts.items():
2088
+ active = [st for st in per if st is not AgentState.idle]
2089
+ if not active:
2090
+ continue # idle agents never colour a row
2091
+ strongest = max(active, key=merge_rank)
2092
+ current = states.get(name)
2093
+ if current is None or merge_rank(current) < merge_rank(strongest):
2094
+ states[name] = strongest
2095
+ if mode == "all":
2096
+ entries.extend(agent_rows)
2097
+
2098
+ def counts_for(name: str) -> tuple[tuple[AgentState, int], ...]:
2099
+ per = session_counts.get(name, {})
2100
+ return tuple(sorted(per.items(), key=lambda item: -item[0]))
2101
+
2102
+ def marker_for(name: str) -> str:
2103
+ if name in live_names and name == current_session:
2104
+ return "current"
2105
+ return "attached" if name in attached else ""
2106
+
2107
+ def where(name: str) -> dict[str, str]:
2108
+ """A live row's path: the active pane's cwd, and "+N" for the other
2109
+ directories its windows sit in."""
2110
+ if name not in live_names or not isinstance(live, LiveSessions):
2111
+ return {}
2112
+ cwd, others = live.location(name)
2113
+ found = {"counts": live.counts(name)}
2114
+ if cwd:
2115
+ found["detail"] = tildify(cwd)
2116
+ found["extra"] = f"+{others}" if others else ""
2117
+ return found
2118
+
2119
+ # A directory with a live session is offered by that session's row only.
2120
+ taken = configured_paths | (
2121
+ live.dirs() if isinstance(live, LiveSessions) else set()
2122
+ )
2123
+
2124
+ if mode in {"all", "sessions"}:
2125
+ entries.extend(
2126
+ Entry(
2127
+ kind="default",
2128
+ name=session.name,
2129
+ session_name=session.name,
2130
+ path=expand(session.path),
2131
+ startup=session.startup,
2132
+ split=session.split,
2133
+ worst_state=states.get(session.name),
2134
+ is_running=session.name in live_names,
2135
+ agent_counts=counts_for(session.name),
2136
+ marker=marker_for(session.name),
2137
+ session_id=ids.get(session.name, ""),
2138
+ **where(session.name),
2139
+ )
2140
+ for session in configured_sessions
2141
+ )
2142
+
2143
+ if mode in {"all", "sessions"}:
2144
+ configured_names = {session.name for session in configured_sessions}
2145
+ # Most recently active first; pinned sessions keep the config order.
2146
+ activity = getattr(live, "activity", {})
2147
+ for session_name in sorted(
2148
+ live_names, key=lambda name: (-activity.get(name, 0), name)
2149
+ ):
2150
+ if session_name in configured_names:
2151
+ continue
2152
+ entries.append(
2153
+ Entry(
2154
+ kind="tmux",
2155
+ name=session_name,
2156
+ session_name=session_name,
2157
+ worst_state=states.get(session_name),
2158
+ is_running=True,
2159
+ agent_counts=counts_for(session_name),
2160
+ marker=marker_for(session_name),
2161
+ session_id=ids.get(session_name, ""),
2162
+ **where(session_name),
2163
+ )
2164
+ )
2165
+ rex_counts: dict[str, dict[AgentState, int]] = {}
2166
+ if snapshot is not None:
2167
+ for pane in snapshot.panes:
2168
+ srv = pane.get("server")
2169
+ if (
2170
+ pane.get("local")
2171
+ and isinstance(srv, dict)
2172
+ and srv.get("kind") == "rex"
2173
+ and isinstance(pane.get("session"), str)
2174
+ ):
2175
+ st = pane_state(pane)
2176
+ per = rex_counts.setdefault(pane["session"], {})
2177
+ per[st] = per.get(st, 0) + 1
2178
+ for sid, label in rex_sessions():
2179
+ per = rex_counts.get(sid, {})
2180
+ active = [st for st in per if st is not AgentState.idle]
2181
+ worst = max(active, key=merge_rank) if active else None
2182
+ entries.append(
2183
+ Entry(
2184
+ kind="rex",
2185
+ name=label,
2186
+ session_name=label,
2187
+ worst_state=worst,
2188
+ is_running=True,
2189
+ agent_counts=tuple(sorted(per.items(), key=lambda item: -item[0])),
2190
+ counts="rex",
2191
+ session_id=sid,
2192
+ )
2193
+ )
2194
+
2195
+ if mode == "all":
2196
+ entries.extend(
2197
+ build_path_entries(
2198
+ kind="zoxide",
2199
+ paths=zoxide_paths(),
2200
+ configured_paths=taken,
2201
+ mode="zoxide",
2202
+ config=config,
2203
+ )
2204
+ )
2205
+
2206
+ if mode == "find":
2207
+ entries.extend(
2208
+ build_path_entries(
2209
+ kind="find",
2210
+ paths=find_paths(config),
2211
+ configured_paths=taken,
2212
+ mode="find",
2213
+ config=config,
2214
+ )
2215
+ )
2216
+
2217
+ return View(entries, header_text(mode, notice=notice), prompt_text(mode, crew))
2218
+
2219
+
2220
+ def tmux_session_preview(name: str) -> bool:
2221
+ """Print a live session's windows and its active pane; False if the
2222
+ session is not there.
2223
+
2224
+ One tmux call: the window list, a marker line, then the capture. The
2225
+ window list fails for a missing session and stops the chain before the
2226
+ marker.
2227
+ """
2228
+ marker = f"muster-{os.urandom(8).hex()}"
2229
+ result = tmux_cmd(
2230
+ "list-windows",
2231
+ "-t",
2232
+ exact_session_target(name),
2233
+ "-F",
2234
+ # The pane fields are the window's active pane. The path last: it
2235
+ # may hold a tab (a window name is assumed not to).
2236
+ "#{session_attached}\t#{window_index}\t#{window_active}\t#{window_panes}"
2237
+ "\t#{window_program_state}\t#{pane_index}\t#{pane_current_command}"
2238
+ "\t#{window_name}\t#{pane_current_path}",
2239
+ ";",
2240
+ "display-message",
2241
+ "-p",
2242
+ marker,
2243
+ ";",
2244
+ "capture-pane",
2245
+ "-p",
2246
+ "-J",
2247
+ "-t",
2248
+ active_pane_target(name),
2249
+ "-S",
2250
+ "-200",
2251
+ check=False,
2252
+ )
2253
+ windows, found, capture = result.stdout.partition(f"{marker}\n")
2254
+ if not found:
2255
+ return False
2256
+
2257
+ attached = ""
2258
+ attention_total = 0
2259
+ active_pane = ""
2260
+ window_lines: list[str] = []
2261
+ for line in windows.splitlines():
2262
+ parts = line.split("\t", 8)
2263
+ if len(parts) != 9:
2264
+ continue
2265
+ attached, index, active, pane_count, raw_state = parts[:5]
2266
+ pane_index, command, window_name, window_path = parts[5:]
2267
+ state = AgentState.parse(raw_state)
2268
+ if state in ATTENTION_STATES:
2269
+ attention_total += 1
2270
+ if active == "1" and not active_pane:
2271
+ active_pane = f"{pane_index} {command}"
2272
+ glyph = STATE_GLYPH[state] if state else " "
2273
+ window_lines.append(
2274
+ f"{'*' if active == '1' else ' '} {index} {glyph} {window_name}"
2275
+ f" {pane_count}p {tildify(window_path)}"
2276
+ )
2277
+
2278
+ meta: list[str] = []
2279
+ if attached:
2280
+ meta.append(f"attached {attached}")
2281
+ if attention_total:
2282
+ meta.append(f"attention {attention_total}")
2283
+ suffix = f" ({', '.join(meta)})" if meta else ""
2284
+ print(f"{name}{suffix}")
2285
+ # Every window: active marker, index, state, name, panes, cwd.
2286
+ for line in window_lines:
2287
+ print(line)
2288
+ if active_pane:
2289
+ print(f"pane: {active_pane}")
2290
+ print()
2291
+
2292
+ if result.returncode != 0:
2293
+ print("(unable to capture active pane)")
2294
+ return True
2295
+ print(capture.rstrip())
2296
+ return True
2297
+
2298
+
2299
+ def preview(
2300
+ path: str,
2301
+ session_name: str = "",
2302
+ kind: str = "",
2303
+ split: str = "",
2304
+ host: str = "",
2305
+ pane: str = "",
2306
+ here: str = "",
2307
+ socket: str = "",
2308
+ session_id: str = "",
2309
+ ) -> int:
2310
+ if kind == "agent":
2311
+ if proven_here(here, socket) and pane:
2312
+ with pinned_server(socket):
2313
+ capture = tmux_cmd(
2314
+ "capture-pane", "-p", "-J", "-t", pane, "-S", "-200", check=False
2315
+ )
2316
+ if capture.returncode == 0:
2317
+ print(capture.stdout.rstrip())
2318
+ return 0
2319
+ print(f"host: {host or '(unknown)'}\nsession: {session_name or '(unknown)'}")
2320
+ return 0
2321
+ if kind == "rex" and rex_session_preview(session_id):
2322
+ return 0
2323
+ live = kind in {"tmux", "default"} and session_name
2324
+ if live and tmux_session_preview(session_name):
2325
+ return 0
2326
+
2327
+ target = expand(path) if path else ""
2328
+ if not target:
2329
+ if split and kind == "default":
2330
+ print(f"session: {session_name or '(unknown)'}\nsplit: {split}", end="")
2331
+ else:
2332
+ print(f"session: {session_name or '(unknown)'}", end="")
2333
+ return 0
2334
+ if split:
2335
+ print(f"split: {split}\n")
2336
+ command = load_config().preview_command
2337
+ if command == default_preview_command():
2338
+ # No shell for the built-in command: a login shell costs more than
2339
+ # the listing.
2340
+ argv = [target if word == "{path}" else word for word in command.split()]
2341
+ os.execvp(argv[0], argv)
2342
+ else:
2343
+ os.execvp("sh", ["sh", "-lc", command.format(path=sh_quote(target))])
2344
+ return 0
2345
+
2346
+
2347
+ def reload_cmd(mode: str, crew: bool = False) -> str:
2348
+ crew_flag = " --crew" if crew else ""
2349
+ return f"{sh_quote(sys.argv[0])} list --mode {mode}{crew_flag}"
2350
+
2351
+
2352
+ def kill_bind() -> str:
2353
+ """ctrl-x: kill the highlighted session row, or dismiss the highlighted
2354
+ agent's crash, then redraw the current view.
2355
+
2356
+ Only live session rows carry an id and only agent rows a jump target; the
2357
+ `=` form keeps an empty one from eating the next flag. fzf exports the
2358
+ live prompt as FZF_PROMPT, which names the view.
2359
+ """
2360
+ me = sh_quote(sys.argv[0])
2361
+ client = f" --client {sh_quote(INVOKING_CLIENT)}" if INVOKING_CLIENT else ""
2362
+ kind = FZF_ROW_FIELDS.index("kind") + 1
2363
+ field = FZF_ROW_FIELDS.index("session_id") + 1
2364
+ target = FZF_ROW_FIELDS.index("jump_target") + 1
2365
+ return (
2366
+ f"ctrl-x:execute-silent({me} kill --kind={{{kind}}}"
2367
+ f" --session-id={{{field}}} --jump-target={{{target}}}{client})"
2368
+ f'+reload({me} list --prompt "$FZF_PROMPT")'
2369
+ )
2370
+
2371
+
2372
+ # Set for fzf's children: where `list` leaves the header and prompt of the view
2373
+ # it printed, for the `load` binding to pick up.
2374
+ PICKER_DIR_ENV = "MUSTER_PICKER_DIR"
2375
+
2376
+
2377
+ def write_view_files(directory: str, view: View) -> None:
2378
+ for name, text in (("header", view.header), ("prompt", view.prompt)):
2379
+ write_atomic(Path(directory, name), text)
2380
+
2381
+
2382
+ def write_atomic(path: Path, text: str) -> None:
2383
+ tmp = path.with_name(f".{path.name}.{os.getpid()}")
2384
+ tmp.write_text(text)
2385
+ tmp.replace(path)
2386
+
2387
+
2388
+ # The optimistic open. pick-and-connect starts fzf on the rows the last open of
2389
+ # the same view left in a cache, builds the fresh view itself meanwhile (Python
2390
+ # is already running), and hands it to fzf over fzf's --listen socket. Files in
2391
+ # the picker's directory carry the handover:
2392
+ # rows the fresh rows, for the posted `reload(cat rows)`
2393
+ # switched a view key or kill ran first: leave fzf's own reload alone
2394
+ # invoker "pane<TAB>session" of the invoking client, for later reloads,
2395
+ # when pick-and-connect found it only after fzf started
2396
+ # fzf keeps the cursor's index, not its row, across a reload (and --track
2397
+ # would drop keys while one runs), so an Enter on a cached row is looked up
2398
+ # again in the fresh build before muster acts on it.
2399
+
2400
+
2401
+ @dataclass(frozen=True)
2402
+ class CachedView:
2403
+ mode: str # the view the rows show (all may have opened as sessions)
2404
+ header: str
2405
+ prompt: str
2406
+ rows: list[str]
2407
+
2408
+
2409
+ def view_cache_path(mode: str) -> Path:
2410
+ """The cache for opening MODE: one per muster version, tmux server and list
2411
+ width, since rows are laid out for one width and proven for one server."""
2412
+ key = json.dumps([VERSION, mode, own_socket() or "", LAYOUT.columns])
2413
+ digest = hashlib.sha256(key.encode()).hexdigest()[:16]
2414
+ return STATE_DIR / "views" / f"{mode}-{digest}.json"
2415
+
2416
+
2417
+ def read_view_cache(path: Path) -> CachedView | None:
2418
+ try:
2419
+ data = json.loads(path.read_text())
2420
+ except (OSError, ValueError):
2421
+ return None
2422
+ if not is_object(data) or data.get("version") != VERSION:
2423
+ return None
2424
+ mode, header, prompt, rows = (
2425
+ data.get(k) for k in ("mode", "header", "prompt", "rows")
2426
+ )
2427
+ if mode not in MODES or not (_is_str(header) and _is_str(prompt)):
2428
+ return None
2429
+ fields = len(FZF_ROW_FIELDS)
2430
+ if not isinstance(rows, list) or not all(
2431
+ _is_str(r) and "\n" not in r and r.count("\t") == fields - 1 for r in rows
2432
+ ):
2433
+ return None
2434
+ return CachedView(str(mode), str(header), str(prompt), [str(r) for r in rows])
2435
+
2436
+
2437
+ def write_view_cache(path: Path, mode: str, view: View, rows: list[str]) -> None:
2438
+ doc = {
2439
+ "version": VERSION,
2440
+ "mode": mode,
2441
+ "header": view.header,
2442
+ "prompt": view.prompt,
2443
+ "rows": rows,
2444
+ }
2445
+ with contextlib.suppress(OSError):
2446
+ path.parent.mkdir(parents=True, exist_ok=True)
2447
+ write_atomic(path, json.dumps(doc))
2448
+
2449
+
2450
+ def picker_dir() -> Path | None:
2451
+ directory = os.environ.get(PICKER_DIR_ENV)
2452
+ return Path(directory) if directory else None
2453
+
2454
+
2455
+ def mark_switched() -> None:
2456
+ """The picker's own reload now owns the list (see the comment above)."""
2457
+ if directory := picker_dir():
2458
+ with contextlib.suppress(OSError):
2459
+ (directory / "switched").touch()
2460
+
2461
+
2462
+ @dataclass(frozen=True)
2463
+ class Fresh:
2464
+ """The rows of the fresh view a cached open built while fzf showed the
2465
+ cache."""
2466
+
2467
+ rows: list[str]
2468
+
2469
+ def choice(self, row: str) -> EntryPayload | None:
2470
+ """ROW as it is now: itself when fresh, else the fresh row with the
2471
+ same identity, or None when that row is gone."""
2472
+ if row in self.rows:
2473
+ return EntryPayload.from_fzf_row(row)
2474
+ wanted = row_identity(EntryPayload.from_fzf_row(row))
2475
+ for fresh_row in self.rows:
2476
+ payload = EntryPayload.from_fzf_row(fresh_row)
2477
+ if row_identity(payload) == wanted:
2478
+ return payload
2479
+ return None
2480
+
2481
+
2482
+ def row_identity(payload: EntryPayload) -> tuple[str, ...]:
2483
+ """What makes two picker rows the same row, whatever their state."""
2484
+ return (
2485
+ payload.kind,
2486
+ payload.session_name,
2487
+ payload.path or "",
2488
+ payload.host,
2489
+ payload.pane,
2490
+ )
2491
+
2492
+
2493
+ def build_fresh(
2494
+ mode: str, directory: Path, cache_path: Path | None, client: str | None
2495
+ ) -> Fresh:
2496
+ """The opening view of MODE, built while fzf shows the cache: in the
2497
+ picker's directory for fzf, and in the cache for the next open. CLIENT:
2498
+ the invoking client whose pane is still to be found."""
2499
+ prefetch_murmur(mode)
2500
+ if client is not None:
2501
+ _, pane, session = resolve_invoker(client)
2502
+ os.environ["MUSTER_CURRENT_PANE"] = pane
2503
+ os.environ["MUSTER_CURRENT_SESSION"] = session
2504
+ with contextlib.suppress(OSError):
2505
+ write_atomic(directory / "invoker", f"{pane}\t{session}")
2506
+ live: Mapping[str, AgentState | None] | None = None
2507
+ if mode != "agents":
2508
+ live = backend().live_sessions()
2509
+ mode = effective_initial_mode(mode, live)
2510
+ view = build_view(mode, live)
2511
+ rows = [entry.to_fzf_row() for entry in view.entries]
2512
+ write_view_files(str(directory), view)
2513
+ write_atomic(directory / "rows", "".join(f"{row}\n" for row in rows))
2514
+ if cache_path is not None:
2515
+ write_view_cache(cache_path, mode, view, rows)
2516
+ return Fresh(rows)
2517
+
2518
+
2519
+ def fzf_post(sock: Path, action: str, proc: subprocess.Popen[str]) -> None:
2520
+ """Send ACTION to the fzf listening on SOCK; quietly give up when fzf has
2521
+ exited or never opens its socket."""
2522
+ body = action.encode()
2523
+ request = (
2524
+ b"POST / HTTP/1.1\r\nHost: localhost\r\n"
2525
+ + f"Content-Length: {len(body)}\r\n\r\n".encode()
2526
+ + body
2527
+ )
2528
+ deadline = time.monotonic() + 2
2529
+ while proc.poll() is None and time.monotonic() < deadline:
2530
+ try:
2531
+ with socket.socket(socket.AF_UNIX) as conn:
2532
+ conn.settimeout(1)
2533
+ conn.connect(str(sock))
2534
+ conn.sendall(request)
2535
+ conn.recv(64)
2536
+ return
2537
+ except OSError:
2538
+ time.sleep(0.01)
2539
+
2540
+
2541
+ def print_entries(mode: str, crew: bool = False) -> int:
2542
+ view = build_view(mode, crew=crew)
2543
+ if directory := picker_dir():
2544
+ with contextlib.suppress(OSError):
2545
+ write_view_files(str(directory), view)
2546
+ for entry in view.entries:
2547
+ print(entry.to_fzf_row())
2548
+ return 0
2549
+
2550
+
2551
+ def fzf_action(target: str) -> int:
2552
+ """fzf `transform` for a view key: switch to TARGET, keeping the crew
2553
+ toggle; the agents key pressed in the agents view flips it instead.
2554
+
2555
+ The state comes from $FZF_PROMPT (see prompt_text), never from a value
2556
+ fixed when the bindings were built.
2557
+ """
2558
+ mark_switched()
2559
+ mode, crew = prompt_state(os.environ.get("FZF_PROMPT", ""))
2560
+ if target == "agents" and mode == "agents":
2561
+ crew = not crew
2562
+ # "current": the popup was resized. Lay the same view out again, and move
2563
+ # the preview for the new width.
2564
+ resized = target == "current"
2565
+ if resized:
2566
+ target = mode
2567
+ actions = [
2568
+ f"change-prompt({prompt_text(target, crew)})",
2569
+ f"reload({reload_cmd(target, crew)})",
2570
+ ]
2571
+ if resized:
2572
+ actions.insert(0, f"change-preview-window({LAYOUT.preview_window})")
2573
+ print("+".join(actions))
2574
+ return 0
2575
+
2576
+
2577
+ def fzf_enter() -> int:
2578
+ """fzf `transform` for Enter: accept only when a row matches."""
2579
+ if os.environ.get("FZF_MATCH_COUNT", "1") != "0":
2580
+ print("accept")
2581
+ return 0
2582
+
2583
+
2584
+ VIEW_KEYS = {
2585
+ "ctrl-a": "all",
2586
+ "ctrl-s": "sessions",
2587
+ "ctrl-g": "agents",
2588
+ "ctrl-f": "find",
2589
+ }
2590
+
2591
+
2592
+ def _fzf_command(
2593
+ mode: str,
2594
+ query: str = "",
2595
+ *,
2596
+ header: str | None = None,
2597
+ prompt: str | None = None,
2598
+ state_dir: str = "",
2599
+ listen: str = "",
2600
+ ) -> list[str]:
2601
+ self_cmd = sh_quote(sys.argv[0])
2602
+ cmd = [
2603
+ "fzf",
2604
+ "--layout=reverse",
2605
+ "--border",
2606
+ fzf_border(),
2607
+ "--ansi",
2608
+ # Match only the visible display column (field 1), not the payload
2609
+ # fields tacked on for the consumer (kind/session/path/startup/split).
2610
+ # Otherwise typing `dotfiles` would also match every row whose path
2611
+ # happens to contain the word.
2612
+ "--nth",
2613
+ "1",
2614
+ # `begin` ranks earlier match positions higher: query `notes` puts
2615
+ # `notes` (pos 0) above `my-notes` (pos 3). `index` is the empty-query
2616
+ # fallback: with no scoring signal it preserves the input grouping
2617
+ # (pinned -> live -> zoxide -> find) we hand to fzf.
2618
+ "--tiebreak",
2619
+ "begin,index",
2620
+ "--color",
2621
+ f"bg:{CATPPUCCIN['base']},bg+:{CATPPUCCIN['surface0']},fg:{CATPPUCCIN['text']},fg+:{CATPPUCCIN['text']},hl:{CATPPUCCIN['sky']},hl+:{CATPPUCCIN['sky']},border:{CATPPUCCIN['overlay0']},gutter:{CATPPUCCIN['base']},header:{CATPPUCCIN['subtext0']},info:{CATPPUCCIN['overlay0']},prompt:{CATPPUCCIN['lavender']},pointer:{CATPPUCCIN['peach']},marker:{CATPPUCCIN['peach']},spinner:{CATPPUCCIN['sky']},label:{CATPPUCCIN['subtext0']},query:{CATPPUCCIN['text']},preview-bg:{CATPPUCCIN['base']},preview-border:{CATPPUCCIN['overlay0']}",
2622
+ "--delimiter",
2623
+ "\t",
2624
+ "--with-nth",
2625
+ "1",
2626
+ "--border-label",
2627
+ FZF_BORDER_LABEL,
2628
+ "--prompt",
2629
+ prompt_text(mode) if prompt is None else prompt,
2630
+ "--header",
2631
+ header_text(mode) if header is None else header,
2632
+ "--bind",
2633
+ "tab:down,btab:up",
2634
+ ]
2635
+ cmd += ["--bind", kill_bind()]
2636
+ # Enter with nothing to pick must not close the picker: an empty agents
2637
+ # view stays up, saying why, until esc. (accept-non-empty still exits on
2638
+ # an empty list.)
2639
+ cmd += ["--bind", f"enter:transform:{self_cmd} fzf-enter"]
2640
+ # transform: the binding decides per keypress from $FZF_PROMPT, so the
2641
+ # crew toggle holds across view switches (a fixed reload cannot know it).
2642
+ for key, view in VIEW_KEYS.items():
2643
+ cmd += ["--bind", f"{key}:transform:{self_cmd} fzf-action {view}"]
2644
+ if state_dir:
2645
+ # Each reload's `list` leaves its view's header and prompt here.
2646
+ d = Path(state_dir)
2647
+ cmd += [
2648
+ "--bind",
2649
+ f"load:transform-header(cat {sh_quote(str(d / 'header'))})"
2650
+ f"+transform-prompt(cat {sh_quote(str(d / 'prompt'))})",
2651
+ ]
2652
+ cmd += [
2653
+ "--preview-window",
2654
+ LAYOUT.preview_window,
2655
+ "--bind",
2656
+ "ctrl-/:toggle-preview",
2657
+ "--bind",
2658
+ f"resize:transform:{self_cmd} fzf-action current",
2659
+ "--preview",
2660
+ f"{self_cmd} preview --kind {{2}} --session-name {{3}} --path {{4}} --split {{6}} --host {{7}} --pane {{8}} --here {{10}} --socket {{11}} --session-id {{12}}",
2661
+ ]
2662
+ if load_config().fzf_exact:
2663
+ # Substring (literal) matching only. Prefix a token with `'` to opt
2664
+ # back into fuzzy for that token.
2665
+ cmd.append("--exact")
2666
+ if query:
2667
+ cmd.extend(["--query", query])
2668
+ if listen:
2669
+ # A unix socket in the picker's private directory: only this user
2670
+ # can reach it.
2671
+ cmd.append(f"--listen={listen}")
2672
+ return cmd
2673
+
2674
+
2675
+ def fzf_env() -> dict[str, str]:
2676
+ """Our environment without the user's fzf defaults: an inherited
2677
+ --exit-0 or --select-1 would close the picker or pick for them."""
2678
+ return {k: v for k, v in os.environ.items() if not k.startswith("FZF_DEFAULT_OPTS")}
2679
+
2680
+
2681
+ def run_fzf(
2682
+ mode: str,
2683
+ query: str,
2684
+ *,
2685
+ capture: bool,
2686
+ cached: CachedView | None = None,
2687
+ cache_path: Path | None = None,
2688
+ client: str | None = None,
2689
+ ) -> tuple[subprocess.CompletedProcess[str], Fresh | None]:
2690
+ """Run the picker on MODE. CACHE_PATH: where to keep this open's rows.
2691
+
2692
+ With CACHED, fzf starts on its rows while the fresh view is built here and
2693
+ then handed over (see the optimistic-open comment); CLIENT is the invoking
2694
+ client whose pane is still to be found. Returns fzf's result, and for a
2695
+ cached open the fresh view, to check the choice against.
2696
+ """
2697
+ if cached is None:
2698
+ # Only all -> sessions is an automatic switch below: both read murmur.
2699
+ prefetch_murmur(mode)
2700
+ with tempfile.TemporaryDirectory(prefix="muster-") as state_dir:
2701
+ directory = Path(state_dir)
2702
+ env = {**fzf_env(), PICKER_DIR_ENV: state_dir}
2703
+ if cached is not None:
2704
+ write_view_files(state_dir, View([], cached.header, cached.prompt))
2705
+ given = directory / "cached"
2706
+ given.write_text("".join(f"{row}\n" for row in cached.rows))
2707
+ sock = directory / "fzf.sock"
2708
+ cmd = _fzf_command(
2709
+ cached.mode,
2710
+ query=query,
2711
+ header=cached.header,
2712
+ prompt=cached.prompt,
2713
+ state_dir=state_dir,
2714
+ listen=str(sock),
2715
+ )
2716
+ with given.open() as rows_in:
2717
+ proc = subprocess.Popen(
2718
+ cmd,
2719
+ stdin=rows_in,
2720
+ stdout=subprocess.PIPE if capture else None,
2721
+ text=True,
2722
+ env=env,
2723
+ )
2724
+ try:
2725
+ fresh = build_fresh(mode, directory, cache_path, client)
2726
+ if not (directory / "switched").exists():
2727
+ rows_file = sh_quote(str(directory / "rows"))
2728
+ fzf_post(sock, f"reload(cat {rows_file})", proc)
2729
+ out, _ = proc.communicate()
2730
+ except BaseException:
2731
+ proc.kill()
2732
+ proc.wait()
2733
+ raise
2734
+ done = subprocess.CompletedProcess(cmd, proc.returncode, out or "", "")
2735
+ return done, fresh
2736
+ if mode == "agents":
2737
+ # Works outside tmux and from other terminals: no server is
2738
+ # started and no session listed.
2739
+ live: Mapping[str, AgentState | None] = {}
2740
+ else:
2741
+ live = backend().snapshot()
2742
+ if live is None:
2743
+ backend().ensure_server()
2744
+ live = backend().live_sessions()
2745
+ mode = effective_initial_mode(mode, live)
2746
+ view = build_view(mode, live)
2747
+ rows = [entry.to_fzf_row() for entry in view.entries]
2748
+ if cache_path is not None:
2749
+ write_view_cache(cache_path, mode, view, rows)
2750
+ write_view_files(state_dir, view)
2751
+ cmd = _fzf_command(
2752
+ mode,
2753
+ query=query,
2754
+ header=view.header,
2755
+ prompt=view.prompt,
2756
+ state_dir=state_dir,
2757
+ )
2758
+ proc = subprocess.run(
2759
+ cmd,
2760
+ input="\n".join(rows),
2761
+ text=True,
2762
+ capture_output=capture,
2763
+ check=False,
2764
+ env=env,
2765
+ )
2766
+ return proc, None
2767
+
2768
+
2769
+ # fzf's exit codes for "no selection": no match (1) and aborted (130).
2770
+ FZF_NOTHING_CHOSEN = {1, 130}
2771
+
2772
+
2773
+ def fzf(mode: str = "all", query: str = "") -> int:
2774
+ return run_fzf(mode, query, capture=False)[0].returncode
2775
+
2776
+
2777
+ def pick_and_connect(mode: str = "all", query: str = "", client: str = "") -> int:
2778
+ """Run the fzf picker and connect to the selection in one step.
2779
+
2780
+ fzf writes its UI to /dev/tty when stdout is captured, so the picker
2781
+ still renders interactively while we keep the selection in-process.
2782
+ """
2783
+ global INVOKING_CLIENT
2784
+ cache_path = view_cache_path(mode)
2785
+ # A cached open lists nothing before fzf, so it cannot start a server
2786
+ # first (ensure_server); only an agents view or a running server has one.
2787
+ usable = mode == "agents" or PINNED_SOCKET is not None
2788
+ cached = read_view_cache(cache_path) if usable else None
2789
+ if cached is None:
2790
+ prefetch_murmur(mode) # node starts while tmux answers
2791
+ deferred: str | None = None
2792
+ if cached is not None and valid_client_name(client):
2793
+ # The client is all the bindings need now; its pane is found while
2794
+ # fzf already shows the cache, off the path to the first paint.
2795
+ INVOKING_CLIENT = deferred = client
2796
+ else:
2797
+ INVOKING_CLIENT, pane, session = resolve_invoker(client)
2798
+ # Read by every build of the picker's rows, reloads included.
2799
+ os.environ["MUSTER_CURRENT_PANE"] = pane
2800
+ os.environ["MUSTER_CURRENT_SESSION"] = session
2801
+ proc, fresh = run_fzf(
2802
+ mode,
2803
+ query,
2804
+ capture=True,
2805
+ cached=cached,
2806
+ cache_path=cache_path,
2807
+ client=deferred,
2808
+ )
2809
+ if proc.returncode in FZF_NOTHING_CHOSEN:
2810
+ # esc, ctrl-c, or enter with no match: a clean exit. run-shell would
2811
+ # otherwise print "returned 130" over the pane once the popup closes.
2812
+ return 0
2813
+ if proc.returncode != 0:
2814
+ return proc.returncode
2815
+ # Strip only the trailing newline fzf appends, not surrounding whitespace.
2816
+ # Picker rows can end in empty tab-separated fields (e.g. blank `startup`
2817
+ # and `split`); using bare `.strip()` would eat those trailing `\t`s and
2818
+ # leave the row short of `len(FZF_ROW_FIELDS)`.
2819
+ choice = proc.stdout.rstrip("\n")
2820
+ if not choice:
2821
+ return 1
2822
+ payload = EntryPayload.from_fzf_row(choice)
2823
+ if fresh is not None and cached is not None and choice in cached.rows:
2824
+ # Picked from the cached rows: act on the row as it is now. A row
2825
+ # they never had (a view key, ctrl-g's crew agents) came from a
2826
+ # reload and is fresh already; the opening view may not hold it.
2827
+ found = fresh.choice(choice)
2828
+ if found is None:
2829
+ name = payload.session_name or payload.path or "that row"
2830
+ report_failure(f"{name}: gone since the picker opened")
2831
+ return 1
2832
+ payload = found
2833
+ if payload.kind == "agent":
2834
+ return connect_agent(payload)
2835
+ if payload.kind == "rex" and payload.session_id:
2836
+ return rex_select_session(payload.session_id)
2837
+ return connect_resolved(
2838
+ payload.session_name,
2839
+ payload.path,
2840
+ payload.startup,
2841
+ payload.split,
2842
+ derived_name=payload.kind in {"zoxide", "find"},
2843
+ )
2844
+
2845
+
2846
+ def proven_here(here: str, socket: str) -> bool:
2847
+ """A row's server proof still holds: the socket it was made against is
2848
+ still the one muster's own calls reach."""
2849
+ return bool(here and socket and own_socket() == socket)
2850
+
2851
+
2852
+ def connect_agent(payload: EntryPayload) -> int:
2853
+ """Take the user to an agent's pane.
2854
+
2855
+ A pane on this tmux server is selected here (pane ids are unique only per
2856
+ server) and the client moved to it, when the client is on that server too.
2857
+ Anything else, such as a remote host, a private tmux server, or a picker
2858
+ run outside tmux, is murmur's to reach: ``murmur jump``.
2859
+ """
2860
+ if (
2861
+ proven_here(payload.here, payload.socket)
2862
+ and inside_own_server()
2863
+ and payload.pane
2864
+ ):
2865
+ # Pinned: the calls below name the proven socket itself, so an alias
2866
+ # retargeted after this check cannot redirect them.
2867
+ with pinned_server(payload.socket):
2868
+ tmux_cmd("select-window", "-t", payload.pane)
2869
+ tmux_cmd("select-pane", "-t", payload.pane)
2870
+ backend().switch(payload.session_name, target=payload.pane)
2871
+ return 0
2872
+ exe = murmur_command()
2873
+ if exe is None or not payload.jump_target:
2874
+ print("agent: murmur is needed to reach this agent", file=sys.stderr)
2875
+ return 1
2876
+ # stdio stays inherited: jump may need the tty (ssh, a hardware-key tap).
2877
+ code = murmur_jump_in_rex(
2878
+ lambda: (
2879
+ subprocess.run(
2880
+ [exe, "jump", payload.jump_target], env=murmur_jump_env(), check=False
2881
+ ).returncode
2882
+ )
2883
+ )
2884
+ if code != 0:
2885
+ report_failure(f"murmur jump {payload.jump_target} failed (exit {code})")
2886
+ return 1
2887
+ return 0
2888
+
2889
+
2890
+ def update_last(name: str) -> None:
2891
+ STATE_DIR.mkdir(parents=True, exist_ok=True)
2892
+ LAST_FILE.write_text(name + "\n")
2893
+
2894
+
2895
+ class LiveSessions(dict[str, AgentState | None]):
2896
+ """Live session -> state, plus the sessions some client has attached
2897
+ and each session's id."""
2898
+
2899
+ attached: frozenset[str] = frozenset()
2900
+
2901
+ def __init__(self) -> None:
2902
+ super().__init__()
2903
+ self.ids: dict[str, str] = {} # name -> tmux session id ($N)
2904
+ self.paths: dict[str, str] = {} # name -> #{session_path}
2905
+ self.activity: dict[str, int] = {} # name -> #{session_activity}
2906
+ # name -> (active, panes, cwd of the active pane), one per window
2907
+ self.windows: dict[str, list[tuple[bool, int, str]]] = {}
2908
+
2909
+ def location(self, name: str) -> tuple[str, int]:
2910
+ """Where session NAME is: its active window's cwd, and how many other
2911
+ directories its windows sit in."""
2912
+ windows = self.windows.get(name, [])
2913
+ here = next((cwd for active, _, cwd in windows if active), "")
2914
+ here = here or self.paths.get(name, "")
2915
+ others = {os.path.realpath(cwd) for _, _, cwd in windows if cwd}
2916
+ others.discard(os.path.realpath(here) if here else "")
2917
+ return here, len(others)
2918
+
2919
+ def counts(self, name: str) -> str:
2920
+ """counts_cell for session NAME, or "" when its windows are unknown."""
2921
+ windows = self.windows.get(name, [])
2922
+ if not windows:
2923
+ return ""
2924
+ return counts_cell(len(windows), sum(panes for _, panes, _ in windows))
2925
+
2926
+ def dirs(self) -> set[str]:
2927
+ """Every directory a live session is rooted at or has a window in."""
2928
+ found = {p for p in self.paths.values() if p}
2929
+ found |= {cwd for ws in self.windows.values() for _, _, cwd in ws if cwd}
2930
+ return {os.path.realpath(p) for p in found}
2931
+
2932
+
2933
+ class TmuxBackend:
2934
+ """tmux sessions. A class so tests can stub one method at a time."""
2935
+
2936
+ def live_sessions(self) -> dict[str, AgentState | None]:
2937
+ return self.snapshot() or {}
2938
+
2939
+ def snapshot(self) -> LiveSessions | None:
2940
+ """Live session -> strongest murmur state, sessions and windows in one
2941
+ tmux call.
2942
+
2943
+ None when no server runs, so a caller can start one and ask again.
2944
+ """
2945
+ # Two lines per session: its fields, then its path, each keyed by the
2946
+ # session id; then one line per window, keyed the same way. The two
2947
+ # commands run back to back in the server, so they see one state.
2948
+ # Free text (name, path) comes last on its line.
2949
+ result = tmux_cmd(
2950
+ "list-sessions",
2951
+ "-F",
2952
+ "#{session_attached}\t#{session_id}\t#{session_program_state}"
2953
+ "\t#{session_activity}\t#{session_name}"
2954
+ "\n#{session_id}\tP\t#{session_path}",
2955
+ ";",
2956
+ "list-windows",
2957
+ "-a",
2958
+ "-F",
2959
+ "#{session_id}\tW\t#{window_active}\t#{window_panes}\t#{pane_current_path}",
2960
+ check=False,
2961
+ )
2962
+ if result.returncode != 0:
2963
+ return None
2964
+ live = LiveSessions()
2965
+ attached: set[str] = set()
2966
+ names: dict[str, str] = {} # id -> name
2967
+ paths: dict[str, str] = {}
2968
+ window_line = re.compile(r"(\$[0-9]+)\tW\t([01])\t([0-9]+)\t(.*)")
2969
+ windows: list[re.Match[str]] = []
2970
+ for line in result.stdout.splitlines():
2971
+ if m := re.fullmatch(r"(\$[0-9]+)\tP\t(.*)", line):
2972
+ paths[m[1]] = m[2]
2973
+ continue
2974
+ if m := window_line.fullmatch(line):
2975
+ windows.append(m)
2976
+ continue
2977
+ fields = [*line.split("\t", 4), "", "", "", ""]
2978
+ clients, sid, raw, activity, name = fields[:5]
2979
+ if name.strip() and re.fullmatch(r"\$[0-9]+", sid):
2980
+ live[name] = AgentState.parse(raw)
2981
+ live.ids[name] = sid
2982
+ live.activity[name] = int(activity) if activity.isdigit() else 0
2983
+ names[sid] = name
2984
+ if clients not in {"", "0"}:
2985
+ attached.add(name)
2986
+ live.attached = frozenset(attached)
2987
+ live.paths = {names[sid]: path for sid, path in paths.items() if sid in names}
2988
+ for m in windows:
2989
+ if m[1] in names:
2990
+ window = (m[2] == "1", int(m[3]), m[4])
2991
+ live.windows.setdefault(names[m[1]], []).append(window)
2992
+ return live
2993
+
2994
+ def exists(self, name: str) -> bool:
2995
+ return (
2996
+ tmux_cmd(
2997
+ "has-session",
2998
+ "-t",
2999
+ exact_session_target(name),
3000
+ check=False,
3001
+ capture=True,
3002
+ ).returncode
3003
+ == 0
3004
+ )
3005
+
3006
+ def switch(self, name: str, target: str | None = None) -> None:
3007
+ """Switch to NAME, or to TARGET (a session id) when the caller has one.
3008
+
3009
+ An id is the only unambiguous target: ``=$0`` means id $0, even when a
3010
+ session is literally named "$0".
3011
+ """
3012
+ target = target or exact_session_target(name)
3013
+ if os.environ.get("TMUX"):
3014
+ # The client that opened the picker, not whichever tmux calls
3015
+ # current (a popup has no pane of its own).
3016
+ client = ["-c", INVOKING_CLIENT] if INVOKING_CLIENT else []
3017
+ tmux_cmd("switch-client", *client, "-t", target, capture=False)
3018
+ elif in_rex():
3019
+ rex_open_tmux_tab(name, target)
3020
+ else:
3021
+ tmux_cmd("attach-session", "-t", target, capture=False)
3022
+ update_last(name)
3023
+
3024
+ def ensure_server(self) -> None:
3025
+ """Start the server if none runs, so a restoring tmux can bring back
3026
+ its saved sessions before they are listed.
3027
+
3028
+ Plain tmux has nothing to restore: ``start-server`` with no sessions
3029
+ exits at once (exit-empty) and the picker lists nothing, as before.
3030
+ """
3031
+ if server_running():
3032
+ return
3033
+ start = ("start-server",)
3034
+ if not start_server_in_own_scope(start):
3035
+ tmux_cmd(*start, check=False)
3036
+
3037
+ def create(
3038
+ self, name: str, path: str, startup: str | None, split: str = ""
3039
+ ) -> None:
3040
+ # realpath: session_path then names the directory, not a symlink that
3041
+ # may later point elsewhere (see live_session_for_path).
3042
+ # "#" is escaped: tmux format-expands -c.
3043
+ start_dir = os.path.realpath(path).replace("#", "##")
3044
+ new_session = ("new-session", "-d", "-s", name, "-c", start_dir)
3045
+ if not server_running():
3046
+ # Starting the server may restore NAME; new-session would then
3047
+ # fail with "duplicate session". Start it first, then look again.
3048
+ self.ensure_server()
3049
+ if self.exists(name):
3050
+ return
3051
+ if server_running():
3052
+ tmux_cmd(*new_session, capture=False)
3053
+ elif not start_server_in_own_scope(new_session):
3054
+ # The server exited again (nothing restored): start it with the
3055
+ # session, in its own scope when that applies.
3056
+ tmux_cmd(*new_session, capture=False)
3057
+ if startup:
3058
+ tmux_cmd(
3059
+ "send-keys",
3060
+ "-t",
3061
+ active_pane_target(name),
3062
+ startup,
3063
+ "C-m",
3064
+ capture=False,
3065
+ )
3066
+ if split in ("vertical", "horizontal"):
3067
+ tmux_cmd(
3068
+ "split-window",
3069
+ "-h" if split == "vertical" else "-v",
3070
+ "-t",
3071
+ active_pane_target(name),
3072
+ "-c",
3073
+ path,
3074
+ capture=False,
3075
+ )
3076
+
3077
+ def last_candidates(self) -> list[str]:
3078
+ result = tmux_cmd(
3079
+ "display-message", "-p", "#{client_last_session}", check=False
3080
+ )
3081
+ if result.returncode != 0:
3082
+ return []
3083
+ name = result.stdout.strip()
3084
+ return [name] if name else []
3085
+
3086
+ def current_cwd(self, ref: str) -> str:
3087
+ return pane_cwd(ref)
3088
+
3089
+
3090
+ BACKEND = TmuxBackend()
3091
+
3092
+
3093
+ def backend() -> TmuxBackend:
3094
+ return BACKEND
3095
+
3096
+
3097
+ def connect_resolved(
3098
+ session_name: str,
3099
+ path: str | None,
3100
+ startup: str | None,
3101
+ split: str = DEFAULT_SPLIT,
3102
+ *,
3103
+ derived_name: bool = False,
3104
+ ) -> int:
3105
+ """Switch to SESSION_NAME, creating it at PATH if needed.
3106
+
3107
+ ``derived_name`` marks a name computed from PATH (not a configured or live
3108
+ session's own name): it may collide with another directory's session, so
3109
+ it gets a suffix then.
3110
+ """
3111
+ if in_rex() and path is not None:
3112
+ for sid, label in rex_sessions():
3113
+ if label == session_name:
3114
+ return rex_select_session(sid)
3115
+ if backend().exists(session_name):
3116
+ backend().switch(session_name)
3117
+ return 0
3118
+ return rex_create_and_select(session_name, path, startup, split)
3119
+
3120
+ if derived_name and path:
3121
+ if live := live_session_for_path(path):
3122
+ backend().switch(live.name, target=live.id)
3123
+ return 0
3124
+ session_name = free_name_for_path(session_name)
3125
+ if backend().exists(session_name):
3126
+ backend().switch(session_name)
3127
+ return 0
3128
+
3129
+ if path is None:
3130
+ print(f"No such session or path: {session_name}", file=sys.stderr)
3131
+ return 1
3132
+
3133
+ backend().create(session_name, path, startup, split)
3134
+ backend().switch(session_name)
3135
+ return 0
3136
+
3137
+
3138
+ def pane_cwd(pane_id: str) -> str:
3139
+ """Read a pane's cwd from tmux instead of taking it on a command line.
3140
+
3141
+ SECURITY: the key binding that reaches here runs under ``run-shell``,
3142
+ which format-expands its argument and hands the result to ``sh -c``.
3143
+ Interpolating ``#{pane_current_path}`` there is command injection --
3144
+ a directory whose name contains a newline splits the shell line and
3145
+ the second line runs as a command. ``#{pane_id}`` is minted by tmux
3146
+ (``%[0-9]+``) and is the only value safe to interpolate, so the
3147
+ binding passes that and we fetch the path over a pipe.
3148
+ """
3149
+ result = tmux_bytes("display-message", "-p", "-t", pane_id, "#{pane_current_path}")
3150
+ if result.returncode != 0:
3151
+ return ""
3152
+ return os.fsdecode(result.stdout).removesuffix("\n")
3153
+
3154
+
3155
+ @dataclass(frozen=True)
3156
+ class LiveSession:
3157
+ id: str # "$N": the only target that cannot alias another session's name
3158
+ name: str
3159
+
3160
+
3161
+ def format_escape(text: str) -> str:
3162
+ """Escape TEXT as a literal inside a tmux format conditional."""
3163
+ return text.replace("#", "##").replace(",", "#,").replace("}", "#}")
3164
+
3165
+
3166
+ def live_session_for_path(path: str) -> LiveSession | None:
3167
+ """The live session rooted at PATH, if any.
3168
+
3169
+ tmux does the comparison (``list-sessions -f``) and we read only session
3170
+ ids: a path may hold any byte, including our own record separators, so it
3171
+ is never parsed out of tmux output. Two spellings match: the realpath
3172
+ (what muster creates sessions with) and the path as given (what older muster
3173
+ stored, possibly through a symlink).
3174
+
3175
+ Accepted limitation: a symlink retargeted after its session was created
3176
+ still reaches that session when connected through the same symlink string.
3177
+ The real path is always exact.
3178
+ """
3179
+ given = os.path.expanduser(path)
3180
+ if not os.path.isabs(given):
3181
+ given = os.path.join(os.getcwd(), given)
3182
+ wanted = {os.path.realpath(given), given}
3183
+ clauses = [f"#{{==:#{{session_path}},{format_escape(p)}}}" for p in sorted(wanted)]
3184
+ condition = clauses[0] if len(clauses) == 1 else f"#{{||:{','.join(clauses)}}}"
3185
+ found = tmux_cmd(
3186
+ "list-sessions", "-f", condition, "-F", "#{session_id}", check=False
3187
+ )
3188
+ ids = found.stdout.split()
3189
+ if found.returncode != 0 or not ids:
3190
+ return None
3191
+ name = tmux_bytes("display-message", "-p", "-t", ids[0], "#{session_name}")
3192
+ return LiveSession(ids[0], os.fsdecode(name.stdout).removesuffix("\n"))
3193
+
3194
+
3195
+ def free_name_for_path(name: str) -> str:
3196
+ """NAME, or NAME-2, NAME-3... when sanitizing made it collide.
3197
+
3198
+ Sanitizing maps distinct paths (``a.b`` and ``a_b``) to one name. Callers
3199
+ look the directory's own session up first (live_session_for_path).
3200
+ """
3201
+ candidate, n = name, 1
3202
+ while backend().exists(candidate):
3203
+ n += 1
3204
+ candidate = f"{name}-{n}"
3205
+ return candidate
3206
+
3207
+
3208
+ def connect(target: str) -> int:
3209
+ target = expand(target)
3210
+ sessions_by_name = {session.name: session for session in load_config().sessions}
3211
+ session = sessions_by_name.get(target)
3212
+ if session:
3213
+ return connect_resolved(
3214
+ session.name,
3215
+ expand(session.path),
3216
+ session.startup,
3217
+ session.split,
3218
+ )
3219
+ # If `target` already names a live tmux session, attach to it directly.
3220
+ # Without this, a bare session name that also happens to be a directory
3221
+ # in the current pane's CWD (e.g. `foot` while sitting in
3222
+ # ~/dotfiles, where stow packages mirror live session names) gets mangled
3223
+ # into `dotfiles/foot` by session_name_for_path below, and a new
3224
+ # session is spawned instead of switching to the running one.
3225
+ if backend().exists(target):
3226
+ return connect_resolved(target, None, None, DEFAULT_SPLIT)
3227
+ # Either a real path (create/attach a session rooted there) or a bare
3228
+ # session name (attach if it exists, error otherwise — connect_resolved
3229
+ # handles both via its `path is None` branch).
3230
+ path = target if Path(target).exists() else None
3231
+ name = session_name_for_path(target) if path else target
3232
+ return connect_resolved(name, path, None, DEFAULT_SPLIT, derived_name=True)
3233
+
3234
+
3235
+ def clear_agent(jump_target: str) -> int:
3236
+ """Dismiss the crash murmur recorded for an agent: ``murmur clear
3237
+ --target``. murmur clears only its own crash records, and only this
3238
+ host's, so a live agent or a remote one is left as it is."""
3239
+ exe = murmur_command()
3240
+ if exe and jump_target:
3241
+ with contextlib.suppress(OSError):
3242
+ subprocess.run(
3243
+ [exe, "clear", "--target", jump_target],
3244
+ stdin=subprocess.DEVNULL,
3245
+ stdout=subprocess.DEVNULL,
3246
+ stderr=subprocess.DEVNULL,
3247
+ check=False,
3248
+ )
3249
+ return 0
3250
+
3251
+
3252
+ def kill(kind: str, session_id: str, client: str = "", jump_target: str = "") -> int:
3253
+ """Kill the session with tmux id SESSION_ID (``$N``), from a picker row
3254
+ of KIND; on an agent row, dismiss its crash instead (clear_agent).
3255
+
3256
+ Only live session rows carry an id, so any other row is a no-op. A name
3257
+ is no target: ``=$0`` means id $0 and ``=a.b`` means window b. The
3258
+ session the invoking client is attached to is refused with a message.
3259
+ """
3260
+ if kind == "agent":
3261
+ return clear_agent(jump_target)
3262
+ if kind == "rex" and session_id.startswith("session:"):
3263
+ rex_call("kill", session_id)
3264
+ return 0
3265
+ if kind not in ("default", "tmux") or not re.fullmatch(r"\$[0-9]+", session_id):
3266
+ return 0
3267
+ mark_switched() # its reload follows; the handover must not undo it
3268
+ listed = tmux_bytes("list-sessions", "-F", "#{session_id}\t#{session_name}")
3269
+ names = dict(
3270
+ line.partition("\t")[::2] for line in os.fsdecode(listed.stdout).splitlines()
3271
+ )
3272
+ if session_id not in names:
3273
+ return 0
3274
+ client = resolve_invoker(client)[0] or ""
3275
+ if client:
3276
+ out = tmux_bytes("list-clients", "-F", "#{client_name}\t#{session_id}")
3277
+ for line in os.fsdecode(out.stdout).splitlines():
3278
+ cname, _, current = line.partition("\t")
3279
+ if cname == client and current == session_id:
3280
+ tmux_cmd(
3281
+ "display-message",
3282
+ "-c",
3283
+ client,
3284
+ "-d",
3285
+ "5000",
3286
+ f"muster: not killing the current session ({names[session_id]})",
3287
+ check=False,
3288
+ )
3289
+ return 0
3290
+ tmux_cmd("kill-session", "-t", session_id, check=False)
3291
+ return 0
3292
+
3293
+
3294
+ def last() -> int:
3295
+ # `muster last` is typically bound to a hotkey (prefix-L). When the
3296
+ # last-known session has been killed, the right behavior is a silent
3297
+ # no-op — not respawning a configured session from scratch (which is
3298
+ # what `connect()` would do for a configured name) and not erroring
3299
+ # with "No such session or path" for an unconfigured one.
3300
+ #
3301
+ # We collect both pointers (the backend's own notion of "last", then our
3302
+ # LAST_FILE) and switch to the first that's still live. If none are,
3303
+ # exit 0 (with a tmux message when inside tmux).
3304
+ candidates: list[str] = list(backend().last_candidates())
3305
+ if LAST_FILE.exists():
3306
+ name = LAST_FILE.read_text().strip()
3307
+ if name and name not in candidates:
3308
+ candidates.append(name)
3309
+ for name in candidates:
3310
+ if backend().exists(name):
3311
+ backend().switch(name)
3312
+ return 0
3313
+ if os.environ.get("TMUX"):
3314
+ tmux_cmd("display-message", "muster: no previous session", check=False)
3315
+ return 0
3316
+
3317
+
3318
+ MODES = ["all", "sessions", "find", "agents"]
3319
+
3320
+
3321
+ # The tmux client the picker was opened from; failures are shown on it, not on
3322
+ # whichever client tmux considers current.
3323
+ INVOKING_CLIENT: str | None = None
3324
+
3325
+
3326
+ def valid_client_name(name: str) -> bool:
3327
+ """A tty path or "client-N": safe as a -t/-c target, nothing to split."""
3328
+ return bool(name) and re.fullmatch(r"[A-Za-z0-9_./:@-]+", name) is not None
3329
+
3330
+
3331
+ def resolve_invoker(given: str = "") -> tuple[str | None, str, str]:
3332
+ """(client, pane id, session name) of whoever opened the picker, with one
3333
+ ``display-message`` before fzf starts. The client is the one the key
3334
+ binding named, else (in tmux) the one tmux reports now. The pane and
3335
+ session are read only from a client of muster's own server; in a popup
3336
+ $TMUX_PANE is unset, so they come from the client itself."""
3337
+ client = given if valid_client_name(given) else None
3338
+ inside = inside_own_server()
3339
+ if client and not inside:
3340
+ return client, "", ""
3341
+ if not client and not os.environ.get("TMUX"):
3342
+ return None, "", ""
3343
+ where = "#{pane_id}\t#{session_name}" if inside else ""
3344
+ if client:
3345
+ result = tmux_bytes("display-message", "-p", "-t", client, where)
3346
+ fields = [client]
3347
+ else:
3348
+ # In a pane (not a popup) $TMUX_PANE is where the picker runs. Asked
3349
+ # of the server the client is on; inside, that is muster's own.
3350
+ own_pane = os.environ.get("TMUX_PANE", "")
3351
+ target = ["-t", own_pane] if inside and _is_pane_id(own_pane) else []
3352
+ result = client_tmux(
3353
+ "display-message", "-p", *target, f"#{{client_name}}\t{where}"
3354
+ )
3355
+ fields = []
3356
+ text = (
3357
+ os.fsdecode(result.stdout).removesuffix("\n") if result.returncode == 0 else ""
3358
+ )
3359
+ fields += text.split("\t", 2 - len(fields))
3360
+ name, pane, session = [*fields, "", "", ""][:3]
3361
+ if not _is_pane_id(pane):
3362
+ pane, session = "", ""
3363
+ return name or None, pane, session
3364
+
3365
+
3366
+ def client_tmux(*args: str) -> subprocess.CompletedProcess[bytes]:
3367
+ """tmux on the server the invoking client is on: the socket in $TMUX.
3368
+
3369
+ Never the MUSTER_TMUX_SOCKET_* override or a pinned socket: a client name
3370
+ only means something on its own server.
3371
+ """
3372
+ socket = os.environ.get("TMUX", "").split(",")[0]
3373
+ return subprocess.run(
3374
+ ["tmux", *(["-S", socket] if socket else []), *args],
3375
+ check=False,
3376
+ capture_output=True,
3377
+ )
3378
+
3379
+
3380
+ def report_failure(message: str) -> None:
3381
+ """Make a failure readable after a popup closes: stderr, a tmux message on
3382
+ the invoking client when in tmux, and a short pause on a tty."""
3383
+ print(message, file=sys.stderr)
3384
+ if os.environ.get("TMUX"):
3385
+ target = ["-c", INVOKING_CLIENT] if INVOKING_CLIENT else []
3386
+ client_tmux("display-message", *target, "-d", "5000", message)
3387
+ pause_for_error()
3388
+
3389
+
3390
+ def pause_for_error() -> None:
3391
+ """display-popup -E closes on exit; leave the message readable."""
3392
+ if sys.stderr.isatty():
3393
+ time.sleep(2)
3394
+
3395
+
3396
+ def main(argv: Iterable[str] | None = None) -> int:
3397
+ try:
3398
+ parser = argparse.ArgumentParser(
3399
+ prog="muster",
3400
+ description="tmux session picker: pinned and live sessions, zoxide,"
3401
+ " a directory scan and, with murmur, coding agents.",
3402
+ )
3403
+ parser.add_argument("--version", action="version", version=f"muster {VERSION}")
3404
+ # fzf-action, fzf-enter and preview serve the picker's own bindings;
3405
+ # they work but are left out of the list.
3406
+ sub = parser.add_subparsers(
3407
+ dest="cmd",
3408
+ required=True,
3409
+ metavar="{pick-and-connect,picker,list,connect,last,kill}",
3410
+ )
3411
+ views = "view: all (default), sessions, find or agents"
3412
+
3413
+ p_pick_connect = sub.add_parser(
3414
+ "pick-and-connect",
3415
+ help="open the picker and switch to the chosen row",
3416
+ description="Open the picker; Enter switches to the session (creating"
3417
+ " it in its directory if needed) or jumps to the agent.",
3418
+ )
3419
+ p_pick_connect.add_argument("--mode", choices=MODES, default="all", help=views)
3420
+ p_pick_connect.add_argument("--query", default="", help="initial query")
3421
+ p_pick_connect.add_argument(
3422
+ "--client",
3423
+ default="",
3424
+ help="tmux client the picker was opened from; messages and the"
3425
+ " switch go to it (the muster.tmux keys pass it)",
3426
+ )
3427
+
3428
+ p_pick = sub.add_parser(
3429
+ "picker", help="open the picker and print the chosen row"
3430
+ )
3431
+ p_pick.add_argument("--mode", choices=MODES, default="all", help=views)
3432
+ p_pick.add_argument("--query", default="", help="initial query")
3433
+
3434
+ p_list = sub.add_parser("list", help="print the picker's rows")
3435
+ p_list.add_argument("--mode", choices=MODES, default="all", help=views)
3436
+ p_list.add_argument(
3437
+ "--crew", action="store_true", help="include orchestrated agents"
3438
+ )
3439
+ p_list.add_argument("--prompt", default="", help=argparse.SUPPRESS)
3440
+
3441
+ p_connect = sub.add_parser(
3442
+ "connect",
3443
+ help="switch to a session or directory",
3444
+ description="Switch to TARGET: a pinned or live session name, or a"
3445
+ " directory (its live session, else a new one rooted there).",
3446
+ )
3447
+ p_connect.add_argument("target", nargs="?", default="")
3448
+ p_connect.add_argument(
3449
+ "--pane",
3450
+ default="",
3451
+ help="use this tmux pane's directory as the target (prefix T)",
3452
+ )
3453
+
3454
+ sub.add_parser(
3455
+ "last", help="switch to the previous session, if it is still live"
3456
+ )
3457
+
3458
+ p_kill = sub.add_parser(
3459
+ "kill",
3460
+ help="kill a live session by id, or clear an agent's crash"
3461
+ " (ctrl-x in the picker)",
3462
+ description="Kill the live session with tmux id --session-id ($N)."
3463
+ " Only --kind=tmux or default rows count, and never the session"
3464
+ " --client is in. With --kind=agent, dismiss the crash murmur"
3465
+ " recorded for --jump-target instead.",
3466
+ )
3467
+ p_kill.add_argument("--kind", default="", help="the row's kind")
3468
+ p_kill.add_argument("--session-id", default="", help="tmux session id, $N")
3469
+ p_kill.add_argument(
3470
+ "--jump-target", default="", help="agent rows: murmur's jump_target"
3471
+ )
3472
+ p_kill.add_argument(
3473
+ "--client", default="", help="tmux client the picker was opened from"
3474
+ )
3475
+
3476
+ # fzf's transform bindings for the view keys and Enter; not for people.
3477
+ p_action = sub.add_parser("fzf-action")
3478
+ p_action.add_argument("view", choices=[*MODES, "current"])
3479
+ sub.add_parser("fzf-enter")
3480
+
3481
+ p_preview = sub.add_parser("preview")
3482
+ p_preview.add_argument("--kind", default="")
3483
+ p_preview.add_argument("--session-name", default="")
3484
+ p_preview.add_argument("--path", default="")
3485
+ p_preview.add_argument("--split", default=DEFAULT_SPLIT)
3486
+ p_preview.add_argument("--host", default="")
3487
+ p_preview.add_argument("--pane", default="")
3488
+ p_preview.add_argument("--here", default="")
3489
+ p_preview.add_argument("--socket", default="")
3490
+ p_preview.add_argument("--session-id", default="")
3491
+
3492
+ args = parser.parse_args(list(argv) if argv is not None else None)
3493
+ pin_own_server()
3494
+ set_layout(terminal_columns())
3495
+
3496
+ if args.cmd == "list":
3497
+ mode, crew = args.mode, args.crew
3498
+ if args.prompt:
3499
+ mode, crew = prompt_state(args.prompt)
3500
+ return print_entries(mode, crew)
3501
+ if args.cmd == "fzf-action":
3502
+ return fzf_action(args.view)
3503
+ if args.cmd == "fzf-enter":
3504
+ return fzf_enter()
3505
+ if args.cmd == "kill":
3506
+ return kill(
3507
+ row_unescape(args.kind),
3508
+ row_unescape(args.session_id),
3509
+ args.client,
3510
+ row_unescape(args.jump_target),
3511
+ )
3512
+ if args.cmd == "picker":
3513
+ return fzf(args.mode, query=args.query)
3514
+ if args.cmd == "pick-and-connect":
3515
+ return pick_and_connect(args.mode, query=args.query, client=args.client)
3516
+ if args.cmd == "connect":
3517
+ target = backend().current_cwd(args.pane) if args.pane else args.target
3518
+ if not target:
3519
+ print("connect: no target", file=sys.stderr)
3520
+ return 1
3521
+ return connect(target)
3522
+ if args.cmd == "preview":
3523
+ # fzf hands over the row's fields still escaped.
3524
+ return preview(
3525
+ *map(
3526
+ row_unescape,
3527
+ (
3528
+ args.path,
3529
+ args.session_name,
3530
+ args.kind,
3531
+ args.split,
3532
+ args.host,
3533
+ args.pane,
3534
+ args.here,
3535
+ args.socket,
3536
+ args.session_id,
3537
+ ),
3538
+ )
3539
+ )
3540
+ if args.cmd == "last":
3541
+ return last()
3542
+ return 1
3543
+ except ConfigError as exc:
3544
+ print(exc, file=sys.stderr)
3545
+ return 1
3546
+ except subprocess.CalledProcessError as exc:
3547
+ detail = (exc.stderr or "").strip()
3548
+ report_failure(detail or f"tmux failed: {exc}")
3549
+ return 1
3550
+
3551
+
3552
+ if __name__ == "__main__":
3553
+ raise SystemExit(main())