-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathvm_client_network.py
More file actions
executable file
·232 lines (189 loc) · 7.36 KB
/
vm_client_network.py
File metadata and controls
executable file
·232 lines (189 loc) · 7.36 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
#!/usr/bin/env python3
"""
VM-to-Host Bridge Client - Network Version
Connects directly to Mac daemon over network (no tunnel needed)
"""
import socket
import json
import time
import uuid
import logging
import subprocess
logger = logging.getLogger(__name__)
def find_mac_host():
"""Find the Mac host IP (usually the gateway)"""
try:
# Get default gateway
result = subprocess.run(['ip', 'route', 'show', 'default'],
capture_output=True, text=True)
if result.returncode == 0:
# Parse: default via 10.211.55.1 dev enp0s5
parts = result.stdout.split()
if 'via' in parts:
gateway = parts[parts.index('via') + 1]
return gateway
except:
pass
# Fallback to common Parallels/VMware IPs
for ip in ['10.211.55.1', '192.168.1.1', '172.16.1.1']:
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(1)
result = sock.connect_ex((ip, 9999))
sock.close()
if result == 0:
return ip
except:
pass
return None
class VMBridgeClient:
"""Client for communicating with VM Bridge Daemon over network"""
def __init__(self, host=None, port=9999, timeout=5):
if host is None:
host = find_mac_host()
if host:
print(f"🔍 Auto-detected Mac host: {host}")
else:
host = '10.211.55.1' # Default Parallels
print(f"⚠️ Using default Mac IP: {host}")
self.host = host
self.port = port
self.timeout = timeout
def send_command(self, cmd, **kwargs):
"""Send command to Mac host"""
request_id = str(uuid.uuid4())
request = {
'id': request_id,
'cmd': cmd,
'timeout': kwargs.get('timeout', self.timeout)
}
# Add optional parameters
for key in ['stdin', 'args', 'path', 'content', 'prompt', 'context', 'task', 'name']:
if key in kwargs:
request[key] = kwargs[key]
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(self.timeout)
sock.connect((self.host, self.port))
request_json = json.dumps(request)
sock.send(request_json.encode('utf-8'))
response_data = b''
while True:
chunk = sock.recv(4096)
if not chunk:
break
response_data += chunk
try:
response = json.loads(response_data.decode('utf-8'))
break
except:
continue
sock.close()
return response
except socket.timeout:
logger.error(f"Timeout connecting to {self.host}:{self.port}")
return {'success': False, 'error': 'Connection timeout'}
except ConnectionRefusedError:
logger.error(f"Connection refused to {self.host}:{self.port}")
return {'success': False, 'error': 'Connection refused - is daemon running on Mac?'}
except Exception as e:
logger.error(f"Client error: {e}")
return {'success': False, 'error': str(e)}
# Clipboard operations
def copy_to_clipboard(self, content):
"""Copy to Mac clipboard"""
result = self.send_command('pbcopy', stdin=content)
return result.get('success', False)
def paste_from_clipboard(self):
"""Get Mac clipboard"""
result = self.send_command('pbpaste')
if result.get('success'):
return result.get('stdout', '')
return None
# File operations
def save_file_on_mac(self, content, path='~/Desktop/vm_file.txt'):
"""Save file on Mac"""
result = self.send_command('save_file', content=content, path=path)
return result.get('success', False)
def read_file_from_mac(self, path):
"""Read file from Mac"""
result = self.send_command('read_file', path=path)
if result.get('success'):
return result.get('content')
return None
# Agent operations
def run_agent_on_mac(self, prompt, context=None):
"""Run Claude agent on Mac with context"""
result = self.send_command('run_agent', prompt=prompt, context=context)
if result.get('success'):
return result.get('output')
return None
def send_task_to_mac(self, task, priority='normal'):
"""Queue task for Mac Claude"""
result = self.send_command('send_task', task=task, priority=priority)
return result.get('success', False)
# System operations
def notify(self, message):
"""Show notification on Mac"""
result = self.send_command('notify', args=[message])
return result.get('success', False)
def open_url(self, url):
"""Open URL on Mac"""
result = self.send_command('open_url', args=[url])
return result.get('success', False)
def create_snapshot(self, name=None):
"""Create VM snapshot"""
result = self.send_command('snapshot', name=name)
return result.get('success', False)
def is_daemon_running(self):
"""Check if daemon is accessible"""
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(1)
result = sock.connect_ex((self.host, self.port))
sock.close()
return result == 0
except:
return False
# Convenience functions
_default_client = None
def get_client():
"""Get or create default client"""
global _default_client
if _default_client is None:
_default_client = VMBridgeClient()
return _default_client
def copy_to_mac_clipboard(content):
"""Copy to Mac clipboard"""
return get_client().copy_to_clipboard(content)
def run_mac_agent(prompt, context=None):
"""Run Claude on Mac"""
return get_client().run_agent_on_mac(prompt, context)
def send_file_to_mac(content, path):
"""Save file on Mac"""
return get_client().save_file_on_mac(content, path)
if __name__ == '__main__':
import sys
print("VM Bridge Client (Network Version)")
print("=" * 40)
client = VMBridgeClient()
print(f"Connecting to Mac at {client.host}:{client.port}")
if not client.is_daemon_running():
print("❌ Cannot connect to daemon")
print("Make sure mac_daemon_network.py is running on your Mac")
sys.exit(1)
print("✅ Connected to Mac daemon!")
# Test clipboard
test_content = f"Network test at {time.strftime('%H:%M:%S')}"
print(f"\n1. Testing clipboard: '{test_content}'")
if client.copy_to_clipboard(test_content):
print(" ✅ Copied to Mac clipboard")
# Test notification
print("\n2. Testing notification")
if client.notify("Hello from VM via network!"):
print(" ✅ Notification sent")
# Test file save
print("\n3. Testing file save")
if client.save_file_on_mac("Test content from VM", "~/Desktop/vm_test.txt"):
print(" ✅ File saved on Mac Desktop")
print("\n✅ All tests completed!")