-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinject.py
More file actions
432 lines (362 loc) · 15.1 KB
/
inject.py
File metadata and controls
432 lines (362 loc) · 15.1 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
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
#!/usr/bin/env python3
"""
Cross-Platform Terminal Injection
==================================
Provides inject/interrupt/detect capabilities across:
- Windows: Win32 AttachConsole + WriteConsoleInputW (via subprocess helper)
- Linux/macOS (tmux): tmux send-keys
- Linux/macOS (screen): screen -X stuff
This module is imported by collab.py to replace the Windows-only injection code.
Zero external dependencies — Python 3.12+ stdlib only.
Usage:
from inject import get_backend, list_sessions
backend = get_backend() # auto-detect best available backend
sessions = backend.list_sessions() # find collaboration sessions
backend.inject(target, "hello world")
backend.interrupt(target)
"""
import os
import shutil
import subprocess
import sys
import time
from abc import ABC, abstractmethod
# ── Constants ─────────────────────────────────────────────────
# Role names that the launcher creates bat/shell scripts for
_ALL_ROLES = ["lead"] + [f"dev{i}" for i in range(1, 20)]
# ══════════════════════════════════════════════════════════════
# Abstract Backend
# ══════════════════════════════════════════════════════════════
class InjectionBackend(ABC):
"""Base class for platform-specific terminal injection."""
name: str = "abstract"
@abstractmethod
def available(self) -> bool:
"""Return True if this backend can be used on the current system."""
@abstractmethod
def list_sessions(self) -> dict[str, str]:
"""Return {role_name: session_id} for detected collaboration sessions."""
@abstractmethod
def inject(self, target: str, text: str) -> bool:
"""Type text + Enter into the target's terminal. Returns True on success."""
@abstractmethod
def interrupt(self, target: str) -> bool:
"""Send Escape (x2) to the target's terminal. Returns True on success."""
def find_target(self, role_name: str) -> str | None:
"""Find the session/PID for a role. Returns session_id or None."""
sessions = self.list_sessions()
return sessions.get(role_name)
# ══════════════════════════════════════════════════════════════
# Windows Backend (Win32 API)
# ══════════════════════════════════════════════════════════════
# Injector script spawned as a subprocess so we don't disturb our own console.
_WIN32_INJECTOR = r'''
import ctypes, ctypes.wintypes, sys, time
KEY_EVENT = 0x0001
GENERIC_READ = 0x80000000
GENERIC_WRITE = 0x40000000
FILE_SHARE_READ = 0x00000001
FILE_SHARE_WRITE = 0x00000002
OPEN_EXISTING = 3
INVALID_HANDLE_VALUE = -1
kernel32 = ctypes.windll.kernel32
class KEY_EVENT_RECORD(ctypes.Structure):
_fields_ = [
("bKeyDown", ctypes.wintypes.BOOL),
("wRepeatCount", ctypes.wintypes.WORD),
("wVirtualKeyCode", ctypes.wintypes.WORD),
("wVirtualScanCode", ctypes.wintypes.WORD),
("uChar", ctypes.wintypes.WCHAR),
("dwControlKeyState", ctypes.wintypes.DWORD),
]
class INPUT_RECORD_Event(ctypes.Union):
_fields_ = [("KeyEvent", KEY_EVENT_RECORD)]
class INPUT_RECORD(ctypes.Structure):
_fields_ = [
("EventType", ctypes.wintypes.WORD),
("_padding", ctypes.wintypes.WORD),
("Event", INPUT_RECORD_Event),
]
def write_key(handle, char, vk=0):
written = ctypes.wintypes.DWORD()
for down in (True, False):
rec = INPUT_RECORD()
rec.EventType = KEY_EVENT
rec.Event.KeyEvent.bKeyDown = down
rec.Event.KeyEvent.wRepeatCount = 1
rec.Event.KeyEvent.wVirtualKeyCode = vk
rec.Event.KeyEvent.wVirtualScanCode = 0
rec.Event.KeyEvent.uChar = char
rec.Event.KeyEvent.dwControlKeyState = 0
ok = kernel32.WriteConsoleInputW(handle, ctypes.byref(rec), 1, ctypes.byref(written))
if not ok:
err = ctypes.get_last_error()
print(f"WriteConsoleInputW failed: error={err}", file=sys.stderr)
return False
return True
def open_conin():
handle = kernel32.CreateFileW(
"CONIN$",
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE,
None, OPEN_EXISTING, 0, None,
)
if handle == INVALID_HANDLE_VALUE:
err = ctypes.get_last_error()
print(f"CreateFileW(CONIN$) failed: error={err}", file=sys.stderr)
return None
return handle
def main():
target_pid = int(sys.argv[1])
action = sys.argv[2] # "text", "escape", or "enter"
payload = sys.argv[3] if len(sys.argv) > 3 else ""
kernel32.FreeConsole()
if not kernel32.AttachConsole(target_pid):
err = ctypes.get_last_error()
print(f"AttachConsole failed for PID {target_pid} (error {err})", file=sys.stderr)
sys.exit(1)
handle = open_conin()
if handle is None:
kernel32.FreeConsole()
sys.exit(1)
if action == "escape":
write_key(handle, '\x1b', 0x1B)
time.sleep(0.05)
write_key(handle, '\x1b', 0x1B)
elif action == "text":
for ch in payload:
if ch == '\n':
write_key(handle, '\r', 0x0D)
else:
write_key(handle, ch, 0)
time.sleep(0.003)
time.sleep(0.02)
write_key(handle, '\r', 0x0D)
elif action == "enter":
write_key(handle, '\r', 0x0D)
kernel32.CloseHandle(handle)
kernel32.FreeConsole()
print("OK")
if __name__ == "__main__":
main()
'''
class WindowsBackend(InjectionBackend):
"""Windows injection via AttachConsole + WriteConsoleInputW."""
name = "win32"
def available(self) -> bool:
return sys.platform == "win32"
def list_sessions(self) -> dict[str, str]:
"""Find cmd.exe PIDs for each role by matching _run_<role>.bat in command lines."""
ps_cmd = (
'Get-CimInstance Win32_Process -Filter "Name=\'cmd.exe\'" '
'| Select-Object ProcessId,CommandLine '
'| ForEach-Object { "$($_.ProcessId)|$($_.CommandLine)" }'
)
try:
result = subprocess.run(
["powershell", "-NoProfile", "-Command", ps_cmd],
capture_output=True, text=True, timeout=8,
)
except Exception:
return {}
role_pids = {}
for line in result.stdout.strip().splitlines():
line = line.strip()
if not line or "|" not in line:
continue
pid_str, _, cmdline = line.partition("|")
try:
pid = int(pid_str.strip())
except ValueError:
continue
for role in _ALL_ROLES:
if f"_run_{role}.bat" in cmdline:
role_pids[role] = str(pid)
break
return role_pids
def _run_injector(self, pid: int, action: str, payload: str = "") -> bool:
"""Spawn the injector helper to write to another console."""
try:
result = subprocess.run(
[sys.executable, "-c", _WIN32_INJECTOR,
str(pid), action, payload],
capture_output=True, text=True, timeout=10,
)
if result.returncode != 0:
stderr = result.stderr.strip()
if stderr:
print(f" [injector error] {stderr}")
return False
return "OK" in result.stdout
except Exception as e:
print(f" [injector error] {e}")
return False
def inject(self, target: str, text: str) -> bool:
session = self.find_target(target)
if not session:
return False
return self._run_injector(int(session), "text", text)
def interrupt(self, target: str) -> bool:
session = self.find_target(target)
if not session:
return False
return self._run_injector(int(session), "escape")
# ══════════════════════════════════════════════════════════════
# tmux Backend (Linux / macOS)
# ══════════════════════════════════════════════════════════════
class TmuxBackend(InjectionBackend):
"""tmux-based injection for Linux/macOS."""
name = "tmux"
# Session/window naming convention: collab_<role>
_PREFIX = "collab_"
def available(self) -> bool:
if sys.platform == "win32":
return False
return shutil.which("tmux") is not None
def list_sessions(self) -> dict[str, str]:
"""Find tmux windows/panes matching collab_<role> naming."""
try:
result = subprocess.run(
["tmux", "list-windows", "-a", "-F",
"#{session_name}:#{window_index} #{window_name}"],
capture_output=True, text=True, timeout=5,
)
except Exception:
return {}
if result.returncode != 0:
return {}
sessions = {}
for line in result.stdout.strip().splitlines():
parts = line.strip().split(None, 1)
if len(parts) < 2:
continue
target, window_name = parts
for role in _ALL_ROLES:
if window_name == f"{self._PREFIX}{role}" or window_name == role:
sessions[role] = target
break
return sessions
def inject(self, target: str, text: str) -> bool:
session = self.find_target(target)
if not session:
return False
try:
# send-keys types the text literally, then Enter
result = subprocess.run(
["tmux", "send-keys", "-t", session, text, "Enter"],
capture_output=True, text=True, timeout=5,
)
return result.returncode == 0
except Exception:
return False
def interrupt(self, target: str) -> bool:
session = self.find_target(target)
if not session:
return False
try:
# Send Escape twice
subprocess.run(
["tmux", "send-keys", "-t", session, "Escape"],
capture_output=True, text=True, timeout=5,
)
time.sleep(0.05)
result = subprocess.run(
["tmux", "send-keys", "-t", session, "Escape"],
capture_output=True, text=True, timeout=5,
)
return result.returncode == 0
except Exception:
return False
# ══════════════════════════════════════════════════════════════
# GNU Screen Backend (Linux / macOS)
# ══════════════════════════════════════════════════════════════
class ScreenBackend(InjectionBackend):
"""GNU Screen-based injection for Linux/macOS."""
name = "screen"
# Session naming convention: collab_<role>
_PREFIX = "collab_"
def available(self) -> bool:
if sys.platform == "win32":
return False
return shutil.which("screen") is not None
def list_sessions(self) -> dict[str, str]:
"""Find screen sessions matching collab_<role> naming."""
try:
result = subprocess.run(
["screen", "-ls"],
capture_output=True, text=True, timeout=5,
)
except Exception:
return {}
sessions = {}
for line in result.stdout.strip().splitlines():
line = line.strip()
for role in _ALL_ROLES:
session_name = f"{self._PREFIX}{role}"
if session_name in line:
# Extract the full session ID (e.g., "12345.collab_dev1")
parts = line.split("\t")
if parts:
sid = parts[0].strip()
sessions[role] = sid
break
return sessions
def inject(self, target: str, text: str) -> bool:
session = self.find_target(target)
if not session:
return False
try:
# screen -S <session> -X stuff "text\n"
result = subprocess.run(
["screen", "-S", session, "-X", "stuff", text + "\n"],
capture_output=True, text=True, timeout=5,
)
return result.returncode == 0
except Exception:
return False
def interrupt(self, target: str) -> bool:
session = self.find_target(target)
if not session:
return False
try:
# Send Escape twice via screen stuff
subprocess.run(
["screen", "-S", session, "-X", "stuff", "\x1b"],
capture_output=True, text=True, timeout=5,
)
time.sleep(0.05)
result = subprocess.run(
["screen", "-S", session, "-X", "stuff", "\x1b"],
capture_output=True, text=True, timeout=5,
)
return result.returncode == 0
except Exception:
return False
# ══════════════════════════════════════════════════════════════
# Backend Selection
# ══════════════════════════════════════════════════════════════
# Priority order: platform-native first, then multiplexers
_BACKENDS = [WindowsBackend, TmuxBackend, ScreenBackend]
def get_backend() -> InjectionBackend | None:
"""Auto-detect and return the best available injection backend.
Returns None if no backend is available."""
for cls in _BACKENDS:
backend = cls()
if backend.available():
return backend
return None
def get_all_backends() -> list[InjectionBackend]:
"""Return all available backends (for diagnostics)."""
return [cls() for cls in _BACKENDS if cls().available()]
def list_all_sessions() -> dict[str, dict]:
"""Find all sessions across all available backends.
Returns {role: {"backend": name, "session": id}}."""
result = {}
for cls in _BACKENDS:
backend = cls()
if not backend.available():
continue
for role, session in backend.list_sessions().items():
if role not in result: # first backend wins
result[role] = {"backend": backend.name, "session": session}
return result