-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.py
More file actions
4370 lines (3844 loc) · 181 KB
/
Copy pathcli.py
File metadata and controls
4370 lines (3844 loc) · 181 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
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from __future__ import annotations
import argparse
import os
import sys
import tarfile
import tempfile
import base64
import hmac
import hashlib
import json
import subprocess
import shutil
import socket
import re
import secrets
import time
import urllib.request
import urllib.error
import pwd
from pathlib import Path
try:
import tomllib
except Exception:
tomllib = None
# ===== Platform =====
IS_MACOS = sys.platform == 'darwin'
# ===== ANSI Colors =====
_IS_TTY = sys.stderr.isatty() if hasattr(sys, 'stderr') else False
_NO_COLOR = os.environ.get('NO_COLOR', '').strip() or os.environ.get('GPTADMIN_NO_COLOR', '').strip()
def _c(code: str, text: str) -> str:
"""Wrap text in ANSI color if TTY and not disabled."""
if not _IS_TTY or _NO_COLOR:
return text
return f'\033[{code}m{text}\033[0m'
def c_green(t): return _c('32', t)
def c_red(t): return _c('31', t)
def c_yellow(t): return _c('33', t)
def c_cyan(t): return _c('36', t)
def c_dim(t): return _c('2', t)
def c_bold(t): return _c('1', t)
def c_mag(t): return _c('35', t)
def c_ok(t): return c_green('✓ ' + t)
def c_err(t): return c_red('✗ ' + t)
def c_warn(t): return c_yellow('⚠ ' + t)
def c_info(t): return c_cyan('→ ' + t)
def print_ok(t): print(c_ok(t))
def print_err(t): print(c_err(t), file=sys.stderr)
def print_warn(t): print(c_warn(t), file=sys.stderr)
def print_info(t): print(c_info(t))
def print_header(t): print(c_bold(c_mag(t)))
# ===== Install mode & paths =====
def _early_install_mode_user() -> bool:
mode = os.environ.get('GPTADMIN_INSTALL_MODE', '').strip().lower()
if mode in {'user', 'userspace', 'local', 'nonroot'}:
return True
if mode in {'system', 'root', 'admin'}:
return False
if '--user' in sys.argv:
return True
if '--system' in sys.argv:
return False
try:
return os.geteuid() != 0
except Exception:
return False
def _install_user_home() -> Path:
if os.environ.get('GPTADMIN_USER_HOME'):
return Path(os.environ['GPTADMIN_USER_HOME']).expanduser()
try:
if os.geteuid() == 0:
sudo_user = os.environ.get('SUDO_USER')
if sudo_user and sudo_user != 'root':
try:
return Path(pwd.getpwnam(sudo_user).pw_dir)
except Exception:
return Path('/Users' if IS_MACOS else '/home') / sudo_user
except Exception:
pass
return Path.home()
IS_USER_INSTALL = _early_install_mode_user()
INSTALL_SCOPE = 'user' if IS_USER_INSTALL else 'system'
USER_HOME = _install_user_home()
if IS_USER_INSTALL:
INSTALL_DIR = Path(os.environ.get('GPTADMIN_HOME', str(USER_HOME / '.local' / 'share' / 'gptadmin'))).expanduser()
ETC_DIR = Path(os.environ.get('GPTADMIN_CONFIG_DIR', str(USER_HOME / '.config' / 'gptadmin'))).expanduser()
CLI_PATH = Path(os.environ.get('GPTADMIN_CLI_PATH', str(USER_HOME / '.local' / 'bin' / 'gptadmin'))).expanduser()
else:
INSTALL_DIR = Path(os.environ.get('GPTADMIN_HOME', '/opt/gptadmin'))
ETC_DIR = Path(os.environ.get('GPTADMIN_CONFIG_DIR', '/etc/gptadmin'))
CLI_PATH = Path(os.environ.get('GPTADMIN_CLI_PATH', '/usr/local/bin/gptadmin'))
# ===== Paths & constants =====
BIN_DIR = INSTALL_DIR / 'bin'
ENV_FILE = ETC_DIR / 'gptadmin.env'
INSTALLED_BUILD_FILE = INSTALL_DIR / 'gptadmin_installed_build.json'
MCP_CONFIG_FILE = ETC_DIR / 'mcp.json'
UPDATE_CHECK_CACHE = INSTALL_DIR / 'update_check.json'
UPDATE_CHECK_COOLDOWN_S = 3600 # 1 hour after failed network attempt
UPDATE_CHECK_FRESH_S = 86400 # 24 hours for successful check
UPDATE_CHECK_TIMEOUT_S = 3 # manifest fetch timeout
MCP_AGENTS_DIR = ETC_DIR / 'mcp-agents.d'
MCP_SUPERVISOR_CONFIG = ETC_DIR / 'mcp-supervisor.json'
MCP_TOKEN_FILE = ETC_DIR / 'mcp-relay.token'
MCP_RUNTIME_DIR = INSTALL_DIR / 'agents' / 'generic_stdio_mcp_relay'
MCP_MANAGER = MCP_RUNTIME_DIR / 'mcp_agent_manager.py'
MCP_RELAY = MCP_RUNTIME_DIR / 'generic_stdio_mcp_relay.py'
if IS_MACOS:
SERVICES_DIR = USER_HOME / 'Library' / 'LaunchAgents' if IS_USER_INSTALL else Path('/Library/LaunchDaemons')
LOG_DIR = USER_HOME / 'Library' / 'Logs' / 'gptadmin' if IS_USER_INSTALL else Path('/var/log/gptadmin')
# Optional test namespace for parallel macOS launchd installs.
# Example: GPTADMIN_SERVICE_SUFFIX=.e2e42 -> com.gptadmin.e2e42.hub
# Empty by default, so normal production labels stay unchanged.
SERVICE_SUFFIX = os.environ.get('GPTADMIN_SERVICE_SUFFIX', '').strip()
if SERVICE_SUFFIX and not re.fullmatch(r'[A-Za-z0-9_.-]+', SERVICE_SUFFIX):
die('GPTADMIN_SERVICE_SUFFIX may contain only letters, digits, dot, underscore and dash')
SERVICE_PREFIX = f'com.gptadmin{SERVICE_SUFFIX}'
SVC_HUB_LABEL = f'{SERVICE_PREFIX}.hub'
SVC_SHELLMCP_LABEL = f'{SERVICE_PREFIX}.shellmcp'
SVC_FRPC_LABEL = f'{SERVICE_PREFIX}.tunnel-frpc'
SVC_CLOUDFLARED_LABEL = f'{SERVICE_PREFIX}.cloudflared'
SVC_AUTO_UPDATE_LABEL = f'{SERVICE_PREFIX}.auto-update'
UNIT_PATH_HUB = SERVICES_DIR / f'{SVC_HUB_LABEL}.plist'
UNIT_PATH_SHELLMCP = SERVICES_DIR / f'{SVC_SHELLMCP_LABEL}.plist'
UNIT_PATH_FRPC = SERVICES_DIR / f'{SVC_FRPC_LABEL}.plist'
UNIT_PATH_CLOUDFLARED = SERVICES_DIR / f'{SVC_CLOUDFLARED_LABEL}.plist'
UNIT_PATH_AUTO_UPDATE = SERVICES_DIR / f'{SVC_AUTO_UPDATE_LABEL}.plist'
FRPC_CONF = ETC_DIR / 'frpc.toml'
else:
SYSTEMD_DIR = USER_HOME / '.config' / 'systemd' / 'user' if IS_USER_INSTALL else Path('/etc/systemd/system')
LOG_DIR = Path(os.environ.get(
'GPTADMIN_LOG_DIR',
str((USER_HOME / '.local' / 'state' / 'gptadmin' / 'logs') if IS_USER_INSTALL else Path('/var/log/gptadmin'))
)).expanduser()
SYSTEMD_HUB = 'gptadmin-hub.service'
SYSTEMD_SHELLMCP = 'gptadmin-shellmcp.service'
SYSTEMD_FRPC = 'gptadmin-tunnel-frpc.service'
SYSTEMD_CLOUDFLARED = 'gptadmin-cloudflared.service'
SYSTEMD_AUTO_UPDATE = 'gptadmin-auto-update.service'
SYSTEMD_AUTO_UPDATE_TIMER = 'gptadmin-auto-update.timer'
UNIT_PATH_HUB = SYSTEMD_DIR / SYSTEMD_HUB
UNIT_PATH_SHELLMCP = SYSTEMD_DIR / SYSTEMD_SHELLMCP
UNIT_PATH_FRPC = SYSTEMD_DIR / SYSTEMD_FRPC
UNIT_PATH_CLOUDFLARED = SYSTEMD_DIR / SYSTEMD_CLOUDFLARED
UNIT_PATH_AUTO_UPDATE = SYSTEMD_DIR / SYSTEMD_AUTO_UPDATE
UNIT_PATH_AUTO_UPDATE_TIMER = SYSTEMD_DIR / SYSTEMD_AUTO_UPDATE_TIMER
FRPC_CONF = ETC_DIR / 'frpc.toml'
# Package URLs can be overridden by env or args
PKG_BASE_URL_DEFAULT = os.environ.get('PKG_BASE_URL', 'https://github.com/megamen32/gptadmin_opensource/releases/latest/download').rstrip('/')
PKG_ALL_URL_DEFAULT = os.environ.get('PKG_ALL_URL', f'{PKG_BASE_URL_DEFAULT}/gptadmin.tar.gz')
PKG_HUB_URL_DEFAULT = os.environ.get('PKG_HUB_URL', f'{PKG_BASE_URL_DEFAULT}/gptadmin-hub.tar.gz')
PKG_SHELLMCP_URL_DEFAULT = os.environ.get('PKG_SHELLMCP_URL', f'{PKG_BASE_URL_DEFAULT}/gptadmin-shellmcp.tar.gz')
REQUIRED_CMDS = ['curl', 'launchctl' if IS_MACOS else 'systemctl']
# ===== macOS plist + launchctl helpers (module-level for cross-platform testability) =====
# These helpers live at module level so they can be unit-tested on Linux even
# though they generate launchd-only artifacts. The Darwin-only branch below
# composes them; Linux never imports them.
def _plist_oneshot(label: str, wrapper: Path, log_file: Path, interval: int | None = None) -> str:
"""Generate a launchd plist for the auto-update oneshot job.
Semantics:
- RunAtLoad=false and KeepAlive=false: the job does NOT start on its own
and does NOT auto-restart. It must be triggered explicitly via
`launchctl kickstart` (which is what we use for both periodic and
manual update triggers).
- AbandonProcessGroup=true: prevents launchd from sending SIGTERM to
the wrapper's process group on bootout. The job is therefore allowed
to complete even if the parent launchd job is unloaded mid-run.
Children are *abandoned*, not cleaned up. The wrapper `exec`s into
the CLI without forking, so we have no children to worry about;
the flag is set for bootout-resilience, not for cleanup.
- StartInterval (optional): if provided, launchd schedules the job to
run every <interval> seconds. When omitted, the plist is a pure
"service unit always present" that does nothing until kicked.
"""
interval_line = (
f' <key>StartInterval</key><integer>{int(interval)}</integer>\n'
if interval is not None else ''
)
return (
'<?xml version="1.0" encoding="UTF-8"?>\n'
'<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"'
' "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n'
'<plist version="1.0"><dict>\n'
f' <key>Label</key><string>{label}</string>\n'
' <key>ProgramArguments</key><array>\n'
' <string>/bin/sh</string>\n'
f' <string>{wrapper}</string>\n'
' </array>\n'
' <key>RunAtLoad</key><false/>\n'
' <key>KeepAlive</key><false/>\n'
' <key>AbandonProcessGroup</key><true/>\n'
f'{interval_line}'
f' <key>StandardOutPath</key><string>{log_file}</string>\n'
f' <key>StandardErrorPath</key><string>{log_file}</string>\n'
'</dict></plist>\n'
)
def _launchctl_kickstart_cmd(label: str, is_user: bool) -> list[str]:
"""Return the argv for `launchctl kickstart -k <domain>/<label>`.
The `-k` flag kills any existing instance first, then starts a fresh one.
That makes the same invocation safe for both "first ever run" and
"already-running, restart" — which is exactly what the auto-update path
needs.
"""
if is_user:
try:
uid = str(os.getuid())
except Exception:
uid = '0'
domain = f'gui/{uid}'
else:
domain = 'system'
return ['launchctl', 'kickstart', '-k', f'{domain}/{label}']
# ===== FRPC defaults =====
FRPC_VERSION = os.environ.get('FRPC_VERSION', '0.64.0')
FRPC_BASE_URL = os.environ.get('FRPC_BASE_URL', 'https://became.bezrabotnyi.com/frp-mirror')
FRPC_SERVER_ADDR_DEFAULT = 'gptadmin.bezrabotnyi.com'
FRPC_SERVER_PORT_DEFAULT = '7000'
FRPC_TOKEN_DEFAULT = 'E10WCLE7ZFT+0NDgOFWwyPV8fb7hG7cLn320aHL0fVk='
FRPC_DOMAIN_DEFAULT = 't.gptadmin.bezrabotnyi.com'
FRPC_SERVER_ENDPOINTS_DEFAULT = os.environ.get(
'FRPC_SERVER_ENDPOINTS_DEFAULT',
'primary=gptadmin.bezrabotnyi.com:7000,vpn2=vpn2.bezrabotnyi.com:27000,vusa=vusa.bezrabotnyi.com:27000'
).strip()
CLOUDFLARED_VERSION = os.environ.get('CLOUDFLARED_VERSION', 'latest')
# ===== Helpers =====
def die(msg: str, code: int = 1):
print(f'ERROR: {msg}', file=sys.stderr)
sys.exit(code)
def need_root():
if IS_USER_INSTALL:
return
if os.geteuid() != 0:
die('run as root (sudo), or use --user / GPTADMIN_INSTALL_MODE=user')
def have(cmd: str) -> bool:
return shutil.which(cmd) is not None
def run(cmd, check=True, capture=False, timeout=None):
try:
if capture:
return subprocess.run(cmd, check=check, text=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, timeout=timeout)
return subprocess.run(cmd, check=check, timeout=timeout)
except subprocess.TimeoutExpired as e:
if check:
raise
print(f'WARNING: command timed out and was ignored: {cmd}', file=sys.stderr)
return subprocess.CompletedProcess(cmd, 124, stdout=getattr(e, 'stdout', None), stderr=getattr(e, 'stderr', None))
# .env read/write
def env_read() -> dict:
d = {}
if ENV_FILE.exists():
for raw in ENV_FILE.read_text().splitlines():
line = raw.strip()
if not line or line.startswith('#'):
continue
if '=' in line:
k, v = line.split('=', 1)
d[k.strip()] = v.strip()
return d
def env_set_many(upd: dict):
cur = env_read()
cur.update(upd)
lines = [f'{k}={cur[k]}' for k in sorted(cur.keys())]
ENV_FILE.parent.mkdir(parents=True, exist_ok=True)
tmp = ENV_FILE.with_name(f'.{ENV_FILE.name}.{os.getpid()}.tmp')
try:
tmp.write_text('\n'.join(lines) + '\n')
os.chmod(tmp, 0o640)
os.replace(tmp, ENV_FILE)
finally:
tmp.unlink(missing_ok=True)
_PERSISTENT_AUTH_KEYS = frozenset({
'CTL_TOKEN',
'SHELLMCP_TOKEN',
'ADMIN_PASSWORD',
'OAUTH_CLIENT_SECRET',
'MCP_BRIDGE_KEY',
'MCP_RELAY_AGENT_TOKEN',
'SHELLMCP_UPDATE_TOKEN',
})
def _capture_persistent_auth_material(env: dict) -> dict[str, str]:
"""Capture secrets and client JWTs that an in-place update must preserve."""
return {
key: str(value)
for key, value in env.items()
if value and (key in _PERSISTENT_AUTH_KEYS or key.startswith('GPTADMIN_') and key.endswith('_MCP_BEARER'))
}
def _restore_persistent_auth_material(env: dict, saved: dict[str, str]) -> None:
"""Restore auth material captured before package replacement."""
env.update(saved)
def ensure_shellmcp_default_user(env: dict) -> None:
"""Persist the invoking non-root account for ordinary ShellMCP commands."""
if env.get('SHELL_DEFAULT_USER') or env.get('SHELLMCP_DEFAULT_USER'):
return
candidate = os.environ.get('SHELLMCP_DEFAULT_USER') or os.environ.get('SHELL_DEFAULT_USER')
if not candidate:
sudo_user = os.environ.get('SUDO_USER', '')
if sudo_user and sudo_user != 'root':
candidate = sudo_user
if not candidate:
try:
if os.geteuid() != 0:
candidate = pwd.getpwuid(os.geteuid()).pw_name
except (AttributeError, KeyError, OSError):
pass
if not candidate or candidate == 'root':
return
try:
home = pwd.getpwnam(candidate).pw_dir
except KeyError:
home = str(Path('/Users' if IS_MACOS else '/home') / candidate)
env.setdefault('SHELLMCP_DEFAULT_USER', candidate)
env.setdefault('SHELLMCP_DEFAULT_HOME', home)
env.setdefault('SHELLMCP_DEFAULT_CWD', home)
def env_remove_keys(keys: list[str]):
cur = env_read()
changed = False
for key in keys:
if key in cur:
cur.pop(key, None)
changed = True
if changed:
lines = [f'{k}={cur[k]}' for k in sorted(cur.keys())]
ENV_FILE.parent.mkdir(parents=True, exist_ok=True)
ENV_FILE.write_text('\n'.join(lines) + '\n')
os.chmod(ENV_FILE, 0o640)
def env_bool(env: dict, key: str, default: bool = False) -> bool:
raw = env.get(key)
if raw is None or str(raw).strip() == '':
return default
return str(raw).strip().lower() in {'1', 'true', 'yes', 'on'}
def auto_update_enabled(env: dict) -> bool:
# Автообновление GPTAdmin включено по умолчанию. Отключается явно:
# GPTADMIN_AUTO_UPDATE=false или `gptadmin auto-update disable`.
return env_bool(env, 'GPTADMIN_AUTO_UPDATE', True)
def auto_update_interval_seconds(env: dict) -> int:
try:
value = int(str(env.get('GPTADMIN_AUTO_UPDATE_INTERVAL_SEC') or '21600').strip())
except Exception:
value = 21600
return max(value, 300)
def auto_update_randomized_delay_seconds(env: dict) -> int:
try:
value = int(str(env.get('GPTADMIN_AUTO_UPDATE_RANDOM_DELAY_SEC') or '1800').strip())
except Exception:
value = 1800
return max(value, 0)
# tokens
def gen_hex(nbytes=16) -> str:
try:
return secrets.token_hex(nbytes)
except Exception:
out = run(['openssl', 'rand', '-hex', str(nbytes)], capture=True)
return out.stdout.strip()
def gen_subdomain() -> str:
return f"u-{gen_hex(4)}"
# network
def first_ip() -> str:
try:
hostname = socket.gethostname()
ips = socket.gethostbyname_ex(hostname)[2]
for ip in ips:
if ip and ip != '127.0.0.1':
return ip
except Exception:
pass
return '127.0.0.1'
# http(s) URL validator
HTTPS_RE = re.compile(r'^https://[A-Za-z0-9._\-]+(:\d+)?(/.*)?$')
def ensure_https(url: str):
if not HTTPS_RE.match(url or ''):
die('Нужен корректный HTTPS URL (например, https://gptadmin.example.com)')
# download & extract
def download(url: str, dest: Path):
"""Download a file with curl's progress meter visible.
curl's default meter shows total size, received bytes, average speed,
elapsed time, estimated time left and current speed when Content-Length is
available. Set GPTADMIN_DOWNLOAD_QUIET=1 to keep the old silent behavior.
"""
quiet = os.environ.get('GPTADMIN_DOWNLOAD_QUIET', '').strip().lower() in {'1', 'true', 'yes', 'on'}
if quiet:
cmd = ['curl', '-fsSL', url, '-o', str(dest)]
else:
print(f' URL: {url}', flush=True)
cmd = ['curl', '-fL', url, '-o', str(dest)]
run(cmd)
try:
size = dest.stat().st_size
except OSError:
size = 0
if size:
print(f' Готово: {size / (1024 * 1024):.1f} MiB -> {dest}', flush=True)
def extract_tgz(tgz_path: Path, target_dir: Path):
with tarfile.open(tgz_path, 'r:gz') as tar:
tar.extractall(path=target_dir)
# package install
def _install_cli_executable_from_file(src: Path):
if not src.exists() or not src.is_file():
return
try:
candidate_text = src.read_text(encoding='utf-8', errors='replace')
current_text = CLI_PATH.read_text(encoding='utf-8', errors='replace') if CLI_PATH.exists() else ''
# Do not let older component packages downgrade a CLI that already knows
# about the new automatic updater. Fresh/future packages with cmd_autoupdate
# still update the executable normally.
if 'cmd_autoupdate' in current_text and 'cmd_autoupdate' not in candidate_text:
print(f'WARNING: package CLI {src} is older than installed CLI; keeping {CLI_PATH}', file=sys.stderr)
return
except Exception as exc:
print(f'WARNING: could not inspect package CLI {src}: {exc}; keeping installed CLI', file=sys.stderr)
return
CLI_PATH.parent.mkdir(parents=True, exist_ok=True)
tmp = CLI_PATH.with_name(CLI_PATH.name + '.new')
shutil.copy2(src, tmp)
os.chmod(tmp, 0o755)
os.replace(tmp, CLI_PATH)
def _copy_pkg_runtime_payloads(tdp: Path):
cli_src = tdp / 'cli'
if cli_src.exists():
_install_cli_executable_from_file(cli_src / 'gptadmin.py')
cli_dst = INSTALL_DIR / 'cli'
if cli_dst.exists():
shutil.rmtree(cli_dst, ignore_errors=True)
shutil.copytree(cli_src, cli_dst)
agents_src = tdp / 'agents'
if agents_src.exists():
agents_dst = INSTALL_DIR / 'agents'
if agents_dst.exists():
shutil.rmtree(agents_dst, ignore_errors=True)
shutil.copytree(agents_src, agents_dst)
client_src = tdp / 'client'
if client_src.exists():
client_dst = INSTALL_DIR / 'client'
if client_dst.exists():
shutil.rmtree(client_dst, ignore_errors=True)
shutil.copytree(client_src, client_dst)
def _arch_tag() -> str:
machine = (os.uname().machine if hasattr(os, 'uname') else '').lower()
if machine in {'arm64', 'aarch64'}:
return 'arm64'
if machine in {'x86_64', 'amd64'}:
return 'amd64'
return machine or 'unknown'
def platform_pkg_url_default() -> str:
platform = 'darwin' if IS_MACOS else 'linux'
return os.environ.get('PKG_PLATFORM_URL', f'{PKG_BASE_URL_DEFAULT}/gptadmin-{platform}-{_arch_tag()}.tar.gz')
def _platform_hub_candidates(tdp: Path) -> list[Path]:
if IS_MACOS:
arch = _arch_tag()
tags = [f'darwin_{arch}', f'macos_{arch}']
# Legacy location is accepted only when the archive itself was built on macOS.
legacy = [tdp / 'gptadmin_hub' / 'dist' / 'gptadmin_hub']
else:
arch = _arch_tag()
tags = [f'linux_{arch}']
legacy = [tdp / 'gptadmin_hub' / 'dist' / 'gptadmin_hub', tdp / 'build' / 'gptadmin_hub' / 'dist' / 'gptadmin_hub']
return [tdp / 'gptadmin_hub' / tag / 'gptadmin_hub' for tag in tags] + legacy
def _binary_looks_native(path: Path) -> bool:
if not IS_MACOS:
return True
try:
out = run(['/usr/bin/file', str(path)], check=False, capture=True).stdout
except Exception:
return True
return 'Mach-O' in out
def _macos_unquarantine_and_codesign(path: Path):
if not IS_MACOS:
return
# Files extracted from browser/curl-delivered archives can inherit macOS
# provenance/quarantine metadata. launchd may then kill ad-hoc binaries with
# OS_REASON_CODESIGNING. Clear xattrs and apply a local ad-hoc signature.
run(['/usr/bin/xattr', '-cr', str(path)], check=False, timeout=10)
if _binary_looks_native(path):
run(['/usr/bin/codesign', '--force', '--sign', '-', str(path)], check=False, timeout=20)
def _install_hub_binary_from_pkg(tdp: Path):
for c in _platform_hub_candidates(tdp):
if c.exists() and _binary_looks_native(c):
BIN_DIR.mkdir(parents=True, exist_ok=True)
dst = BIN_DIR / 'gptadmin_hub'
shutil.copy2(c, dst)
os.chmod(dst, 0o755)
_macos_unquarantine_and_codesign(dst)
return
if IS_MACOS:
die('macOS gptadmin_hub binary not found in package: expected gptadmin_hub/darwin_arm64/gptadmin_hub or gptadmin_hub/darwin_amd64/gptadmin_hub')
die('gptadmin_hub binary not found in package')
def _shellmcp_go_binary_candidates(tdp: Path) -> list[Path]:
arch = _arch_tag()
if IS_MACOS:
tags = [f'darwin_{arch}', f'macos_{arch}']
else:
tags = [f'linux_{arch}']
names = ('shellmcp-go', 'rootd-go', 'rootd-go-canary', 'shellmcp')
roots = (
tdp / 'go-shellmcp',
tdp / 'shellmcp-go',
tdp / 'rootd-go',
tdp / 'shellmcp',
tdp / 'build' / 'go-shellmcp',
tdp / 'build' / 'shellmcp-go',
tdp / 'build' / 'rootd-go',
)
out: list[Path] = []
for root in roots:
for tag in tags:
for name in names:
out.append(root / tag / name)
for name in names:
out.append(root / name)
out += [tdp / name for name in names]
return out
def _install_shellmcp_binary_from_pkg(tdp: Path) -> None:
# ShellMCP is now Go-only (go-shellmcp). Legacy Python/PyInstaller fallback removed.
for c in _shellmcp_go_binary_candidates(tdp):
if c.exists() and c.is_file():
BIN_DIR.mkdir(parents=True, exist_ok=True)
dst = BIN_DIR / 'shellmcp'
shutil.copy2(c, dst)
os.chmod(dst, 0o755)
_macos_unquarantine_and_codesign(dst)
return
die('Go ShellMCP/rootd binary not found in package. Legacy Python/PyInstaller shellmcp has been removed; ensure the package contains go-shellmcp/<platform>/<arch>/shellmcp-go or rootd-go.')
def _cleanup_obsolete_runtime_files():
"""Remove obsolete replaceable runtime files after an in-place upgrade.
User configuration, identities, tokens, logs, registry state and MCP config are
intentionally preserved. Only old executable aliases, interrupted .new files
and binary backup artifacts are removed.
"""
obsolete = [
BIN_DIR / 'rootd-go',
BIN_DIR / 'rootd-go-canary',
BIN_DIR / 'shellmcp-go',
BIN_DIR / 'gptadmin_hub.py',
BIN_DIR / 'shellmcp.py',
BIN_DIR / 'shellmcp_pure.py',
CLI_PATH.with_name(CLI_PATH.name + '.new'),
]
for path in obsolete:
try:
if path.is_dir():
shutil.rmtree(path)
else:
path.unlink()
except FileNotFoundError:
pass
for directory in (BIN_DIR, CLI_PATH.parent):
if not directory.exists():
continue
for pattern in ('*.bak.*', '*.old', '*.new'):
for path in directory.glob(pattern):
try:
if path.is_dir():
shutil.rmtree(path)
else:
path.unlink()
except FileNotFoundError:
pass
def install_component_from_pkg(pkg_tgz: Path, component: str):
with tempfile.TemporaryDirectory() as td:
tdp = Path(td)
extract_tgz(pkg_tgz, tdp)
_copy_pkg_runtime_payloads(tdp)
if component == 'hub':
_install_hub_binary_from_pkg(tdp)
return
if component == 'shellmcp':
_install_shellmcp_binary_from_pkg(tdp)
return
die(f'unknown component: {component}')
# ===== Service management =====
if IS_MACOS:
def _mac_python() -> str:
candidates = [
os.environ.get('GPTADMIN_PYTHON'),
'/Library/Frameworks/Python.framework/Versions/3.11/bin/python3',
'/opt/homebrew/bin/python3',
'/usr/local/bin/python3',
sys.executable,
'/usr/bin/python3',
]
for c in candidates:
if c and Path(c).exists():
return c
return 'python3'
def _plist_path(label: str) -> Path:
return SERVICES_DIR / f'{label}.plist'
def _wrapper_script(name: str, bin_path: Path) -> Path:
LOG_DIR.mkdir(parents=True, exist_ok=True)
script = BIN_DIR / f'run_{name}.sh'
if name == 'shellmcp' and not _binary_looks_native(bin_path):
exec_line = f'PYTHONPATH={INSTALL_DIR}/client${{PYTHONPATH:+:$PYTHONPATH}} exec {_mac_python()} {bin_path}'
else:
exec_line = f'exec {bin_path}'
script.write_text(
f'#!/bin/sh\n'
f'set -a; [ -f {ENV_FILE} ] && . {ENV_FILE}; set +a\n'
f'{exec_line}\n'
)
os.chmod(script, 0o755)
return script
def _make_plist(label: str, wrapper: Path, log_file: Path) -> str:
# Long-running launchd service plist (hub / shellmcp / frpc / cloudflared):
# KeepAlive=true so launchd respawns the job if it exits, and RunAtLoad
# so it boots with the system. The auto-update path does NOT use this
# template — see _plist_oneshot at module level for oneshot semantics.
return (
'<?xml version="1.0" encoding="UTF-8"?>\n'
'<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"'
' "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n'
'<plist version="1.0"><dict>\n'
f' <key>Label</key><string>{label}</string>\n'
' <key>ProgramArguments</key><array>\n'
' <string>/bin/sh</string>\n'
f' <string>{wrapper}</string>\n'
' </array>\n'
' <key>RunAtLoad</key><true/>\n'
' <key>KeepAlive</key><true/>\n'
f' <key>StandardOutPath</key><string>{log_file}</string>\n'
f' <key>StandardErrorPath</key><string>{log_file}</string>\n'
'</dict></plist>\n'
)
def _make_interval_plist(label: str, wrapper: Path, log_file: Path, interval: int) -> str:
# Kept as a thin wrapper for backwards compatibility with any external
# caller. New auto-update code calls module-level _plist_oneshot
# directly so the template is testable on Linux.
return _plist_oneshot(label, wrapper, log_file, interval=interval)
def svc_daemon_reload():
pass # launchd has no daemon-reload
def svc_enable(label: str, unit_path: Path):
# Load the (possibly rewritten) plist into launchd WITHOUT starting
# the job. This is the right primitive for "I just changed the plist
# config — pick up the new file but do not run the job now." Used by:
# * write_autoupdate_unit (install-time registration; we want the
# job loaded so manual kickstart works, but we do NOT want a
# surprise update to fire at install time).
# * timer_disable (user said "stop periodic updates" — we rewrite
# the plist without StartInterval; loading it must not run the
# job because that would violate the user's intent).
#
# macOS launchctl load/unload is legacy and can silently fail to
# restore a LaunchAgent after bootout during in-place update. Prefer
# bootstrap into the explicit domain, then enable; keep load -w as
# fallback for older systems.
domain = _launchd_domain()
# A missing/unloaded launchd job is normal during update or first install.
# `launchctl bootout` prints "Boot-out failed: 3: No such process" to
# stderr in that case; suppress it so a harmless pre-cleanup does not look
# like an update failure.
_launchctl_capture(['launchctl', 'bootout', _launchd_service_target(label)])
bootstrap = _launchctl_capture(['launchctl', 'bootstrap', domain, str(unit_path)])
if bootstrap.returncode != 0 and not _launchd_is_loaded(label):
# A stale launchd registration can transiently return EIO. Retry once
# after removing the label, while keeping harmless output quiet.
_launchctl_capture(['launchctl', 'remove', label])
time.sleep(0.2)
bootstrap = _launchctl_capture(['launchctl', 'bootstrap', domain, str(unit_path)])
_launchctl_capture(['launchctl', 'enable', _launchd_service_target(label)])
if not _launchd_is_loaded(label):
run(['launchctl', 'load', '-w', str(unit_path)], check=False)
if not _launchd_is_loaded(label):
raise RuntimeError(f'launchd service did not load: {_launchd_service_target(label)}')
def svc_enable_start(label: str, unit_path: Path):
# Load the plist AND kickstart it. Used for long-running services
# (hub / shellmcp / frpc / cloudflared) where RunAtLoad + KeepAlive
# semantics mean "bootstrap should also start the job now." Do NOT
# use this for oneshot plists whose purpose is to be triggered only
# on explicit kickstart (e.g., auto-update) — calling it there
# would fire one unintended run per config reload.
svc_enable(label, unit_path)
# kickstart can block for long-running LaunchAgents on some macOS
# versions; keep kickstart as silent best-effort only.
try:
subprocess.run(
['launchctl', 'kickstart', '-k', _launchd_service_target(label)],
check=False, text=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
timeout=int(os.environ.get('GPTADMIN_LAUNCHCTL_KICKSTART_TIMEOUT', '2')),
)
except subprocess.TimeoutExpired:
pass
def svc_restart(label: str, unit_path: Path):
svc_disable_stop(label, unit_path)
svc_enable_start(label, unit_path)
def _launchd_uid() -> str:
if IS_USER_INSTALL:
sudo_uid = os.environ.get('SUDO_UID')
if sudo_uid and sudo_uid != '0':
return sudo_uid
try:
return str(os.getuid())
except Exception:
return '0'
return ''
def _launchd_domain() -> str:
return f'gui/{_launchd_uid()}' if IS_USER_INSTALL else 'system'
def _launchctl_capture(args: list[str]) -> subprocess.CompletedProcess:
return subprocess.run(args, check=False, text=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
def _launchd_service_target(label: str) -> str:
return f'{_launchd_domain()}/{label}'
def _launchd_is_loaded(label: str) -> bool:
return _launchctl_capture(['launchctl', 'print', _launchd_service_target(label)]).returncode == 0
def _launchd_stop(label: str, unit_path: Path) -> tuple[bool, list[str]]:
attempts = [
['launchctl', 'bootout', _launchd_service_target(label)],
['launchctl', 'remove', label],
]
if unit_path.exists():
attempts.insert(1, ['launchctl', 'bootout', _launchd_domain(), str(unit_path)])
attempts.append(['launchctl', 'unload', '-w', str(unit_path)])
messages: list[str] = []
for cmd in attempts:
res = _launchctl_capture(cmd)
if res.returncode != 0 and res.stdout.strip():
messages.append('$ ' + ' '.join(cmd) + '\n' + res.stdout.strip())
loaded = _launchd_is_loaded(label)
if loaded and not messages:
messages.append(f'launchd service is still loaded: {_launchd_service_target(label)}')
return (not loaded), messages
def svc_disable_stop(label: str, unit_path: Path):
ok, messages = _launchd_stop(label, unit_path)
if not ok:
print(f'WARN: не удалось выгрузить launchd service {label}', file=sys.stderr)
for msg in messages[-3:]:
print(msg, file=sys.stderr)
return ok
def svc_status_multi(labels_and_paths):
for label, path in labels_and_paths:
if not path.exists():
print(f' {c_bold(label):<40} {c_red("● missing")}')
continue
r = _launchctl_capture(['launchctl', 'list', label])
out = r.stdout or ''
pid = '0'
status = 'not loaded' if r.returncode != 0 else 'unknown'
for line in out.splitlines():
stripped = line.strip()
if stripped.startswith('"PID"'):
pid = stripped.split('=')[-1].strip().rstrip(';')
elif stripped.startswith('"state"'):
status = stripped.split('=')[-1].strip().strip('"').rstrip(';')
if status == 'unknown' and pid not in ('', '0'):
status = 'running'
if status == 'running':
status_str = c_green('● running')
elif status in ('exited',):
status_str = c_yellow('● exited')
elif status in ('not loaded',):
status_str = c_red('● not loaded')
else:
status_str = c_yellow('● ' + status)
print(f' {c_bold(label):<40} {status_str} PID {c_dim(pid):<8}')
def svc_start_multi(labels_and_paths):
for label, path in labels_and_paths:
if path.exists():
svc_enable_start(label, path)
def svc_stop_multi(labels_and_paths):
for label, path in reversed(labels_and_paths):
if path.exists() or _launchd_is_loaded(label):
svc_disable_stop(label, path)
def svc_logs_one(_label: str, log_file: Path):
if log_file.exists():
run(['tail', '-n', '200', '-f', str(log_file)], check=False)
else:
print(f'Лог-файл не найден: {log_file}')
def svc_logs_all(labels_paths_logs):
for _, _, log_file in labels_paths_logs:
if log_file and log_file.exists():
run(['tail', '-n', '200', '-f', str(log_file)], check=False)
def write_hub_unit(install_hub: bool, _install_shellmcp: bool):
if not install_hub:
return
LOG_DIR.mkdir(parents=True, exist_ok=True)
wrapper = _wrapper_script('hub', BIN_DIR / 'gptadmin_hub')
SERVICES_DIR.mkdir(parents=True, exist_ok=True)
UNIT_PATH_HUB.write_text(_make_plist(SVC_HUB_LABEL, wrapper, LOG_DIR / 'hub.log'))
def write_shellmcp_unit(_install_hub: bool, install_shellmcp: bool):
if not install_shellmcp:
return
LOG_DIR.mkdir(parents=True, exist_ok=True)
wrapper = _wrapper_script('shellmcp', BIN_DIR / 'shellmcp')
SERVICES_DIR.mkdir(parents=True, exist_ok=True)
UNIT_PATH_SHELLMCP.write_text(_make_plist(SVC_SHELLMCP_LABEL, wrapper, LOG_DIR / 'shellmcp.log'))
def write_frpc_unit(frpc_bin: str):
LOG_DIR.mkdir(parents=True, exist_ok=True)
SERVICES_DIR.mkdir(parents=True, exist_ok=True)
wrapper = BIN_DIR / 'run_frpc_all.sh'
wrapper.write_text(frpc_wrapper_script(frpc_bin, env_read()))
os.chmod(wrapper, 0o755)
UNIT_PATH_FRPC.write_text(_make_plist(SVC_FRPC_LABEL, wrapper, LOG_DIR / 'frpc.log'))
def write_cloudflared_unit(cloudflared_bin: str, env: dict):
LOG_DIR.mkdir(parents=True, exist_ok=True)
wrapper = BIN_DIR / 'run_cloudflared.sh'
local_url = f"http://127.0.0.1:{env.get('HUB_PORT', '9001')}"
wrapper.write_text(
f'#!/bin/sh\n'
f'set -a; [ -f {ENV_FILE} ] && . {ENV_FILE}; set +a\n'
f'exec {cloudflared_bin} tunnel --protocol http2 --url {local_url} --no-autoupdate\n'
)
os.chmod(wrapper, 0o755)
SERVICES_DIR.mkdir(parents=True, exist_ok=True)
UNIT_PATH_CLOUDFLARED.write_text(_make_plist(SVC_CLOUDFLARED_LABEL, wrapper, LOG_DIR / 'cloudflared.log'))
def write_autoupdate_unit(env: dict):
LOG_DIR.mkdir(parents=True, exist_ok=True)
BIN_DIR.mkdir(parents=True, exist_ok=True)
SERVICES_DIR.mkdir(parents=True, exist_ok=True)
wrapper = BIN_DIR / 'run_auto_update.sh'
wrapper.write_text(
f'#!/bin/sh\n'
f'set -a; [ -f {ENV_FILE} ] && . {ENV_FILE}; set +a\n'
f'exec {CLI_PATH} --{INSTALL_SCOPE} update --auto\n'
)
os.chmod(wrapper, 0o755)
# Always present, oneshot-style: RunAtLoad/KeepAlive are false so the
# job does nothing on its own. StartInterval is omitted entirely so we
# never accidentally auto-run until timer_enable rewrites the plist
# with an interval. Keep the wrapper around for both periodic and
# manual `launchctl kickstart` invocations.
UNIT_PATH_AUTO_UPDATE.write_text(
_plist_oneshot(SVC_AUTO_UPDATE_LABEL, wrapper, LOG_DIR / 'auto-update.log'))
# Register the job with launchd so manual `launchctl kickstart` works
# on a fresh install. We use the LOAD-ONLY path (svc_enable, no
# kickstart) on purpose: a freshly installed auto-update must not
# fire on its own. The first kick only happens when the user clicks
# "update now" or when timer_enable rewrites the plist with a
# StartInterval and explicitly kicks once.
svc_enable(SVC_AUTO_UPDATE_LABEL, UNIT_PATH_AUTO_UPDATE)
def svc_hub_name(): return SVC_HUB_LABEL
def svc_shellmcp_name(): return SVC_SHELLMCP_LABEL
def svc_frpc_name(): return SVC_FRPC_LABEL
def svc_cloudflared_name(): return SVC_CLOUDFLARED_LABEL
def timer_enable(timer_unit: str):
env = env_read()
LOG_DIR.mkdir(parents=True, exist_ok=True)
BIN_DIR.mkdir(parents=True, exist_ok=True)
SERVICES_DIR.mkdir(parents=True, exist_ok=True)
wrapper = BIN_DIR / 'run_auto_update.sh'
wrapper.write_text(
f'#!/bin/sh\n'
f'set -a; [ -f {ENV_FILE} ] && . {ENV_FILE}; set +a\n'
f'exec {CLI_PATH} --{INSTALL_SCOPE} update --auto\n'
)
os.chmod(wrapper, 0o755)
# Rewrite the plist WITH StartInterval so launchd schedules the
# periodic trigger, then (re)load via the existing helper. The job
# was previously either absent or loaded without StartInterval; the
# enable_start path handles bootout + bootstrap so the new plist
# content is picked up.
UNIT_PATH_AUTO_UPDATE.write_text(
_plist_oneshot(SVC_AUTO_UPDATE_LABEL, wrapper, LOG_DIR / 'auto-update.log',
interval=auto_update_interval_seconds(env)))
svc_enable_start(SVC_AUTO_UPDATE_LABEL, UNIT_PATH_AUTO_UPDATE)
def timer_disable(timer_unit: str):
# Rewrite the plist WITHOUT StartInterval so launchd stops scheduling
# periodic runs. Keep the job loaded (do NOT call svc_disable_stop
# here) so manual `launchctl kickstart` invocations still work.
UNIT_PATH_AUTO_UPDATE.write_text(
_plist_oneshot(SVC_AUTO_UPDATE_LABEL, BIN_DIR / 'run_auto_update.sh',
LOG_DIR / 'auto-update.log'))
# Reload to pick up the StartInterval removal. Use the LOAD-ONLY
# path (svc_enable, no kickstart) on purpose: the user just said
# "stop periodic updates" — booting the new plist must NOT fire an
# update. The job is still loaded afterwards; only its schedule
# changed.
svc_enable(SVC_AUTO_UPDATE_LABEL, UNIT_PATH_AUTO_UPDATE)
def timer_status(timer_unit: str, timer_path: Path):
if not _launchd_is_loaded(SVC_AUTO_UPDATE_LABEL):
print(f' LaunchAgent {SVC_AUTO_UPDATE_LABEL} not loaded')
return
# Distinguish periodic vs manual mode by reading the StartInterval
# key from the on-disk plist. Periodic = enabled, no key = disabled
# but still present (manual kickstart still works).
on_disk = UNIT_PATH_AUTO_UPDATE
has_interval = False
if on_disk.exists():
try:
plist_xml = on_disk.read_text()
has_interval = '<key>StartInterval</key>' in plist_xml
except Exception:
pass
mode_str = c_green('● enabled (periodic)') if has_interval else c_yellow('● disabled (manual kickstart)')
print(f' {c_bold(SVC_AUTO_UPDATE_LABEL):<40} {mode_str}')
else:
# Linux systemd. In user mode this uses systemd --user and ~/.config/systemd/user.
LINUX_WANTED_BY = 'default.target' if IS_USER_INSTALL else 'multi-user.target'