-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathstart_sarah.py
More file actions
193 lines (161 loc) · 5.34 KB
/
Copy pathstart_sarah.py
File metadata and controls
193 lines (161 loc) · 5.34 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
#!/usr/bin/env python3
"""
Start Sarah with proper cleanup and single instance guarantee.
No watchdog - just clean, reliable startup.
"""
import os
import sys
import subprocess
import time
from pathlib import Path
SIBLINGS_DIR = Path(__file__).parent
SARAH_DIR = SIBLINGS_DIR / "sarah"
PID_DIR = SIBLINGS_DIR / ".pids"
PID_DIR.mkdir(exist_ok=True)
SARAH_PID_FILE = PID_DIR / "sarah.pid"
SARAH_LOCK = PID_DIR / "sarah.lock"
# Global lock handle
_lock_fd = None
def acquire_lock() -> bool:
"""Acquire lock to prevent multiple Sarahs."""
global _lock_fd
if sys.platform != "win32":
return True
import msvcrt
try:
if not SARAH_LOCK.exists():
SARAH_LOCK.write_text("init")
_lock_fd = open(SARAH_LOCK, 'r+')
msvcrt.locking(_lock_fd.fileno(), msvcrt.LK_NBLCK, 10)
_lock_fd.seek(0)
_lock_fd.write(f"{os.getpid()}\n{time.time()}")
_lock_fd.flush()
return True
except (IOError, OSError):
return False
def release_lock():
"""Release lock."""
global _lock_fd
if _lock_fd is None:
return
try:
if sys.platform == "win32":
import msvcrt
try:
msvcrt.locking(_lock_fd.fileno(), msvcrt.LK_UNLCK, 10)
except Exception:
pass
_lock_fd.close()
_lock_fd = None
except Exception:
pass
def is_process_running(pid: int) -> bool:
"""Check if process is running."""
try:
result = subprocess.run(
["tasklist", "/FI", f"PID eq {pid}"],
capture_output=True, text=True
)
return str(pid) in result.stdout
except Exception:
return False
def kill_sarah_processes():
"""Kill ALL Sarah processes - nuclear option."""
print("Cleaning up existing Sarah processes...")
# 1. Kill by PID file
if SARAH_PID_FILE.exists():
try:
pid = int(SARAH_PID_FILE.read_text().strip())
if is_process_running(pid):
print(f" Killing PID {pid} from file...")
subprocess.run(["taskkill", "/F", "/PID", str(pid)],
capture_output=True)
except Exception:
pass
SARAH_PID_FILE.unlink(missing_ok=True)
# 2. Kill by command line (find all sarah/bot.main)
try:
result = subprocess.run(
["wmic", "process", "where",
"commandline like '%sarah%' and commandline like '%bot.main%'",
"get", "processid"],
capture_output=True, text=True
)
for line in result.stdout.split('\n'):
line = line.strip()
if line.isdigit():
pid = int(line)
print(f" Killing orphan Sarah PID {pid}...")
subprocess.run(["taskkill", "/F", "/PID", str(pid)],
capture_output=True)
except Exception as e:
print(f" WMIC error: {e}")
# 3. Wait for processes to die
time.sleep(2)
def start_sarah():
"""Start Sarah bot."""
# Find venv Python
venv_python = SIBLINGS_DIR / ".venv" / "Scripts" / "python.exe"
if not venv_python.exists():
print(f"ERROR: venv not found at {venv_python}")
sys.exit(1)
print("Starting Sarah...")
process = subprocess.Popen(
[str(venv_python), "-m", "bot.main"],
cwd=str(SARAH_DIR),
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
creationflags=subprocess.CREATE_NEW_PROCESS_GROUP
)
# Save PID
SARAH_PID_FILE.write_text(str(process.pid))
print(f"Sarah started with PID {process.pid}")
# Verify it's running — poll up to 10 seconds (bot takes ~6s to init)
for i in range(5):
time.sleep(2)
if is_process_running(process.pid):
print(f"Sarah is running OK! (checked after {(i+1)*2}s)")
return True
print("WARNING: Sarah may have crashed on startup!")
return False
def main():
print("=" * 50)
print("Sarah Launcher (Single Instance)")
print("=" * 50)
# Acquire lock
if not acquire_lock():
print("\nERROR: Another Sarah launcher is running!")
print("Wait a moment or run: python stop_bots.py")
sys.exit(1)
try:
# Clean up existing processes
kill_sarah_processes()
# Verify clean state
result = subprocess.run(
["wmic", "process", "where",
"commandline like '%sarah%' and commandline like '%bot.main%'",
"get", "processid"],
capture_output=True, text=True
)
remaining = [l.strip() for l in result.stdout.split('\n') if l.strip().isdigit()]
if remaining:
print(f"\nWARNING: {len(remaining)} Sarah processes still running!")
print("Trying PowerShell kill...")
subprocess.run(
["powershell", "-Command",
"Get-Process python* | Where-Object {$_.Path -like '*sarah*'} | Stop-Process -Force"],
capture_output=True
)
time.sleep(2)
# Start fresh
success = start_sarah()
print("\n" + "=" * 50)
if success:
print("Done! Sarah is running.")
else:
print("Check logs at: siblings/sarah/logs/sarah.log")
print("=" * 50)
finally:
release_lock()
if __name__ == "__main__":
main()