compose_bridge.py 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. """Private Compose desktop transport. No network port or Docker socket."""
  2. import base64
  3. import http.server
  4. import json
  5. import os
  6. from pathlib import Path
  7. import secrets
  8. import signal
  9. import socketserver
  10. import subprocess
  11. import threading
  12. import time
  13. from skill_bundle import install as install_skill
  14. DESKTOP_ID = os.environ.get('YAOYAO_COMPOSE_DESKTOP_ID')
  15. if not DESKTOP_ID:
  16. raise SystemExit(0)
  17. ROOT = Path('/run/yaoyao-private')
  18. ROOT.mkdir(exist_ok=True)
  19. ROOT.chmod(0o700)
  20. BRIDGE = ROOT / 'bridge'
  21. BRIDGE.mkdir(exist_ok=True)
  22. BRIDGE.chmod(0o755)
  23. SOCKET = BRIDGE / 'desktop.sock'
  24. INSTANCE = secrets.token_hex(24)
  25. PID1 = Path('/proc/1/stat').read_text().split()[21]
  26. RESET = BRIDGE / 'reset.json'
  27. if RESET.exists() and json.loads(RESET.read_text()).get('pid1') == PID1:
  28. raise SystemExit(1) # A new bridge process alone cannot fence old programs.
  29. RESET.unlink(missing_ok=True)
  30. SOCKET.unlink(missing_ok=True)
  31. LOCK = threading.RLock()
  32. LEASE = None
  33. RESTARTING = False
  34. DRIVER = '/usr/local/libexec/openmausbot/cua-driver'
  35. CUA_SOCKET = '/run/user/1000/openmausbot-cua.sock'
  36. ENV = {'PATH': '/opt/venv/bin:/usr/local/bin:/usr/bin:/bin', 'HOME': '/home/cua', 'USER': 'cua', 'DISPLAY': ':1'}
  37. def reset_desktop():
  38. global RESTARTING, LEASE
  39. with LOCK:
  40. if RESTARTING:
  41. return
  42. RESTARTING = True
  43. LEASE = None
  44. RESET.write_text(json.dumps({'pid1': PID1}))
  45. # Compose restarts the same service and retains its workspace volume.
  46. threading.Timer(0.1, lambda: os.kill(1, signal.SIGTERM)).start()
  47. def current(body):
  48. if RESTARTING or not LEASE or body.get('token') != LEASE['token'] or body.get('instance') != INSTANCE or LEASE['expires'] <= time.monotonic():
  49. raise ValueError('桌面控制授权已失效')
  50. return LEASE
  51. def start(argv, cwd):
  52. # Change directory after dropping privileges: the persistent workspace is
  53. # owned by cua and the bridge does not need DAC_OVERRIDE.
  54. wrapper = 'import os,sys;os.chdir(sys.argv[1]);os.execvpe(sys.argv[2],sys.argv[2:],os.environ)'
  55. return subprocess.Popen(['python3','-c',wrapper,cwd,*argv], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=ENV, user=1000, group=1000, extra_groups=[], start_new_session=True)
  56. def run(argv, cwd='/home/cua/workspace', data=None, timeout=30):
  57. process = start(argv, cwd)
  58. try:
  59. stdout, stderr = process.communicate(data, timeout=timeout)
  60. except subprocess.TimeoutExpired:
  61. os.killpg(process.pid, signal.SIGKILL)
  62. process.communicate()
  63. raise ValueError('桌面画面服务尚未就绪')
  64. if len(stdout) + len(stderr) > 8 * 1024 * 1024:
  65. raise ValueError('桌面命令输出超过限制')
  66. return {'stdout': stdout.decode('utf-8', 'replace'), 'stderr': stderr.decode('utf-8', 'replace'), 'exitCode': process.returncode}
  67. class Handler(http.server.BaseHTTPRequestHandler):
  68. def log_message(self, *args):
  69. pass
  70. def do_POST(self):
  71. global LEASE
  72. try:
  73. length = int(self.headers.get('Content-Length', '0'))
  74. if length > 36 * 1024 * 1024:
  75. raise ValueError('请求过大')
  76. body = json.loads(self.rfile.read(length) or b'{}')
  77. if body.get('desktopId') != DESKTOP_ID:
  78. raise ValueError('桌面身份不匹配')
  79. op = self.path
  80. if op == '/health':
  81. ready = False
  82. if not RESTARTING:
  83. try:
  84. result = run([DRIVER, 'call', 'health_report', '{}', '--socket', CUA_SOCKET], timeout=5)
  85. ready = result['exitCode'] == 0
  86. except Exception:
  87. pass
  88. result = {'id': DESKTOP_ID, 'protocol': 1, 'instance': INSTANCE, 'ready': ready, 'features': ['skills-v1']}
  89. elif op == '/acquire':
  90. with LOCK:
  91. if RESTARTING:
  92. raise ValueError('桌面正在重置')
  93. if LEASE:
  94. if body.get('requestId') != LEASE['requestId'] or body.get('owner') != LEASE['owner']:
  95. raise ValueError('共享桌面正在使用')
  96. current({'token': LEASE['token'], 'instance': INSTANCE})
  97. else:
  98. if not isinstance(body.get('requestId'), str) or not isinstance(body.get('owner'), str):
  99. raise ValueError('缺少桌面授权身份')
  100. LEASE = {'requestId': body['requestId'], 'owner': body['owner'], 'token': secrets.token_hex(32), 'expires': time.monotonic() + 90, 'active': 0}
  101. result = {'token': LEASE['token'], 'instance': INSTANCE}
  102. elif op == '/renew':
  103. with LOCK:
  104. current(body)['expires'] = time.monotonic() + 90
  105. result = {'ok': True}
  106. elif op == '/release':
  107. with LOCK:
  108. current(body)
  109. if LEASE['active'] and not body.get('cancel'):
  110. raise ValueError('共享桌面仍有未结束操作')
  111. LEASE = None
  112. result = {'ok': True}
  113. if body.get('cancel'):
  114. reset_desktop()
  115. elif op == '/frame':
  116. path = '/tmp/yaoyao-compose-' + secrets.token_hex(12) + '.png'
  117. try:
  118. frame = run([DRIVER, 'call', 'get_desktop_state', '{}', '--socket', CUA_SOCKET, '--screenshot-out-file', path], timeout=10)
  119. if frame['exitCode'] != 0:
  120. raise ValueError('桌面画面尚未就绪')
  121. data = Path(path).read_bytes()
  122. if data[1:4] != b'PNG':
  123. raise ValueError('桌面画面无效')
  124. result = {'data': base64.b64encode(data).decode(), 'width': int.from_bytes(data[16:20], 'big'), 'height': int.from_bytes(data[20:24], 'big'), 'capturedAt': int(time.time()*1000)}
  125. finally:
  126. Path(path).unlink(missing_ok=True)
  127. elif op == '/skills-install':
  128. with LOCK:
  129. current(body)
  130. result = install_skill(body.get('bundle', {}))
  131. current(body)
  132. elif op == '/execute':
  133. argv = body.get('argv')
  134. if not isinstance(argv, list) or not argv or len(argv) > 64 or any(not isinstance(x, str) or '\0' in x for x in argv) or sum(map(len, argv)) > 65536:
  135. raise ValueError('桌面命令无效')
  136. cwd = body.get('cwd', '/home/cua/workspace')
  137. if not isinstance(cwd, str) or (cwd != '/home/cua/workspace' and not cwd.startswith('/home/cua/workspace/')) or '..' in Path(cwd).parts:
  138. raise ValueError('Compose 桌面工作目录必须位于 /home/cua/workspace')
  139. with LOCK:
  140. lease = current(body)
  141. # Spawn while holding the lease lock, then release the lock
  142. # before waiting so revocation can stop the container.
  143. process = start(argv, cwd)
  144. lease['active'] += 1
  145. try:
  146. data = base64.b64decode(body['input']) if body.get('input') else None
  147. stdout, stderr = process.communicate(data, timeout=min(60, max(1, body.get('timeout', 30000)/1000)))
  148. if len(stdout) + len(stderr) > 8*1024*1024:
  149. raise ValueError('桌面命令输出超过限制')
  150. with LOCK:
  151. current(body)
  152. result = {'stdout': stdout.decode('utf-8','replace'), 'stderr': stderr.decode('utf-8','replace'), 'exitCode': process.returncode}
  153. except Exception:
  154. reset_desktop()
  155. raise
  156. finally:
  157. with LOCK:
  158. if LEASE is lease:
  159. lease['active'] -= 1
  160. else:
  161. raise ValueError('桌面数量和创建删除由 Compose 管理')
  162. payload = json.dumps(result).encode()
  163. self.send_response(200)
  164. except Exception as exc:
  165. code = 'computer_busy' if str(exc) in ('共享桌面正在使用','共享桌面仍有未结束操作') else 'compose_desktop_error'
  166. payload = json.dumps({'error': str(exc), 'code': code}, ensure_ascii=False).encode()
  167. self.send_response(409)
  168. self.send_header('Content-Type','application/json')
  169. self.send_header('X-Yaoyao-Desktop-Id',DESKTOP_ID)
  170. self.send_header('Content-Length',str(len(payload)))
  171. self.end_headers()
  172. try:
  173. self.wfile.write(payload)
  174. except BrokenPipeError:
  175. pass
  176. class Server(socketserver.ThreadingMixIn, socketserver.UnixStreamServer):
  177. daemon_threads = True
  178. def expire():
  179. while True:
  180. time.sleep(5)
  181. with LOCK:
  182. expired = LEASE and LEASE['expires'] <= time.monotonic()
  183. if expired:
  184. reset_desktop()
  185. server = Server(str(SOCKET), Handler)
  186. SOCKET.chmod(0o600)
  187. os.chown(SOCKET,1000,1000)
  188. threading.Thread(target=expire,daemon=True).start()
  189. server.serve_forever()