-
-
Notifications
You must be signed in to change notification settings - Fork 182
Expand file tree
/
Copy pathwrapper_unix.py
More file actions
176 lines (150 loc) · 5.81 KB
/
wrapper_unix.py
File metadata and controls
176 lines (150 loc) · 5.81 KB
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
"""Mac/Linux agent injection — uses tmux send-keys to type into the agent CLI.
Called by wrapper.py on Mac and Linux. Requires tmux to be installed.
- Mac: brew install tmux
- Linux: apt install tmux (or yum, pacman, etc.)
How it works:
1. Creates a tmux session running the agent CLI
2. Queue watcher sends keystrokes via 'tmux send-keys'
3. Wrapper attaches to the session so you see the full TUI
4. Ctrl+B, D to detach (agent keeps running in background)
"""
import shlex
import shutil
import subprocess
import sys
import time
def _session_exists(session_name: str) -> bool:
"""Return True while the tmux session is still alive."""
result = subprocess.run(
["tmux", "has-session", "-t", session_name],
capture_output=True,
)
return result.returncode == 0
def _check_tmux():
"""Verify tmux is installed, exit with helpful message if not."""
if shutil.which("tmux"):
return
print("\n Error: tmux is required for auto-trigger on Mac/Linux.")
if sys.platform == "darwin":
print(" Install: brew install tmux")
else:
print(" Install: apt install tmux (or yum/pacman equivalent)")
sys.exit(1)
def inject(text: str, *, tmux_session: str, delay: float = 0.3):
"""Send text + Enter to a tmux session via send-keys."""
# Use -l to send text literally (avoids misinterpreting as key names),
# then send Enter as a separate key press
subprocess.run(
["tmux", "send-keys", "-t", tmux_session, "-l", text],
capture_output=True,
)
# Scale delay with text length so longer prompts get more processing time
time.sleep(max(delay, len(text) * 0.001))
subprocess.run(
["tmux", "send-keys", "-t", tmux_session, "Enter"],
capture_output=True,
)
def get_activity_checker(session_name, trigger_flag=None):
"""Return a callable that detects tmux pane output by hashing content."""
last_hash = [None]
def check():
# External trigger: queue watcher injected a message
if trigger_flag is not None and trigger_flag[0]:
trigger_flag[0] = False
return True
try:
result = subprocess.run(
["tmux", "capture-pane", "-t", session_name, "-p"],
capture_output=True, timeout=2,
)
h = hash(result.stdout)
changed = last_hash[0] is not None and h != last_hash[0]
last_hash[0] = h
return changed
except Exception:
return False
return check
def run_agent(
command,
extra_args,
cwd,
env,
queue_file,
agent,
no_restart,
start_watcher,
strip_env=None,
pid_holder=None,
session_name=None,
inject_env=None,
inject_delay: float = 0.3,
):
"""Run agent inside a tmux session, inject via tmux send-keys."""
_check_tmux()
session_name = session_name or f"agentchattr-{agent}"
agent_cmd = " ".join(
[shlex.quote(command)] + [shlex.quote(a) for a in extra_args]
)
# Build env(1) prefix for the command INSIDE the tmux session.
# subprocess.run(env=...) only affects the tmux client binary — the
# session shell inherits from the tmux server instead. Use env(1)
# to set (-u to unset, VAR=val to inject) vars in the actual session.
env_parts = []
if strip_env:
env_parts.extend(f"-u {shlex.quote(v)}" for v in strip_env)
if inject_env:
env_parts.extend(
f"{shlex.quote(k)}={shlex.quote(v)}"
for k, v in inject_env.items()
)
if env_parts:
agent_cmd = f"env {' '.join(env_parts)} {agent_cmd}"
# Resolve cwd to absolute path (tmux -c needs it)
from pathlib import Path
abs_cwd = str(Path(cwd).resolve())
# Wire up injection with the tmux session name
inject_fn = lambda text: inject(text, tmux_session=session_name, delay=inject_delay)
start_watcher(inject_fn)
print(f" Using tmux session: {session_name}")
print(f" Detach: Ctrl+B, D (agent keeps running)")
print(f" Reattach: tmux attach -t {session_name}\n")
while True:
try:
# Clean up stale session from a previous crash
subprocess.run(
["tmux", "kill-session", "-t", session_name],
capture_output=True,
)
# Create tmux session running the agent CLI
result = subprocess.run(
["tmux", "new-session", "-d", "-s", session_name,
"-c", abs_cwd, agent_cmd],
env=env,
)
if result.returncode != 0:
print(f" Error: failed to create tmux session (exit {result.returncode})")
break
# Attach — blocks until agent exits or user detaches (Ctrl+B, D)
subprocess.run(["tmux", "attach-session", "-t", session_name])
# Check: did the agent exit, or did the user just detach?
if _session_exists(session_name):
# Session still alive — user detached, agent running in background.
# Keep the wrapper alive so the local proxy and heartbeats survive.
print(f"\n Detached. {agent.capitalize()} still running in tmux.")
print(f" Reattach: tmux attach -t {session_name}")
while _session_exists(session_name):
time.sleep(1)
break
# Session gone — agent exited
if no_restart:
break
print(f"\n {agent.capitalize()} exited.")
print(f" Restarting in 3s... (Ctrl+C to quit)")
time.sleep(3)
except KeyboardInterrupt:
# Kill the tmux session on Ctrl+C
subprocess.run(
["tmux", "kill-session", "-t", session_name],
capture_output=True,
)
break