-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathopencode-serve
More file actions
executable file
·835 lines (689 loc) · 26.6 KB
/
opencode-serve
File metadata and controls
executable file
·835 lines (689 loc) · 26.6 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
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
#!/usr/bin/env python3
"""
opencode-serve — portable single-file OpenCode hosting.
Runs opencode on loopback and exposes it via Tailscale Serve (HTTPS, tailnet-only).
Credentials are stored in the OS keychain when available. Auto-starts on login
via launchd/systemd/Task Scheduler.
Usage:
opencode-serve install [--name NAME] [--reveal]
opencode-serve uninstall [--purge] [NAME]
opencode-serve start|stop|restart|status [NAME]
opencode-serve logs [--lines N] [NAME]
opencode-serve show-password [NAME]
"""
import argparse
import json
import os
import platform
import random
import secrets
import shutil
import socket
import subprocess
import sys
import time
from pathlib import Path
# ---------------------------------------------------------------------------
# Constants
# ---------------------------------------------------------------------------
PROG = "opencode-serve"
DEFAULT_NAME = "default"
KEYCHAIN_ACCOUNT = "opencode-serve"
SERVICE_PREFIX = "com.opencode.serve"
USERNAME = "opencode"
SECURE_OPENCODE_JSON = {
"$schema": "https://opencode.ai/config.json",
"permission": {
"*": "ask",
"read": "allow",
"grep": "allow",
"glob": "allow",
"list": "allow",
"external_directory": "ask",
},
}
# ---------------------------------------------------------------------------
# Paths
# ---------------------------------------------------------------------------
def _config_dir() -> Path:
return Path.home() / ".config" / PROG
def _state_dir(name: str) -> Path:
return Path.home() / ".local" / "state" / PROG / name
def _config_path(name: str) -> Path:
return _config_dir() / f"{name}.json"
def _log_path(name: str) -> Path:
return _state_dir(name) / "serve.log"
def _pid_path(name: str) -> Path:
return _state_dir(name) / "serve.pid"
def _service_path(name: str) -> Path:
system = platform.system()
if system == "Darwin":
return Path.home() / "Library" / "LaunchAgents" / f"{SERVICE_PREFIX}.{name}.plist"
if system == "Windows":
return _state_dir(name) / f"{PROG}-{name}.cmd"
return Path.home() / ".config" / "systemd" / "user" / f"{PROG}-{name}.service"
def _service_label(name: str) -> str:
return f"{SERVICE_PREFIX}.{name}"
def _service_name(name: str) -> str:
if platform.system() == "Windows":
return f"{PROG}-{name}"
if platform.system() == "Darwin":
return _service_label(name)
return f"{PROG}-{name}.service"
# ---------------------------------------------------------------------------
# Config
# ---------------------------------------------------------------------------
def _load_config(name: str) -> dict:
p = _config_path(name)
if not p.exists():
sys.exit(f"error: no instance '{name}'. Run: {PROG} install [--name {name}]")
return json.loads(p.read_text())
def _save_config(name: str, cfg: dict) -> None:
_config_dir().mkdir(parents=True, exist_ok=True)
p = _config_path(name)
p.write_text(json.dumps(cfg, indent=2) + "\n")
p.chmod(0o600)
# ---------------------------------------------------------------------------
# Keychain
# ---------------------------------------------------------------------------
def _keychain_service(name: str) -> str:
return f"{KEYCHAIN_ACCOUNT}:{name}"
def _keychain_store(name: str, password: str) -> None:
if platform.system() == "Darwin":
subprocess.run(
["security", "delete-generic-password",
"-a", KEYCHAIN_ACCOUNT, "-s", _keychain_service(name)],
capture_output=True,
)
r = subprocess.run(
["security", "add-generic-password",
"-a", KEYCHAIN_ACCOUNT, "-s", _keychain_service(name), "-w", password],
capture_output=True, text=True,
)
if r.returncode != 0:
sys.exit(f"error: failed to store password in keychain: {r.stderr.strip()}")
else:
st = shutil.which("secret-tool")
if st:
proc = subprocess.Popen(
[st, "store", "--label", _keychain_service(name),
"service", KEYCHAIN_ACCOUNT, "account", name],
stdin=subprocess.PIPE,
)
proc.communicate(input=password.encode())
if proc.returncode == 0:
return
# Fallback: mode-600 file
_state_dir(name).mkdir(parents=True, exist_ok=True)
pf = _state_dir(name) / ".pw"
pf.write_text(password)
pf.chmod(0o600)
def _keychain_get(name: str) -> str:
if platform.system() == "Darwin":
r = subprocess.run(
["security", "find-generic-password",
"-a", KEYCHAIN_ACCOUNT, "-s", _keychain_service(name), "-w"],
capture_output=True, text=True,
)
if r.returncode == 0:
return r.stdout.strip()
else:
st = shutil.which("secret-tool")
if st:
r = subprocess.run(
[st, "lookup", "service", KEYCHAIN_ACCOUNT, "account", name],
capture_output=True, text=True,
)
if r.returncode == 0 and r.stdout.strip():
return r.stdout.strip()
pf = _state_dir(name) / ".pw"
if pf.exists():
return pf.read_text().strip()
sys.exit(f"error: could not retrieve password. Run: {PROG} show-password {name}")
def _keychain_delete(name: str) -> None:
if platform.system() == "Darwin":
subprocess.run(
["security", "delete-generic-password",
"-a", KEYCHAIN_ACCOUNT, "-s", _keychain_service(name)],
capture_output=True,
)
else:
st = shutil.which("secret-tool")
if st:
subprocess.run(
[st, "clear", "service", KEYCHAIN_ACCOUNT, "account", name],
capture_output=True,
)
pf = _state_dir(name) / ".pw"
if pf.exists():
pf.unlink()
# ---------------------------------------------------------------------------
# Networking
# ---------------------------------------------------------------------------
def _free_loopback_port() -> int:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind(("127.0.0.1", 0))
return s.getsockname()[1]
def _active_tailscale_https_ports() -> set:
try:
r = subprocess.run(
["tailscale", "serve", "status", "--json"],
capture_output=True, text=True, timeout=10,
)
if r.returncode != 0 or not r.stdout.strip():
return set()
data = json.loads(r.stdout)
ports: set = set()
for raw in (data.get("TCP") or {}):
try:
ports.add(int(raw))
except ValueError:
pass
for hp in (data.get("Web") or {}):
_, _, p = hp.rpartition(":")
try:
ports.add(int(p))
except ValueError:
pass
return ports
except Exception:
return set()
def _free_tailscale_https_port() -> int:
used = _active_tailscale_https_ports()
for _ in range(200):
p = random.randint(20000, 49151)
if p not in used:
return p
sys.exit("error: could not find a free Tailscale HTTPS port")
# ---------------------------------------------------------------------------
# Tailscale
# ---------------------------------------------------------------------------
def _tailscale_dns_name() -> str:
r = subprocess.run(
["tailscale", "status", "--json"],
capture_output=True, text=True, timeout=15,
)
if r.returncode != 0:
sys.exit(f"error: tailscale status failed: {r.stderr.strip()}")
data = json.loads(r.stdout)
state = data.get("BackendState", "")
if state.lower() != "running":
sys.exit(f"error: Tailscale is not running (state: {state})")
self_node = data.get("Self") or {}
dns = self_node.get("DNSName", "").rstrip(".")
if not dns:
sys.exit(
"error: Tailscale DNS name not found.\n"
"Enable MagicDNS and HTTPS certificates in your tailnet admin console."
)
return dns
def _tailscale_serve_on(oc_port: int, https_port: int) -> None:
r = subprocess.run(
["tailscale", "serve", "--bg", f"--https={https_port}", "--yes",
f"http://127.0.0.1:{oc_port}"],
capture_output=True, text=True, timeout=30,
)
if r.returncode != 0:
sys.exit(f"error: tailscale serve failed:\n{r.stdout}\n{r.stderr}")
def _tailscale_serve_off(https_port: int) -> None:
subprocess.run(
["tailscale", "serve", f"--https={https_port}", "--yes", "off"],
capture_output=True, timeout=15,
)
# ---------------------------------------------------------------------------
# Service (launchd / systemd / Task Scheduler)
# ---------------------------------------------------------------------------
def _script_path() -> str:
return os.path.realpath(sys.argv[0])
def _task_command(name: str) -> str:
return subprocess.list2cmdline(
[
sys.executable or "python",
_script_path(),
"run",
"--name",
name,
"--log-file",
str(_log_path(name)),
]
)
def _run_or_exit(args: list, failure: str) -> subprocess.CompletedProcess:
r = subprocess.run(args, capture_output=True, text=True)
if r.returncode != 0:
detail = "\n".join(x for x in (r.stdout.strip(), r.stderr.strip()) if x)
sys.exit(f"error: {failure}" + (f":\n{detail}" if detail else ""))
return r
def _start_windows_task(name: str) -> None:
r = subprocess.run(
["schtasks", "/Run", "/TN", _service_name(name)],
capture_output=True, text=True,
)
detail = "\n".join(x for x in (r.stdout.strip(), r.stderr.strip()) if x)
if r.returncode != 0 and "already running" not in detail.lower():
sys.exit(f"error: failed to start scheduled task" + (f":\n{detail}" if detail else ""))
def _write_service(name: str) -> None:
lp = _log_path(name)
sp = _script_path()
path = _service_path(name)
path.parent.mkdir(parents=True, exist_ok=True)
system = platform.system()
if system == "Windows":
path.write_text(f"@echo off\r\n{_task_command(name)}\r\n")
path.chmod(0o700)
elif system == "Darwin":
path.write_text(
f'<?xml version="1.0" encoding="UTF-8"?>\n'
f'<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"'
f' "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n'
f"<plist version=\"1.0\">\n<dict>\n"
f" <key>Label</key>\n <string>{_service_label(name)}</string>\n"
f" <key>ProgramArguments</key>\n <array>\n"
f" <string>{sp}</string>\n"
f" <string>run</string>\n"
f" <string>--name</string>\n"
f" <string>{name}</string>\n"
f" </array>\n"
f" <key>RunAtLoad</key>\n <true/>\n"
f" <key>KeepAlive</key>\n <true/>\n"
f" <key>StandardOutPath</key>\n <string>{lp}</string>\n"
f" <key>StandardErrorPath</key>\n <string>{lp}</string>\n"
f"</dict>\n</plist>\n"
)
else:
path.write_text(
f"[Unit]\n"
f"Description=opencode-serve: {name}\n"
f"After=network.target\n\n"
f"[Service]\n"
f"ExecStart={sp} run --name {name}\n"
f"Restart=on-failure\n"
f"RestartSec=3\n"
f"StandardOutput=append:{lp}\n"
f"StandardError=append:{lp}\n\n"
f"[Install]\n"
f"WantedBy=default.target\n"
)
def _load_service(name: str) -> None:
if platform.system() == "Windows":
_run_or_exit(
[
"schtasks",
"/Create",
"/TN",
_service_name(name),
"/SC",
"ONLOGON",
"/TR",
_task_command(name),
"/F",
],
"failed to create scheduled task",
)
_start_windows_task(name)
elif platform.system() == "Darwin":
subprocess.run(
["launchctl", "load", "-w", str(_service_path(name))],
check=True,
)
else:
subprocess.run(["systemctl", "--user", "daemon-reload"], check=True)
subprocess.run(
["systemctl", "--user", "enable", "--now", f"{PROG}-{name}.service"],
check=True,
)
def _unload_service(name: str) -> None:
if platform.system() == "Windows":
was_running = _service_running(name)
if was_running:
_kill_windows_pid_tree(name)
subprocess.run(
["schtasks", "/End", "/TN", _service_name(name)],
capture_output=True,
)
subprocess.run(
["schtasks", "/Delete", "/TN", _service_name(name), "/F"],
capture_output=True,
)
elif platform.system() == "Darwin":
subprocess.run(
["launchctl", "unload", "-w", str(_service_path(name))],
capture_output=True,
)
else:
subprocess.run(
["systemctl", "--user", "disable", "--now", f"{PROG}-{name}.service"],
capture_output=True,
)
def _service_action(name: str, action: str) -> None:
if platform.system() == "Windows":
if action == "restart":
was_running = _service_running(name)
if was_running:
_kill_windows_pid_tree(name)
subprocess.run(
["schtasks", "/End", "/TN", _service_name(name)],
capture_output=True,
)
time.sleep(1)
_start_windows_task(name)
elif action == "stop":
was_running = _service_running(name)
if was_running:
_kill_windows_pid_tree(name)
subprocess.run(
["schtasks", "/End", "/TN", _service_name(name)],
capture_output=True,
)
elif action == "start":
_start_windows_task(name)
elif platform.system() == "Darwin":
label = _service_label(name)
if action == "restart":
subprocess.run(["launchctl", "stop", label], capture_output=True)
time.sleep(1)
subprocess.run(["launchctl", "start", label], check=True)
else:
subprocess.run(["launchctl", action, label], check=True)
else:
subprocess.run(
["systemctl", "--user", action, f"{PROG}-{name}.service"],
check=True,
)
def _service_running(name: str) -> bool:
if platform.system() == "Windows":
r = subprocess.run(
["schtasks", "/Query", "/TN", _service_name(name), "/FO", "LIST", "/V"],
capture_output=True, text=True,
)
if r.returncode != 0:
return False
for line in r.stdout.splitlines():
if line.lower().startswith("status:"):
return line.split(":", 1)[1].strip().lower() == "running"
return False
if platform.system() == "Darwin":
r = subprocess.run(
["launchctl", "list", _service_label(name)],
capture_output=True, text=True,
)
# launchctl list <label> output includes "PID" = <num>; when stopped there is no PID key
return r.returncode == 0 and '"PID"' in r.stdout
r = subprocess.run(
["systemctl", "--user", "is-active", f"{PROG}-{name}.service"],
capture_output=True, text=True,
)
return r.stdout.strip() == "active"
def _kill_windows_pid_tree(name: str) -> None:
if platform.system() != "Windows":
return
pp = _pid_path(name)
if not pp.exists():
return
pid = pp.read_text().strip()
if pid.isdigit():
subprocess.run(["taskkill", "/PID", pid, "/T", "/F"], capture_output=True)
pp.unlink(missing_ok=True)
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _find_opencode() -> str:
candidates = [Path.home() / ".opencode" / "bin" / "opencode"]
for c in candidates:
if c.is_file() and os.access(c, os.X_OK):
return str(c)
found = shutil.which("opencode")
if found:
return found
sys.exit(
"error: opencode binary not found.\n"
"Install from https://opencode.ai or ensure it is on your PATH."
)
def _seed_opencode_config() -> None:
p = Path.home() / ".opencode" / "opencode.json"
if p.exists():
print(f" opencode.json: existing {p} preserved")
return
p.parent.mkdir(parents=True, exist_ok=True)
p.write_text(json.dumps(SECURE_OPENCODE_JSON, indent=2) + "\n")
p.chmod(0o600)
print(f" opencode.json: created secure default at {p}")
def _health_ok(cfg: dict, password: str, timeout: float = 3.0) -> bool:
import base64
import urllib.request
url = f"http://127.0.0.1:{cfg['port']}/global/health"
creds = base64.b64encode(f"{cfg['username']}:{password}".encode()).decode()
try:
req = urllib.request.Request(url, headers={"Authorization": f"Basic {creds}"})
with urllib.request.urlopen(req, timeout=timeout) as resp:
return resp.status < 500
except Exception:
return False
# ---------------------------------------------------------------------------
# Commands
# ---------------------------------------------------------------------------
def _cmd_install(name: str, reveal: bool) -> None:
if _config_path(name).exists():
cfg = _load_config(name)
print(f"Installing existing '{name}'...")
print(" tailscale: ensuring serve...")
_tailscale_serve_on(cfg["port"], cfg["tailscale_https_port"])
_state_dir(name).mkdir(parents=True, exist_ok=True)
_write_service(name)
_load_service(name)
print(f" service: loaded {_service_name(name)}")
print()
print(f"Installed '{name}'.")
print(f" URL: {cfg['advertise_url']}")
print(f" Local: http://127.0.0.1:{cfg['port']}")
print(f" Username: {cfg['username']}")
if reveal:
print(f" Password: {_keychain_get(name)}")
else:
print(f" Password: (use '{PROG} show-password {name}' to reveal)")
return
print(f"Installing '{name}'...")
binary = _find_opencode()
print(f" binary: {binary}")
_seed_opencode_config()
password = secrets.token_urlsafe(32)
_keychain_store(name, password)
print(" keychain: password stored")
oc_port = _free_loopback_port()
https_port = _free_tailscale_https_port()
print(f" ports: opencode={oc_port} tailscale-https={https_port}")
print(" tailscale: configuring serve...")
_tailscale_serve_on(oc_port, https_port)
dns = _tailscale_dns_name()
url = f"https://{dns}:{https_port}"
print(f" tailscale: {url}")
cfg = {
"name": name,
"opencode_binary": binary,
"port": oc_port,
"username": USERNAME,
"tailscale_https_port": https_port,
"advertise_url": url,
}
_save_config(name, cfg)
_state_dir(name).mkdir(parents=True, exist_ok=True)
_write_service(name)
_load_service(name)
print(f" service: loaded {_service_name(name)}")
print()
print(f"Installed '{name}'.")
print(f" URL: {url}")
print(f" Local: http://127.0.0.1:{oc_port}")
print(f" Username: {USERNAME}")
if reveal:
print(f" Password: {password}")
else:
print(f" Password: (use '{PROG} show-password {name}' to reveal)")
def _cmd_uninstall(name: str, purge: bool) -> None:
cfg = _load_config(name)
print(f"Uninstalling '{name}'...")
_unload_service(name)
sp = _service_path(name)
if sp.exists():
sp.unlink()
print(" service: stopped and removed")
_tailscale_serve_off(cfg["tailscale_https_port"])
print(" tailscale: serve entry removed")
if purge:
_config_path(name).unlink(missing_ok=True)
shutil.rmtree(_state_dir(name), ignore_errors=True)
_keychain_delete(name)
print(" purged: config, state, and keychain entry removed")
else:
print(f" note: config preserved at {_config_path(name)}")
print(f" use --purge to also remove config, state, and keychain")
print(f"Uninstalled '{name}'.")
def _cmd_start(name: str) -> None:
_load_config(name)
_service_action(name, "start")
print(f"Started '{name}'.")
def _cmd_stop(name: str) -> None:
_load_config(name)
_service_action(name, "stop")
print(f"Stopped '{name}'.")
def _cmd_restart(name: str) -> None:
_load_config(name)
_service_action(name, "restart")
print(f"Restarted '{name}'.")
def _cmd_status(name: str) -> None:
cfg = _load_config(name)
password = _keychain_get(name)
running = _service_running(name)
healthy = _health_ok(cfg, password) if running else False
state = "running" if healthy else ("starting" if running else "stopped")
print(f"Name: {name}")
print(f"URL: {cfg['advertise_url']}")
print(f"Local: http://127.0.0.1:{cfg['port']}")
print(f"Status: {state}")
print(f"Service: {_service_name(name)}")
print(f"Log: {_log_path(name)}")
def _cmd_logs(name: str, lines: int) -> None:
_load_config(name)
lp = _log_path(name)
if not lp.exists():
print(f"No log file at {lp}")
return
if lines <= 0:
return
from collections import deque
with lp.open("r", encoding="utf-8", errors="replace") as fh:
sys.stdout.write("".join(deque(fh, maxlen=lines)))
def _cmd_show_password(name: str) -> None:
cfg = _load_config(name)
pw = _keychain_get(name)
print(f"URL: {cfg['advertise_url']}")
print(f"Local: http://127.0.0.1:{cfg['port']}")
print(f"Username: {cfg['username']}")
print(f"Password: {pw}")
def _cmd_run(name: str, log_file: str = "") -> None:
import signal as _signal
cfg = _load_config(name)
password = _keychain_get(name)
_state_dir(name).mkdir(parents=True, exist_ok=True)
_pid_path(name).write_text(str(os.getpid()) + "\n")
log_handle = None
if log_file:
lp = Path(log_file)
lp.parent.mkdir(parents=True, exist_ok=True)
log_handle = lp.open("a", encoding="utf-8", buffering=1)
sys.stdout = log_handle
sys.stderr = log_handle
env = dict(os.environ)
env["OPENCODE_SERVER_USERNAME"] = cfg["username"]
env["OPENCODE_SERVER_PASSWORD"] = password
cmd = [
cfg["opencode_binary"], "serve",
"--hostname", "127.0.0.1",
"--port", str(cfg["port"]),
"--print-logs",
]
cwd = str(Path.home())
shell = (
platform.system() == "Windows"
and cfg["opencode_binary"].lower().endswith((".bat", ".cmd"))
)
popen_cmd = subprocess.list2cmdline(cmd) if shell else cmd
proc_holder: list = [None]
def _stop(sig, frame): # noqa: ARG001
p = proc_holder[0]
if p and p.poll() is None:
p.terminate()
try:
p.wait(timeout=5)
except subprocess.TimeoutExpired:
p.kill()
_pid_path(name).unlink(missing_ok=True)
if log_handle:
log_handle.close()
sys.exit(0)
_signal.signal(_signal.SIGTERM, _stop)
_signal.signal(_signal.SIGINT, _stop)
def _log(msg: str) -> None:
print(f"{time.strftime('%Y-%m-%dT%H:%M:%S')} {PROG}[{name}]: {msg}", flush=True)
backoff = 3
_log(f"starting (binary={cfg['opencode_binary']} port={cfg['port']})")
while True:
try:
proc = subprocess.Popen(
popen_cmd,
cwd=cwd,
env=env,
shell=shell,
stdout=log_handle or None,
stderr=subprocess.STDOUT if log_handle else None,
)
proc_holder[0] = proc
code = proc.wait()
_log(f"opencode exited (code={code}); restarting in {backoff}s")
except Exception as exc:
_log(f"failed to start opencode: {exc}; retrying in {backoff}s")
time.sleep(backoff)
backoff = min(backoff * 2, 60)
# ---------------------------------------------------------------------------
# CLI
# ---------------------------------------------------------------------------
def main() -> None:
ap = argparse.ArgumentParser(
prog=PROG,
description="Portable single-file OpenCode hosting via Tailscale.",
formatter_class=argparse.RawDescriptionHelpFormatter,
)
sub = ap.add_subparsers(dest="cmd", metavar="COMMAND", required=True)
p = sub.add_parser("install", help="install and start a new instance")
p.add_argument("--name", default=DEFAULT_NAME, metavar="NAME")
p.add_argument("--reveal", action="store_true", help="print the generated password")
p = sub.add_parser("uninstall", help="stop and remove an instance")
p.add_argument("name", nargs="?", default=DEFAULT_NAME, metavar="NAME")
p.add_argument("--purge", action="store_true",
help="also remove config, state, and keychain entry")
_help = {"start": "start the service", "stop": "stop the service",
"restart": "restart the service", "status": "show instance status"}
for c in ("start", "stop", "restart", "status"):
p = sub.add_parser(c, help=_help[c])
p.add_argument("name", nargs="?", default=DEFAULT_NAME, metavar="NAME")
p = sub.add_parser("logs", help="tail the instance log")
p.add_argument("name", nargs="?", default=DEFAULT_NAME, metavar="NAME")
p.add_argument("--lines", "-n", type=int, default=100, metavar="N")
p = sub.add_parser("show-password", help="print URL, username, and password")
p.add_argument("name", nargs="?", default=DEFAULT_NAME, metavar="NAME")
p = sub.add_parser("run", help=argparse.SUPPRESS)
p.add_argument("--name", default=DEFAULT_NAME, metavar="NAME")
p.add_argument("--log-file", default="", metavar="PATH")
args = ap.parse_args()
{
"install": lambda: _cmd_install(args.name, args.reveal),
"uninstall": lambda: _cmd_uninstall(args.name, args.purge),
"start": lambda: _cmd_start(args.name),
"stop": lambda: _cmd_stop(args.name),
"restart": lambda: _cmd_restart(args.name),
"status": lambda: _cmd_status(args.name),
"logs": lambda: _cmd_logs(args.name, args.lines),
"show-password": lambda: _cmd_show_password(args.name),
"run": lambda: _cmd_run(args.name, args.log_file),
}[args.cmd]()
if __name__ == "__main__":
main()