-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathopencode_mobile_bridge.py
More file actions
674 lines (549 loc) · 23.2 KB
/
opencode_mobile_bridge.py
File metadata and controls
674 lines (549 loc) · 23.2 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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
import argparse
import atexit
import json
import os
from pathlib import Path
import shutil
import socket
import subprocess
import sys
import threading
import time
import urllib.error
import urllib.request
import webbrowser
DEFAULT_UPSTREAM_HOST = "127.0.0.1"
DEFAULT_UPSTREAM_PORT = 4097
DEFAULT_PROXY_HOST = "0.0.0.0"
DEFAULT_PROXY_PORT = 4096
DEFAULT_OPENCODE_PACKAGE = "opencode-ai@latest"
DEFAULT_OPENCODE_SUBCOMMAND = "serve"
BRIDGE_PROXY_VERSION = "0.2.0"
def command_exists(command: str | None) -> bool:
if not command:
return False
if Path(command).exists():
return True
return shutil.which(command) is not None
def prepend_path(directory: Path) -> None:
if not directory.exists():
return
current = os.environ.get("PATH", "")
parts = current.split(os.pathsep) if current else []
directory_text = str(directory)
if any(part.lower() == directory_text.lower() for part in parts):
return
os.environ["PATH"] = directory_text + os.pathsep + current if current else directory_text
def refresh_node_path() -> None:
if os.name != "nt":
return
for env_name in ("ProgramFiles", "ProgramFiles(x86)"):
root = os.environ.get(env_name)
if root:
prepend_path(Path(root) / "nodejs")
appdata = os.environ.get("APPDATA")
if appdata:
prepend_path(Path(appdata) / "npm")
def known_windows_executable(*names: str) -> str | None:
if os.name != "nt":
return None
directories: list[Path] = []
for env_name in ("ProgramFiles", "ProgramFiles(x86)"):
root = os.environ.get(env_name)
if root:
directories.append(Path(root) / "nodejs")
appdata = os.environ.get("APPDATA")
if appdata:
directories.append(Path(appdata) / "npm")
for directory in directories:
for name in names:
candidate = directory / name
if candidate.exists():
return str(candidate)
return None
def find_npm_command() -> str | None:
refresh_node_path()
if os.name == "nt":
return shutil.which("npm.cmd") or shutil.which("npm") or known_windows_executable("npm.cmd", "npm.exe")
return shutil.which("npm")
def default_node_command() -> str | None:
configured = os.environ.get("NODE_CMD")
if configured:
return configured
refresh_node_path()
found = shutil.which("node")
if found:
return found
return known_windows_executable("node.exe")
def resolve_node_command(preferred: str | None) -> str | None:
refresh_node_path()
candidates = []
if preferred:
candidates.append(preferred)
detected = default_node_command()
if detected:
candidates.append(detected)
candidates.append("node")
for candidate in candidates:
if command_exists(candidate):
return candidate
return None
def install_nodejs() -> bool:
if os.name == "nt":
winget = shutil.which("winget")
if not winget:
print("Node.js was not found and winget is not available to install it automatically.", file=sys.stderr, flush=True)
print("Install Node.js LTS from https://nodejs.org/ and run this script again.", file=sys.stderr, flush=True)
return False
print("Node.js was not found. Installing Node.js LTS with winget...", flush=True)
result = subprocess.run(
[
winget,
"install",
"--id",
"OpenJS.NodeJS.LTS",
"-e",
"--accept-package-agreements",
"--accept-source-agreements",
]
)
refresh_node_path()
return result.returncode == 0 and resolve_node_command(None) is not None
if sys.platform == "darwin":
brew = shutil.which("brew")
if not brew:
print("Node.js was not found and Homebrew is not available to install it automatically.", file=sys.stderr, flush=True)
print("Install Node.js LTS from https://nodejs.org/ and run this script again.", file=sys.stderr, flush=True)
return False
print("Node.js was not found. Installing Node.js with Homebrew...", flush=True)
result = subprocess.run([brew, "install", "node"])
return result.returncode == 0 and resolve_node_command(None) is not None
print("Node.js was not found. Automatic Node.js install is currently supported on Windows and macOS only.", file=sys.stderr, flush=True)
print("Install Node.js LTS from https://nodejs.org/ and run this script again.", file=sys.stderr, flush=True)
return False
def ensure_node_command(preferred: str | None, auto_install: bool) -> str | None:
command = resolve_node_command(preferred)
if command:
return command
if not auto_install:
return None
if not install_nodejs():
return None
return resolve_node_command(preferred)
def default_opencode_command() -> str | None:
configured = os.environ.get("OPENCODE_CMD")
if configured:
return configured
if os.name == "nt":
appdata = os.environ.get("APPDATA", "")
candidate = Path(appdata) / "npm" / "opencode.cmd"
if candidate.exists():
return str(candidate)
found = shutil.which("opencode")
return found
def resolve_opencode_command(preferred: str | None) -> str | None:
candidates = []
if preferred:
candidates.append(preferred)
detected = default_opencode_command()
if detected:
candidates.append(detected)
candidates.append("opencode")
for candidate in candidates:
if command_exists(candidate):
return candidate
return None
def install_opencode_cli(package: str) -> bool:
npm = find_npm_command()
if not npm:
print("npm was not found. Install Node.js first, then run this script again.", file=sys.stderr, flush=True)
return False
print(f"OpenCode CLI was not found. Installing {package} with npm...", flush=True)
result = subprocess.run([npm, "install", "-g", package])
return result.returncode == 0
def ensure_opencode_command(preferred: str | None, package: str, auto_install: bool) -> str | None:
command = resolve_opencode_command(preferred)
if command:
return command
if not auto_install:
return None
if not install_opencode_cli(package):
return None
return resolve_opencode_command(preferred)
def default_desktop_global_path() -> str:
if os.name == "nt":
appdata = os.environ.get("APPDATA", "")
return str(Path(appdata) / "ai.opencode.desktop" / "opencode.global.dat")
home = Path.home()
macos = home / "Library" / "Application Support" / "ai.opencode.desktop" / "opencode.global.dat"
linux = home / ".config" / "ai.opencode.desktop" / "opencode.global.dat"
return str(macos if macos.exists() else linux)
def get_lan_ip() -> str:
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
sock.connect(("8.8.8.8", 80))
return sock.getsockname()[0]
except OSError:
try:
return socket.gethostbyname(socket.gethostname())
except OSError:
return "127.0.0.1"
finally:
sock.close()
def connect_host(host: str) -> str:
if host in ("", "0.0.0.0", "::"):
return "127.0.0.1"
return host
def can_connect(host: str, port: int) -> bool:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.settimeout(1)
try:
sock.connect((connect_host(host), port))
return True
except OSError:
return False
def wait_for_port(host: str, port: int, timeout: float) -> bool:
deadline = time.time() + timeout
while time.time() < deadline:
if can_connect(host, port):
return True
time.sleep(0.25)
return False
def request_json(url: str) -> dict | None:
try:
with urllib.request.urlopen(url, timeout=2) as response:
return json.loads(response.read().decode("utf-8"))
except (OSError, urllib.error.URLError, json.JSONDecodeError):
return None
def http_status(url: str) -> int | None:
try:
request = urllib.request.Request(url, method="GET")
with urllib.request.urlopen(request, timeout=2) as response:
return response.status
except urllib.error.HTTPError as error:
return error.code
except (OSError, urllib.error.URLError):
return None
def bridge_health(host: str, port: int) -> dict | None:
return request_json(f"http://{connect_host(host)}:{port}/__health")
def bridge_projects(host: str, port: int) -> dict | None:
return request_json(f"http://{connect_host(host)}:{port}/__projects")
def wait_for_bridge_projects(host: str, port: int, timeout: float) -> dict | None:
deadline = time.time() + timeout
last_result = None
while time.time() < deadline:
result = bridge_projects(host, port)
if result is not None:
last_result = result
if result.get("projects"):
return result
time.sleep(0.5)
return last_result
def summarize_projects(result: dict | None) -> str:
if not result:
return "Project discovery did not return diagnostics."
projects = result.get("projects") or []
diagnostics = result.get("diagnostics") or {}
return (
f"Discovered {len(projects)} projects "
f"(manual={diagnostics.get('manual', 0)}, "
f"desktop={diagnostics.get('desktop', 0)}, "
f"upstream={diagnostics.get('upstream', 0)})."
)
def stream_output(process: subprocess.Popen, label: str) -> None:
if not process.stdout:
return
for line in iter(process.stdout.readline, ""):
if line:
print(f"[{label}] {line.rstrip()}", flush=True)
if process.poll() is not None:
break
def terminate(processes: list[subprocess.Popen]) -> None:
for process in processes:
if process.poll() is None:
process.terminate()
deadline = time.time() + 5
for process in processes:
while process.poll() is None and time.time() < deadline:
time.sleep(0.1)
if process.poll() is None:
process.kill()
def stop_process_on_port(port: int) -> bool:
if os.name == "nt":
command = [
"powershell",
"-NoProfile",
"-NonInteractive",
"-Command",
(
"$ids = Get-NetTCPConnection -LocalPort "
+ str(port)
+ " -State Listen -ErrorAction SilentlyContinue | Select-Object -ExpandProperty OwningProcess -Unique; "
+ "if ($ids) { $ids | ForEach-Object { Stop-Process -Id $_ -Force -ErrorAction SilentlyContinue }; exit 0 } else { exit 1 }"
),
]
else:
shell_command = (
"ids=$(lsof -ti tcp:" + str(port) + " -sTCP:LISTEN 2>/dev/null); "
"if [ -n \"$ids\" ]; then kill $ids; exit 0; else exit 1; fi"
)
command = ["sh", "-c", shell_command]
try:
return subprocess.run(command, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode == 0
except OSError:
return False
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
description="Expose OpenCode Web UI on your LAN and seed Desktop projects for mobile browsers.",
)
parser.add_argument(
"--opencode",
default=default_opencode_command(),
help="Path to opencode executable. If missing, the script installs OpenCode with npm by default.",
)
parser.add_argument(
"--opencode-package",
default=DEFAULT_OPENCODE_PACKAGE,
help="npm package to install when OpenCode CLI is missing.",
)
parser.add_argument(
"--no-install-opencode",
action="store_true",
help="Fail instead of installing OpenCode CLI when it is missing.",
)
parser.add_argument(
"--opencode-subcommand",
choices=("serve", "web"),
default=DEFAULT_OPENCODE_SUBCOMMAND,
help="OpenCode command used to start the upstream server. 'serve' avoids opening an empty browser tab.",
)
parser.add_argument(
"--node",
default=default_node_command(),
help="Path to node executable. If missing, the script installs Node.js when possible.",
)
parser.add_argument(
"--no-install-node",
action="store_true",
help="Fail instead of installing Node.js when it is missing.",
)
parser.add_argument("--upstream-host", default=DEFAULT_UPSTREAM_HOST, help="Host for the private OpenCode server.")
parser.add_argument("--upstream-port", type=int, default=DEFAULT_UPSTREAM_PORT, help="Port for the private OpenCode server.")
parser.add_argument("--proxy-host", default=DEFAULT_PROXY_HOST, help="Host for the LAN proxy.")
parser.add_argument("--proxy-port", type=int, default=DEFAULT_PROXY_PORT, help="Port for the LAN proxy.")
parser.add_argument(
"--desktop-global",
default=default_desktop_global_path(),
help="Path to OpenCode Desktop opencode.global.dat for project import.",
)
parser.add_argument(
"--seed-project",
action="append",
default=[],
help="Extra project path to seed into the mobile/browser project list. Can be used multiple times.",
)
parser.add_argument(
"--keep-auth",
action="store_true",
help="Do not remove OPENCODE_SERVER_PASSWORD/USERNAME before starting OpenCode.",
)
parser.add_argument(
"--startup-timeout",
type=float,
default=20,
help="Seconds to wait for OpenCode before starting the proxy.",
)
parser.add_argument(
"--project-timeout",
type=float,
default=15,
help="Seconds to wait for project discovery before opening the browser.",
)
parser.add_argument(
"--no-open",
action="store_true",
help="Do not open a browser automatically after seeding is ready.",
)
parser.add_argument(
"--no-restart-outdated-proxy",
action="store_true",
help="Do not automatically stop an older OpenCode Mobile Bridge proxy on the same port.",
)
parser.add_argument(
"--open-target",
choices=("seed", "ui", "projects"),
default="seed",
help="Page to open automatically. 'seed' updates project localStorage before redirecting to the UI.",
)
return parser
def main() -> int:
args = build_parser().parse_args()
project_dir = Path(__file__).resolve().parent
proxy_script = project_dir / "bridge_proxy.js"
if not proxy_script.exists():
print(f"Proxy script not found: {proxy_script}", file=sys.stderr, flush=True)
return 1
env = os.environ.copy()
if not args.keep_auth:
env.pop("OPENCODE_SERVER_PASSWORD", None)
env.pop("OPENCODE_SERVER_USERNAME", None)
env["OPENCODE_UPSTREAM_HOST"] = args.upstream_host
env["OPENCODE_UPSTREAM_PORT"] = str(args.upstream_port)
env["OPENCODE_PROXY_HOST"] = args.proxy_host
env["OPENCODE_PROXY_PORT"] = str(args.proxy_port)
env["OPENCODE_DESKTOP_GLOBAL"] = args.desktop_global
env["OPENCODE_SEED_PROJECTS"] = ";".join(args.seed_project)
print("OpenCode Mobile Bridge", flush=True)
print(f"Desktop project state: {args.desktop_global}", flush=True)
processes: list[subprocess.Popen] = []
atexit.register(lambda: terminate(processes))
node_command = ensure_node_command(args.node, auto_install=not args.no_install_node)
if not node_command:
print("Node.js is not installed or could not be found.", file=sys.stderr, flush=True)
print("Install Node.js LTS from https://nodejs.org/ and run this script again.", file=sys.stderr, flush=True)
return 1
env["PATH"] = os.environ.get("PATH", env.get("PATH", ""))
print(f"Node.js command: {node_command}", flush=True)
upstream_url = f"http://{connect_host(args.upstream_host)}:{args.upstream_port}/"
upstream_running = can_connect(args.upstream_host, args.upstream_port)
if upstream_running:
print(f"Found an existing OpenCode server on {upstream_url}; reusing it.", flush=True)
status = http_status(upstream_url)
if status == 401:
print("Warning: the existing OpenCode server is asking for HTTP basic auth.", flush=True)
print("Stop that server and rerun this script if you want the bridge to launch a no-auth server.", flush=True)
elif not args.keep_auth:
print("Auth env vars only affect servers launched by this script; existing server auth is unchanged.", flush=True)
else:
opencode_command = ensure_opencode_command(
args.opencode,
args.opencode_package,
auto_install=not args.no_install_opencode,
)
if not opencode_command:
print("OpenCode CLI is not installed or could not be found.", file=sys.stderr, flush=True)
print("Install it with: npm install -g opencode-ai@latest", file=sys.stderr, flush=True)
return 1
print(f"OpenCode command: {opencode_command}", flush=True)
if not args.keep_auth:
print("HTTP basic auth env vars will be removed for the launched server.", flush=True)
server_command = [
opencode_command,
args.opencode_subcommand,
"--hostname",
args.upstream_host,
"--port",
str(args.upstream_port),
]
print(
f"Starting OpenCode {args.opencode_subcommand} on http://{args.upstream_host}:{args.upstream_port}/",
flush=True,
)
server_process = subprocess.Popen(
server_command,
env=env,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
bufsize=1,
)
processes.append(server_process)
threading.Thread(target=stream_output, args=(server_process, "opencode"), daemon=True).start()
if not wait_for_port(args.upstream_host, args.upstream_port, args.startup_timeout):
print("Warning: OpenCode did not accept connections before the startup timeout.", flush=True)
print("The proxy will still start; check OpenCode output for startup errors.", flush=True)
proxy = bridge_health(args.proxy_host, args.proxy_port)
if proxy and proxy.get("version") != BRIDGE_PROXY_VERSION:
message = (
"Found an older OpenCode Mobile Bridge proxy "
f"on http://{connect_host(args.proxy_host)}:{args.proxy_port}/ "
f"(version={proxy.get('version') or 'unknown'})."
)
if args.no_restart_outdated_proxy:
print(message, flush=True)
print("Reusing it because --no-restart-outdated-proxy was set.", flush=True)
else:
print(message, flush=True)
print("Restarting it so the fixed seed page is used.", flush=True)
if stop_process_on_port(args.proxy_port) and wait_for_port(args.proxy_host, args.proxy_port, 2):
print("Warning: old proxy is still accepting connections after restart attempt.", flush=True)
time.sleep(0.5)
proxy = bridge_health(args.proxy_host, args.proxy_port)
if proxy and proxy.get("version") != BRIDGE_PROXY_VERSION:
print("Could not replace the older proxy. Stop the old bridge process and run this script again.", file=sys.stderr, flush=True)
terminate(processes)
return 1
if proxy:
print(f"Found an existing OpenCode Mobile Bridge proxy on http://{connect_host(args.proxy_host)}:{args.proxy_port}/; reusing it.", flush=True)
elif can_connect(args.proxy_host, args.proxy_port):
print(f"Port {args.proxy_port} is already in use, but it does not look like OpenCode Mobile Bridge.", file=sys.stderr, flush=True)
print("Stop the process using that port or rerun with --proxy-port <free-port>.", file=sys.stderr, flush=True)
terminate(processes)
return 1
else:
print(f"Starting LAN proxy on http://{args.proxy_host}:{args.proxy_port}/", flush=True)
proxy_process = subprocess.Popen(
[node_command, str(proxy_script)],
env=env,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
bufsize=1,
)
processes.append(proxy_process)
threading.Thread(target=stream_output, args=(proxy_process, "proxy"), daemon=True).start()
if not wait_for_port(args.proxy_host, args.proxy_port, args.startup_timeout):
print("Warning: bridge proxy did not accept connections before the startup timeout.", flush=True)
lan_ip = get_lan_ip()
lan_ui_url = f"http://{lan_ip}:{args.proxy_port}/"
lan_seed_url = f"http://{lan_ip}:{args.proxy_port}/__seed"
lan_projects_url = f"http://{lan_ip}:{args.proxy_port}/__projects"
print("Checking project discovery before opening the browser...", flush=True)
project_result = wait_for_bridge_projects(args.proxy_host, args.proxy_port, args.project_timeout)
print(summarize_projects(project_result), flush=True)
projects = (project_result or {}).get("projects") or []
diagnostics = (project_result or {}).get("diagnostics") or {}
if diagnostics.get("desktopError"):
print(f"Desktop project import warning: {diagnostics['desktopError']}", flush=True)
if diagnostics.get("upstreamError"):
print(f"OpenCode project API warning: {diagnostics['upstreamError']}", flush=True)
open_targets = {
"seed": lan_seed_url,
"ui": lan_ui_url,
"projects": lan_projects_url,
}
open_url = open_targets[args.open_target]
if args.open_target == "seed" and not projects:
open_url = lan_projects_url
print("No projects were discovered; opening diagnostics instead of the seed page.", flush=True)
if not args.no_open:
print(f"Opening {open_url}", flush=True)
webbrowser.open(open_url)
print("", flush=True)
print("Bridge is running.", flush=True)
print(f"Local OpenCode: http://127.0.0.1:{args.upstream_port}/", flush=True)
print(f"LAN Web UI: {lan_ui_url}", flush=True)
print(f"Seed projects: {lan_seed_url}", flush=True)
print(f"Debug projects: {lan_projects_url}", flush=True)
print("", flush=True)
print("The seed page writes the latest project list into that browser, then redirects to OpenCode.", flush=True)
print("Open the seed URL once from each phone/browser after adding new Desktop projects.", flush=True)
if processes:
print("Press Ctrl+C to stop processes started by this script.", flush=True)
else:
print("Everything was already running; no new processes were started.", flush=True)
return 0
try:
while True:
for process in processes:
if process.poll() is not None:
print(f"A child process exited with code {process.returncode}; shutting down.", flush=True)
terminate(processes)
return int(process.returncode or 0)
time.sleep(0.5)
except KeyboardInterrupt:
print("\nStopping bridge...", flush=True)
terminate(processes)
return 0
if __name__ == "__main__":
raise SystemExit(main())