-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmac_daemon_network.py
More file actions
408 lines (349 loc) · 13.4 KB
/
mac_daemon_network.py
File metadata and controls
408 lines (349 loc) · 13.4 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
#!/usr/bin/env python3
"""
VM-to-Host Command Bridge Daemon - Network Version
Binds to network interface for direct VM access
Supports bidirectional agent communication
"""
import socket
import json
import subprocess
import threading
import logging
import sys
import os
from datetime import datetime
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler(os.path.expanduser('~/Library/Logs/vm-bridge.log')),
logging.StreamHandler()
]
)
# Command whitelist with bidirectional support
COMMANDS = {
# Clipboard operations
'pbcopy': {
'binary': '/usr/bin/pbcopy',
'allow_stdin': True,
'max_stdin_size': 50 * 1024 * 1024, # 50MB for large files
'description': 'Copy to Mac clipboard'
},
'pbpaste': {
'binary': '/usr/bin/pbpaste',
'allow_stdout': True,
'description': 'Paste from Mac clipboard'
},
# File operations
'save_file': {
'handler': 'save_file_handler',
'description': 'Save file from VM to Mac'
},
'read_file': {
'handler': 'read_file_handler',
'description': 'Read file from Mac to VM'
},
# Agent communication
'run_agent': {
'handler': 'run_agent_handler',
'description': 'Run Claude agent on Mac with context'
},
'send_task': {
'handler': 'send_task_handler',
'description': 'Send task to Mac Claude'
},
# System operations
'notify': {
'binary': '/usr/bin/osascript',
'allow_args': True,
'args_template': ['-e', 'display notification "{message}" with title "VM Agent"'],
'description': 'Show Mac notification'
},
'open_url': {
'binary': '/usr/bin/open',
'allow_args': True,
'args_validator': lambda args: len(args) == 1 and args[0].startswith(('http://', 'https://')),
'description': 'Open URL in Mac browser'
},
'snapshot': {
'handler': 'snapshot_handler',
'description': 'Create VM snapshot'
}
}
class CommandHandler:
"""Handle command execution with custom handlers"""
@staticmethod
def save_file_handler(request):
"""Save file from VM to Mac"""
try:
path = os.path.expanduser(request.get('path', '~/Desktop/vm_file.txt'))
content = request.get('content', '')
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, 'w') as f:
f.write(content)
return {
'success': True,
'message': f'File saved to {path}',
'path': path
}
except Exception as e:
return {'success': False, 'error': str(e)}
@staticmethod
def read_file_handler(request):
"""Read file from Mac"""
try:
path = os.path.expanduser(request.get('path'))
with open(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_agent_handler(request):
"""Run Claude agent on Mac with provided context"""
try:
prompt = request.get('prompt', '')
context = request.get('context', '')
# Create a command for Claude on Mac
claude_cmd = f"claude '{prompt}'"
# Save context to temp file if provided
if context:
context_file = '/tmp/vm_context.md'
with open(context_file, 'w') as f:
f.write(context)
claude_cmd = f"claude '@{context_file} {prompt}'"
# Run Claude
result = subprocess.run(
claude_cmd,
shell=True,
capture_output=True,
text=True,
timeout=30
)
return {
'success': result.returncode == 0,
'output': result.stdout,
'error': result.stderr
}
except Exception as e:
return {'success': False, 'error': str(e)}
@staticmethod
def send_task_handler(request):
"""Queue task for Mac Claude"""
try:
task = request.get('task', '')
priority = request.get('priority', 'normal')
# Save task to queue file
task_file = os.path.expanduser('~/Documents/vm_tasks.json')
tasks = []
if os.path.exists(task_file):
with open(task_file, 'r') as f:
tasks = json.load(f)
tasks.append({
'task': task,
'priority': priority,
'timestamp': datetime.now().isoformat(),
'from': 'VM'
})
with open(task_file, 'w') as f:
json.dump(tasks, f, indent=2)
# Notify
subprocess.run([
'osascript', '-e',
f'display notification "New task from VM" with title "Agent Bridge"'
])
return {
'success': True,
'message': 'Task queued',
'queue_length': len(tasks)
}
except Exception as e:
return {'success': False, 'error': str(e)}
@staticmethod
def snapshot_handler(request):
"""Create VM snapshot"""
try:
name = request.get('name', f"snapshot_{datetime.now().strftime('%Y%m%d_%H%M%S')}")
# Try Parallels first
result = subprocess.run(
['prlctl', 'snapshot', 'Ubuntu', '-n', name],
capture_output=True,
text=True
)
if result.returncode != 0:
# Try VirtualBox
result = subprocess.run(
['VBoxManage', 'snapshot', 'Ubuntu', 'take', name],
capture_output=True,
text=True
)
return {
'success': result.returncode == 0,
'message': f'Snapshot {name} created' if result.returncode == 0 else result.stderr
}
except Exception as e:
return {'success': False, 'error': str(e)}
@staticmethod
def execute(request):
"""Execute a whitelisted command"""
try:
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]
# Use custom handler if specified
if 'handler' in config:
handler_name = config['handler']
handler = getattr(CommandHandler, handler_name)
return handler(request)
# Otherwise use standard binary execution
stdin_data = request.get('stdin', '')
if stdin_data and config.get('allow_stdin'):
max_size = config.get('max_stdin_size', float('inf'))
if len(stdin_data) > max_size:
return {'success': False, 'error': f'Stdin too large'}
cmd = [config['binary']]
if config.get('allow_args'):
args = request.get('args', [])
if config.get('args_template'):
template = config['args_template'].copy()
for i, arg in enumerate(template):
if '{message}' in arg and args:
template[i] = arg.replace('{message}', args[0])
cmd.extend(template)
else:
cmd.extend(args)
process = subprocess.Popen(
cmd,
stdin=subprocess.PIPE if stdin_data else None,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True
)
stdout, stderr = process.communicate(
input=stdin_data if stdin_data else None,
timeout=request.get('timeout', 5)
)
return {
'success': process.returncode == 0,
'stdout': stdout if config.get('allow_stdout') else '',
'stderr': stderr,
'exit_code': process.returncode
}
except Exception as e:
logging.error(f"Command execution error: {e}")
return {'success': False, 'error': str(e)}
class ClientHandler(threading.Thread):
"""Handle 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
if len(data) > 50 * 1024 * 1024: # 50MB max
raise ValueError("Request too large")
try:
json.loads(data.decode('utf-8'))
break
except:
continue
request = json.loads(data.decode('utf-8'))
request_id = request.get('id', 'unknown')
logging.info(f"Request {request_id}: {request.get('cmd')} from {self.address}")
result = CommandHandler.execute(request)
result['id'] = request_id
response = json.dumps(result).encode('utf-8')
self.client.send(response)
logging.info(f"Request {request_id}: {'Success' if result.get('success') else 'Failed'}")
except Exception as e:
logging.error(f"Client 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 VMBridgeDaemon:
"""Main daemon class - network version"""
def __init__(self, host='0.0.0.0', port=9999):
"""Bind to all interfaces for VM access"""
self.host = host # 0.0.0.0 allows VM connection
self.port = port
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((self.host, self.port))
self.socket.listen(5)
self.running = True
# Get actual IP for display
import subprocess
ip_result = subprocess.run(['ipconfig', 'getifaddr', 'en0'],
capture_output=True, text=True)
mac_ip = ip_result.stdout.strip() or 'unknown'
logging.info(f"VM Bridge Daemon started on {self.host}:{self.port}")
print(f"🌉 VM Bridge Daemon (Network Version)")
print(f"=" * 50)
print(f"✅ Listening on all interfaces: {self.host}:{self.port}")
print(f"📍 Mac IP: {mac_ip}")
print(f"🔌 VM can connect to: {mac_ip}:{self.port}")
print(f"📝 Logs: ~/Library/Logs/vm-bridge.log")
print(f"")
print(f"Available commands:")
for cmd, config in COMMANDS.items():
print(f" • {cmd}: {config['description']}")
print(f"")
print(f"VM clients should connect to {mac_ip}:{self.port}")
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:
logging.warning(f"Rejected connection from {address}")
client.close()
except KeyboardInterrupt:
break
except Exception as e:
logging.error(f"Accept error: {e}")
except Exception as e:
logging.error(f"Daemon start error: {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()
logging.info("VM Bridge Daemon stopped")
print("\n👋 VM Bridge Daemon stopped")
def main():
print("=" * 50)
print("VM-to-Host Agent Bridge (Network Version)")
print("=" * 50)
daemon = VMBridgeDaemon()
try:
daemon.start()
except KeyboardInterrupt:
daemon.stop()
if __name__ == '__main__':
main()