psmux 3.3.4

Terminal multiplexer for Windows - tmux alternative for PowerShell and Windows Terminal
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
# Developer Integration Guide


This guide is for developers who want to build tools, scripts, IDE extensions, or automation pipelines that use psmux on Windows, especially if you already have tmux integrations on Linux/macOS.

## Why psmux for Developers


psmux implements the same CLI protocol and command set as tmux. If your project already integrates with tmux via subprocess calls, control mode, or libraries like libtmux, you can run on Windows with minimal or zero code changes.

Key points:

- **Same binary name**: psmux installs `tmux.exe` as an alias. Existing scripts that call `tmux` will find psmux on the PATH.
- **Same commands**: 83 tmux commands with the same flags, arguments, and output formats.
- **Same IDs**: `$N` (session), `@N` (window), `%N` (pane) stable IDs follow the tmux scheme.
- **Same control mode**: `-C`/`-CC` wire protocol with `%begin`/`%end` framing, notifications, and output escaping.
- **Same config**: Reads `~/.tmux.conf` directly. Your config, key bindings, and themes transfer as-is.
- **Same format engine**: 140+ format variables with conditionals, loops, regex, and string operations.

## Installation


```powershell
# Cargo (recommended for developers)

cargo install --git https://github.com/psmux/psmux

# Scoop

scoop bucket add extras
scoop install psmux

# Winget

winget install psmux

# Chocolatey

choco install psmux
```

After installation, `psmux`, `pmux`, and `tmux` are all available as commands. Use whichever fits your project.

## Quick Start: Subprocess Integration


The simplest integration pattern. Works with any language that can spawn processes.

### Python


```python
import subprocess
import platform

def mux_cmd(args, encoding="utf-8"):
    """Run a tmux/psmux command and return stdout."""
    kwargs = {"capture_output": True, "text": True}
    if platform.system() == "Windows":
        kwargs["encoding"] = encoding
    result = subprocess.run(["tmux"] + args, **kwargs)
    if result.returncode != 0:
        raise RuntimeError(f"tmux command failed: {result.stderr}")
    return result.stdout.strip()

# Create a session

mux_cmd(["new-session", "-d", "-s", "dev", "-x", "120", "-y", "30"])

# Send a command

mux_cmd(["send-keys", "-t", "dev", "echo hello", "Enter"])

# Read pane output

content = mux_cmd(["capture-pane", "-t", "dev", "-p"])
print(content)

# Query format variables

pane_path = mux_cmd(["display-message", "-t", "dev", "-p", "#{pane_current_path}"])

# List all sessions

sessions = mux_cmd(["list-sessions", "-F", "#{session_name}"])

# Clean up

mux_cmd(["kill-session", "-t", "dev"])
```

### PowerShell


```powershell
function Invoke-Mux {
    param([string[]]$Args)
    $result = & tmux @Args 2>&1
    if ($LASTEXITCODE -ne 0) { throw "tmux command failed: $result" }
    return $result
}

# Create and interact with a session

Invoke-Mux new-session -d -s dev -x 120 -y 30
Invoke-Mux send-keys -t dev "Get-Process | Select -First 5" Enter
Start-Sleep -Seconds 1
$content = Invoke-Mux capture-pane -t dev -p
Write-Host $content
Invoke-Mux kill-session -t dev
```

### Node.js


```javascript
const { execFileSync } = require("child_process");

function muxCmd(args) {
  return execFileSync("tmux", args, { encoding: "utf-8" }).trim();
}

// Create a session
muxCmd(["new-session", "-d", "-s", "dev", "-x", "120", "-y", "30"]);

// Send keys
muxCmd(["send-keys", "-t", "dev", "echo hello", "Enter"]);

// Capture output
const content = muxCmd(["capture-pane", "-t", "dev", "-p"]);
console.log(content);

// Clean up
muxCmd(["kill-session", "-t", "dev"]);
```

### Go


```go
package main

import (
    "fmt"
    "os/exec"
    "strings"
)

func muxCmd(args ...string) (string, error) {
    out, err := exec.Command("tmux", args...).Output()
    return strings.TrimSpace(string(out)), err
}

func main() {
    muxCmd("new-session", "-d", "-s", "dev", "-x", "120", "-y", "30")
    muxCmd("send-keys", "-t", "dev", "echo hello", "Enter")
    content, _ := muxCmd("capture-pane", "-t", "dev", "-p")
    fmt.Println(content)
    muxCmd("kill-session", "-t", "dev")
}
```

### Rust


```rust
use std::process::Command;

fn mux_cmd(args: &[&str]) -> String {
    let output = Command::new("tmux")
        .args(args)
        .output()
        .expect("failed to run tmux/psmux");
    String::from_utf8_lossy(&output.stdout).trim().to_string()
}

fn main() {
    mux_cmd(&["new-session", "-d", "-s", "dev", "-x", "120", "-y", "30"]);
    mux_cmd(&["send-keys", "-t", "dev", "echo hello", "Enter"]);
    let content = mux_cmd(&["capture-pane", "-t", "dev", "-p"]);
    println!("{}", content);
    mux_cmd(&["kill-session", "-t", "dev"]);
}
```

## libtmux Integration


[libtmux](https://github.com/tmux-python/libtmux) is the most popular Python library for controlling tmux programmatically. psmux is compatible with libtmux because it implements the same commands and output formats.

### Setup


```powershell
pip install libtmux
```

### Basic Usage


```python
import libtmux

# Connect to the psmux server

server = libtmux.Server(socket_name="default")

# List sessions

for session in server.sessions:
    print(f"{session.name} ({session.id}): {len(session.windows)} windows")

# Work with a session

session = server.sessions[0]

# Create a window

window = session.new_window(window_name="build")

# Access panes

pane = window.panes[0]

# Send commands

pane.send_keys("cargo build")

# Capture output

lines = pane.capture_pane()
for line in lines:
    print(line)

# Kill the window

window.kill()
```

### Windows Encoding Fix


libtmux uses the Unicode character U+241E (SYMBOL FOR RECORD SEPARATOR) internally to split format fields when querying tmux. On Linux, this works transparently because both tmux and Python use UTF-8.

On Windows, Python's `subprocess.Popen(text=True)` defaults to cp1252 encoding, which garbles the 3-byte UTF-8 sequence for U+241E. This causes `server.sessions` and similar queries to return empty results or parse errors.

**Option 1**: Set `PYTHONUTF8=1` before running your script:

```powershell
$env:PYTHONUTF8 = "1"
python my_script.py
```

**Option 2**: Patch libtmux locally. In your installed libtmux package, edit `common.py` and add `encoding="utf-8"` to the `Popen` call in the `tmux_cmd.__init__` method:

```python
subprocess.Popen(
    cmd, stdout=PIPE, stderr=PIPE, text=True,
    encoding="utf-8", errors="backslashreplace"
)
```

This is an upstream libtmux issue (not psmux-specific). The library should specify encoding explicitly for cross-platform compatibility.

### libtmux API Coverage


The following libtmux operations are verified working with psmux:

| Operation | Status | Notes |
|-----------|--------|-------|
| `Server(socket_name="default")` | Works | Connects to the running psmux server |
| `server.sessions` | Works | Returns all sessions (needs encoding fix on Windows) |
| `session.id` (`$N`) | Works | Returns the stable session ID |
| `session.windows` | Works | Lists all windows in the session |
| `session.new_window()` | Works | Creates a new window |
| `window.id` (`@N`) | Works | Returns the stable window ID |
| `window.panes` | Works | Lists all panes in the window |
| `pane.id` (`%N`) | Works | Returns the stable pane ID |
| `pane.send_keys()` | Works | Sends keystrokes to the pane |
| `pane.capture_pane()` | Works | Captures visible pane content |
| `window.kill()` | Works | Destroys the window |
| `session.kill()` | Works | Destroys the session |
| `server.has_session()` | Works | Checks if a session exists |
| Custom format queries (`-F`) | Works | All 140+ format variables supported |

## Control Mode Integration


For persistent, event-driven integration (IDE plugins, session managers, monitoring tools), use control mode. See [control-mode.md](control-mode.md) for the full protocol reference.

### Quick Example


```python
import subprocess
import threading

proc = subprocess.Popen(
    ["psmux", "-CC"],
    stdin=subprocess.PIPE,
    stdout=subprocess.PIPE,
    stderr=subprocess.PIPE,
    text=True,
    encoding="utf-8",
)

def reader():
    for line in proc.stdout:
        line = line.rstrip("\n")
        if line.startswith("%output"):
            _, pane_id, *data = line.split(" ", 2)
            print(f"[{pane_id}] {data[0] if data else ''}")
        elif line.startswith("%window-add"):
            print(f"Window created: {line}")
        elif line.startswith("%session-changed"):
            print(f"Session changed: {line}")

t = threading.Thread(target=reader, daemon=True)
t.start()

# Send commands

proc.stdin.write("list-windows\n")
proc.stdin.flush()

proc.stdin.write("new-window -n monitor\n")
proc.stdin.flush()

proc.stdin.write('send-keys "Get-Process" Enter\n')
proc.stdin.flush()
```

### psmux Extension Commands


In addition to the 83 standard tmux commands, psmux provides extra commands useful for rich integrations:

| Command | Description |
|---------|-------------|
| `dump-state` | Full session state as JSON (windows, panes, options, screen content) |
| `dump-layout` | Pane layout tree structure |
| `list-tree` | Hierarchical session/window/pane tree |
| `send-text <text>` | Send raw text to active pane (no key name parsing) |
| `send-paste <text>` | Send text as a bracketed paste sequence |
| `claim-session` | Claim a warm (pre-spawned) session for instant startup |
| `set-pane-title <title>` | Set pane title directly |
| `toggle-sync` | Toggle synchronized input for all panes in a window |

## Named Paste Buffers


psmux supports named paste buffers for structured inter-pane data exchange:

```powershell
# Set a named buffer

psmux set-buffer -b config "key=value"

# Read it from another pane or script

psmux show-buffer -b config

# Delete when done

psmux delete-buffer -b config

# Paste into the active pane

psmux paste-buffer -b config
```

Named buffers are useful for passing structured data between automation steps without relying on environment variables or temporary files.

## Cross-Platform Project Structure


For projects that need to work on both Linux/macOS (tmux) and Windows (psmux), here is a recommended pattern:

### 1. Use the `tmux` Binary Name


psmux installs `tmux.exe` as an alias. Your code can call `tmux` on all platforms:

```python
binary = "tmux"  # Works on Linux (real tmux) and Windows (psmux alias)
```

### 2. Set Encoding on Windows


The only platform-specific code you need:

```python
import platform

def get_mux_kwargs():
    kwargs = {"capture_output": True, "text": True}
    if platform.system() == "Windows":
        kwargs["encoding"] = "utf-8"
    return kwargs
```

### 3. Handle Path Separators


tmux uses Unix paths (`/home/user/project`), psmux uses Windows paths (`C:\Users\user\project`). Format variables like `#{pane_current_path}` return the native path format. If your code compares paths, normalize them:

```python
from pathlib import Path

pane_path = Path(mux_cmd(["display-message", "-p", "#{pane_current_path}"]))
```

### 4. Shell Differences


On Linux, the default shell in tmux is usually `bash` or `zsh`. On Windows, psmux defaults to PowerShell 7 (`pwsh`). Keep this in mind when sending commands:

```python
import platform

if platform.system() == "Windows":
    mux_cmd(["send-keys", "-t", target, "Get-ChildItem", "Enter"])
else:
    mux_cmd(["send-keys", "-t", target, "ls -la", "Enter"])
```

### 5. Test Matrix


A typical CI/CD matrix for a cross-platform tmux integration:

```yaml
# GitHub Actions example

strategy:
  matrix:
    os: [ubuntu-latest, windows-latest]
    include:
      - os: ubuntu-latest
        mux: tmux
      - os: windows-latest
        mux: psmux

steps:
  - name: Install multiplexer
    run: |
      if [ "${{ matrix.mux }}" = "psmux" ]; then
        cargo install --git https://github.com/psmux/psmux
      else
        sudo apt-get install -y tmux
      fi
    shell: bash

  - name: Run integration tests
    run: python -m pytest tests/test_mux_integration.py
    env:
      PYTHONUTF8: "1"
```

## Environment Variables

psmux sets these environment variables in child processes, matching tmux:

| Variable | Example | Description |
|----------|---------|-------------|
| `TMUX` | `/tmp/tmux-1000/default,12345,0` | Indicates a tmux/psmux session is active |
| `TMUX_PANE` | `%0` | The pane ID of the current pane |
| `TERM` | `xterm-256color` | Terminal type |
| `COLORTERM` | `truecolor` | Indicates 24-bit color support |

Tools that check for `$TMUX` to detect tmux will correctly detect psmux as well.

### Propagating Environment Variables

Use `set-environment` to pass configuration to panes:

```powershell
# Global: all new panes inherit this
psmux set-environment -g API_KEY "sk-..."

# Session-scoped
psmux set-environment PROJECT_ROOT "C:\Projects\myapp"

# On session creation
psmux new-session -s work -e "NODE_ENV=development"
```

## Server Namespaces


Use `-L` to run isolated psmux instances (each with its own sessions, windows, and options):

```powershell
# Create isolated servers for different projects

psmux -L frontend new-session -d -s app
psmux -L backend new-session -d -s api

# Each namespace is completely independent

psmux -L frontend list-sessions   # Only shows "app"
psmux -L backend list-sessions    # Only shows "api"

# Attach to a specific namespace

psmux -L frontend attach -t app
```

In control mode, the session name includes the namespace:

```powershell
$env:PSMUX_SESSION_NAME = "frontend__app"
psmux -CC
```

The double underscore separates namespace from session name.

## Targeting Syntax Reference


psmux supports the full tmux target syntax for the `-t` flag:

| Target | Meaning |
|--------|---------|
| `mysession` | Session by name |
| `$0` | Session by stable ID |
| `mysession:2` | Window 2 in session "mysession" |
| `mysession:editor` | Window named "editor" in session "mysession" |
| `:2` | Window 2 in the current session |
| `@3` | Window by stable ID |
| `%5` | Pane by stable ID |
| `mysession:2.1` | Pane 1 of window 2 in session "mysession" |
| `.+1` | Next pane |
| `.-1` | Previous pane |

## Hooks for Event-Driven Automation


Hooks let you react to session events without polling:

```powershell
# Run a script when a new window is created

psmux set-hook -g after-new-window "run-shell 'echo window created >> /tmp/events.log'"

# Notify on session attach

psmux set-hook -g client-attached "display-message 'Welcome back!'"

# Auto-layout on split

psmux set-hook -g after-split-window "select-layout tiled"
```

Available hooks: `after-new-session`, `after-new-window`, `after-split-window`, `client-attached`, `client-detached`, `after-select-window`, `after-select-pane`, `after-resize-pane`, `pane-died`, `alert-activity`, `alert-silence`, `alert-bell`, `after-kill-pane`.

## Synchronization with `wait-for`


For multi-step automation that needs coordination between panes:

```powershell
# Pane 1: Wait for a signal

psmux send-keys -t %0 "psmux wait-for ready && echo 'proceeding'" Enter

# Pane 2: Do some work, then signal

psmux send-keys -t %1 "cargo build && psmux wait-for -S ready" Enter
```

`wait-for` supports `-L` (lock), `-S` (signal/unlock), and bare wait. Use it for producer/consumer patterns across panes.

## Troubleshooting


### "no server running" Error


psmux requires a running session. Create one first:

```powershell
psmux new-session -d -s work
```

Or use `has-session` to check:

```powershell
psmux has-session -t work 2>$null
if ($LASTEXITCODE -ne 0) {
    psmux new-session -d -s work
}
```

### Empty Results from Format Queries on Windows


If `list-sessions -F`, `list-windows -F`, or `list-panes -F` returns garbled or empty output, your process is decoding psmux's UTF-8 output with the wrong encoding. See the [encoding section](#windows-encoding-fix) above.

### Control Mode Connection Issues


If `psmux -CC` exits immediately, ensure a session exists and `PSMUX_SESSION_NAME` is set:

```powershell
psmux new-session -d -s work
$env:PSMUX_SESSION_NAME = "work"
psmux -CC
```

### ConPTY Differences from Unix PTY


When porting Unix tmux integrations to Windows:

- **Alternate screen buffer**: ConPTY processes SMCUP/RMCUP internally. The `alternate_on` flag is always false in psmux. Use content-based heuristics to detect fullscreen TUI apps.
- **Output normalization**: ConPTY may normalize line endings. `%output` data may differ slightly from Unix tmux output.
- **Ctrl+C**: `GenerateConsoleCtrlEvent` sends to all processes sharing the console. Prefer app-specific quit keys over `C-c` in automation.
- **TUI exit timing**: After a TUI exits, ConPTY needs 4 to 6 seconds to restore the screen. Add a delay before `capture-pane` after TUI exit.

## Related Documentation


- [compatibility.md]compatibility.md : Full tmux command and feature compatibility matrix
- [control-mode.md]control-mode.md : Control mode wire protocol reference
- [scripting.md]scripting.md : Command reference and scripting examples
- [configuration.md]configuration.md : All options and config file format
- [claude-code.md]claude-code.md : Claude Code agent team integration
- [features.md]features.md : Complete feature list