-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathvm_daemon.py
More file actions
249 lines (215 loc) · 7.43 KB
/
vm_daemon.py
File metadata and controls
249 lines (215 loc) · 7.43 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
#!/usr/bin/env python3
"""
VM-side daemon to receive commands from Mac
Enables bidirectional Mac ↔ VM communication
"""
import socket
import json
import subprocess
import threading
import logging
import sys
import os
from datetime import datetime
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s'
)
# VM-side command handlers
COMMANDS = {
'run_command': {
'handler': 'run_command_handler',
'description': 'Execute shell command on VM'
},
'analyze_project': {
'handler': 'analyze_project_handler',
'description': 'Run PROJECT_INDEX analysis'
},
'read_file': {
'handler': 'read_file_handler',
'description': 'Read file from VM'
},
'run_claude': {
'handler': 'run_claude_handler',
'description': 'Run Claude CLI on VM'
}
}
class VMCommandHandler:
"""Handle commands sent from Mac"""
@staticmethod
def run_command_handler(request):
"""Execute shell command"""
try:
cmd = request.get('command', '')
result = subprocess.run(
cmd,
shell=True,
capture_output=True,
text=True,
timeout=30
)
return {
'success': result.returncode == 0,
'stdout': result.stdout,
'stderr': result.stderr,
'exit_code': result.returncode
}
except Exception as e:
return {'success': False, 'error': str(e)}
@staticmethod
def analyze_project_handler(request):
"""Run PROJECT_INDEX analysis"""
try:
project_path = request.get('path', os.getcwd())
# Generate index
result = subprocess.run(
f"cd {project_path} && /index",
shell=True,
capture_output=True,
text=True,
timeout=60
)
# Read the index
index_path = os.path.join(project_path, 'PROJECT_INDEX.json')
if os.path.exists(index_path):
with open(index_path, 'r') as f:
index = json.load(f)
return {
'success': True,
'message': 'Index generated',
'stats': index.get('stats', {}),
'files_count': len(index.get('files', {}))
}
return {'success': False, 'error': 'Index not created'}
except Exception as e:
return {'success': False, 'error': str(e)}
@staticmethod
def read_file_handler(request):
"""Read file from VM"""
try:
path = request.get('path')
with open(os.path.expanduser(path), 'r') as f:
content = f.read()
return {
'success': True,
'content': content,
'size': len(content)
}
except Exception as e:
return {'success': False, 'error': str(e)}
@staticmethod
def run_claude_handler(request):
"""Run Claude CLI on VM"""
try:
prompt = request.get('prompt', '')
# Run Claude
result = subprocess.run(
f"claude '{prompt}'",
shell=True,
capture_output=True,
text=True,
timeout=60
)
return {
'success': result.returncode == 0,
'output': result.stdout,
'error': result.stderr
}
except Exception as e:
return {'success': False, 'error': str(e)}
@staticmethod
def execute(request):
"""Execute command based on request"""
cmd_name = request.get('cmd')
if not cmd_name or cmd_name not in COMMANDS:
return {'success': False, 'error': f'Unknown command: {cmd_name}'}
config = COMMANDS[cmd_name]
handler_name = config['handler']
handler = getattr(VMCommandHandler, handler_name)
return handler(request)
class ClientHandler(threading.Thread):
"""Handle Mac client connections"""
def __init__(self, client_socket, address):
super().__init__()
self.client = client_socket
self.address = address
self.daemon = True
def run(self):
try:
data = b''
while True:
chunk = self.client.recv(4096)
if not chunk:
break
data += chunk
try:
json.loads(data.decode('utf-8'))
break
except:
continue
request = json.loads(data.decode('utf-8'))
logging.info(f"Request from {self.address}: {request.get('cmd')}")
result = VMCommandHandler.execute(request)
response = json.dumps(result).encode('utf-8')
self.client.send(response)
except Exception as e:
logging.error(f"Handler error: {e}")
error_response = json.dumps({'success': False, 'error': str(e)}).encode('utf-8')
try:
self.client.send(error_response)
except:
pass
finally:
self.client.close()
class VMDaemon:
"""VM-side daemon for receiving commands from Mac"""
def __init__(self, port=9998):
self.port = port # Different port to avoid conflict
self.socket = None
self.running = False
def start(self):
try:
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.socket.bind(('0.0.0.0', self.port))
self.socket.listen(5)
self.running = True
print(f"🤖 VM Daemon Started")
print(f"=" * 50)
print(f"Listening on port {self.port}")
print(f"Mac can send commands to: 10.211.55.4:{self.port}")
print(f"")
print(f"Available commands:")
for cmd, config in COMMANDS.items():
print(f" • {cmd}: {config['description']}")
while self.running:
try:
client, address = self.socket.accept()
# Only accept from local network
if address[0].startswith(('127.', '10.', '192.168.', '172.')):
handler = ClientHandler(client, address)
handler.start()
else:
client.close()
except KeyboardInterrupt:
break
except Exception as e:
logging.error(f"Accept error: {e}")
except Exception as e:
print(f"❌ Failed to start daemon: {e}")
sys.exit(1)
finally:
self.stop()
def stop(self):
self.running = False
if self.socket:
self.socket.close()
print("\n👋 VM Daemon stopped")
def main():
daemon = VMDaemon()
try:
daemon.start()
except KeyboardInterrupt:
daemon.stop()
if __name__ == '__main__':
main()