-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.py
More file actions
6574 lines (5843 loc) · 289 KB
/
Copy pathcli.py
File metadata and controls
6574 lines (5843 loc) · 289 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 gzip
import io
import stat
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.parse
import urllib.request
import urllib.error
import pwd
from functools import wraps
from email.utils import parsedate_to_datetime
from pathlib import Path, PurePosixPath
# The curl bootstrap must run on a stock Python installation. The signed
# optional MCP catalogue is the only feature that needs ``cryptography``;
# defer that dependency so setup/update are not blocked before packages can
# install their runtime payloads.
try:
from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
except ImportError: # pragma: no cover - exercised in the installer subprocess
InvalidSignature = ValueError
Ed25519PublicKey = None
try:
import tomllib
except Exception:
tomllib = None
# CTL_TOKEN is a deprecated compatibility credential. New and updated
# installations do not create it, but an existing credential remains valid
# until its owner explicitly rotates or removes it.
# ===== Platform =====
IS_MACOS = sys.platform == 'darwin'
IS_WINDOWS = sys.platform == 'win32'
# ===== 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'
STARTUP_INSTRUCTIONS_FILE = ETC_DIR / 'startup_instructions.md'
GREPMESH_CONFIG_FILE = ETC_DIR / 'grepmesh.json'
STARTUP_INSTRUCTIONS_MAX_BYTES = 16 * 1024
MCP_CAPABILITY_CATALOG_VERSION = 'gptadmin-capabilities/v1'
# The private signing key is intentionally not part of GPTAdmin. This detached
# public key and signature authenticate the immutable catalog shipped in this
# release; changing a definition requires a deliberate release-time re-sign.
MCP_CAPABILITY_CATALOG_PUBLIC_KEY_B64 = 'em0_XbX6G5Tr8CSbH9EfQMFWUyHFHwyjYhs6JkCTl3s'
MCP_CAPABILITY_CATALOG_SIGNATURE_B64 = 'fMIkvEZ7uOq3L19onPa9JyYK9oef-B5-Go9_CmaHYO9a2MKRMTHmogA9D4bK5mfhqF3K6dOBXfOWcjNRFOUmDQ'
MCP_CAPABILITY_CATALOG = (
{
'id': 'gptadmin-safe-demo',
'version': '1.0.0',
'provenance': 'bundled:gptadmin-hub',
'scopes': ['gptadmin.read'],
'network_needs': [],
'risk_level': 'low',
'maintenance_owner': 'GPTAdmin',
'tools': ['demo'],
},
{
'id': 'gptadmin-readonly-inspection',
'version': '1.0.0',
'provenance': 'bundled:gptadmin-shellmcp',
'scopes': ['gptadmin.inspect'],
'network_needs': [],
'risk_level': 'medium',
'maintenance_owner': 'GPTAdmin',
'tools': ['system_inspect', 'inspect'],
},
{
'id': 'gptadmin-network-tunnel',
'version': '1.0.0',
'provenance': 'bundled:gptadmin-network-proxy',
'scopes': ['gptadmin.network'],
'network_needs': ['explicit finite LAN or internet-egress target policy'],
'risk_level': 'high',
'maintenance_owner': 'GPTAdmin',
'tools': ['network_proxy_request', 'network_proxy_issue'],
},
)
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_GREPMESH_LABEL = f'{SERVICE_PREFIX}.grepmesh'
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_GREPMESH = SERVICES_DIR / f'{SVC_GREPMESH_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_HUB_STANDBY = 'gptadmin-hub-standby.service'
SYSTEMD_SHELLMCP = 'shellmcp.service'
SYSTEMD_GREPMESH = 'gptadmin-grepmesh-mcp.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_HUB_STANDBY = SYSTEMD_DIR / SYSTEMD_HUB_STANDBY
UNIT_PATH_SHELLMCP = SYSTEMD_DIR / SYSTEMD_SHELLMCP
UNIT_PATH_GREPMESH = SYSTEMD_DIR / SYSTEMD_GREPMESH
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 = 'became.bezrabotnyi.com'
FRPC_SERVER_PORT_DEFAULT = '7000'
FRPC_TOKEN_DEFAULT = 'E10WCLE7ZFT+0NDgOFWwyPV8fb7hG7cLn320aHL0fVk='
FRPC_DOMAIN_DEFAULT = 't.became.bezrabotnyi.com'
FRPC_SERVER_ENDPOINTS_DEFAULT = os.environ.get(
'FRPC_SERVER_ENDPOINTS_DEFAULT',
'primary=became.bezrabotnyi.com:7000,server01=server01.bezrabotnyi.com:27001,server01=server01.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')
# gptadmin.env contains bearer/OAuth/admin secrets. Keep it private in
# both user and system installs; doctor deliberately rejects group-read.
os.chmod(tmp, 0o600)
os.replace(tmp, ENV_FILE)
finally:
tmp.unlink(missing_ok=True)
_PERSISTENT_AUTH_KEYS = frozenset({
'CTL_TOKEN',
'SHELLMCP_TOKEN',
'SHELL_TOKEN',
'ROOTD_TOKEN',
'ROOTD_UPDATE_TOKEN',
'ADMIN_PASSWORD',
'OAUTH_CLIENT_SECRET',
'MCP_BRIDGE_KEY',
'MCP_RELAY_AGENT_TOKEN',
'MCP_RELAY_ENROLLMENT_PASSWORD',
'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 normalize_bundled_shellmcp_hub_url(env: dict, install_hub: bool, install_shellmcp: bool) -> None:
"""Keep same-host ShellMCP on the local Hub even when public ingress fails over.
HUB_PUBLIC_URL/PUBLIC_ORIGIN/MCP_RESOURCE are the external identity. HUB_URL is
the durable transport used by ShellMCP. A bundled Hub+ShellMCP install must
never poll its own public failover URL: during a Hub handover that can point
at standby and strand jobs created on the restarted primary.
"""
if not (install_hub and install_shellmcp):
return
local_hub = f"http://127.0.0.1:{env.get('HUB_PORT') or '9001'}"
env['HUB_URL'] = local_hub
transport = str(env.get('SHELLMCP_TRANSPORT') or 'polling').strip().lower()
queue_enabled = str(env.get('SHELLMCP_QUEUE') or env.get('SHELL_QUEUE') or '1').strip().lower()
if transport in {'polling', 'long_poll', 'long-poll'} or queue_enabled in {'1', 'true', 'yes', 'on'}:
env['QUEUE_URL'] = local_hub + '/queue'
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] | str, *additional: str):
"""Atomically remove transient secret values from the persistent env file."""
if isinstance(keys, str):
keys = [keys, *additional]
else:
keys = [*keys, *additional]
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)
tmp = ENV_FILE.with_name(f'.{ENV_FILE.name}.{os.getpid()}.tmp')
try:
tmp.write_text('\n'.join(lines) + '\n', encoding='utf-8')
os.chmod(tmp, 0o600)
os.replace(tmp, ENV_FILE)
finally:
tmp.unlink(missing_ok=True)
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)
public_src = tdp / 'public'
admin_src = public_src / 'admin'
if admin_src.exists():
public_dst = INSTALL_DIR / 'public'
public_dst.mkdir(parents=True, exist_ok=True)
admin_dst = public_dst / 'admin'
staged_admin = public_dst / '.admin-react.new'
if staged_admin.exists():
shutil.rmtree(staged_admin, ignore_errors=True)
shutil.copytree(admin_src, staged_admin)
if admin_dst.exists():
shutil.rmtree(admin_dst, ignore_errors=True)
os.replace(staged_admin, admin_dst)
legacy_src = public_src / 'admin-legacy'
if legacy_src.exists():
legacy_dst = public_dst / 'admin-legacy'
staged_legacy = public_dst / '.admin-legacy.new'
if staged_legacy.exists():
shutil.rmtree(staged_legacy, ignore_errors=True)
shutil.copytree(legacy_src, staged_legacy)
if legacy_dst.exists():
shutil.rmtree(legacy_dst, ignore_errors=True)
os.replace(staged_legacy, legacy_dst)
for sibling in public_src.iterdir():
if sibling.name in {'admin', 'admin-legacy'}:
continue
target = public_dst / sibling.name
if sibling.is_dir():
staged = public_dst / f'.{sibling.name}.new'
if staged.exists():
shutil.rmtree(staged, ignore_errors=True)
shutil.copytree(sibling, staged)
if target.exists():
shutil.rmtree(target, ignore_errors=True)
os.replace(staged, target)
elif sibling.is_file():
shutil.copy2(sibling, target)
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 _release_platform_tag() -> str:
return 'macos' if IS_MACOS else 'ubuntu'
def _release_arch_tag() -> str:
arch = _arch_tag()
if arch == 'amd64':
return 'x64'
if arch == 'arm64':
return 'arm64'
return arch
def platform_pkg_url_default(edition: str = 'full') -> str:
if edition not in {'full', 'client'}:
raise ValueError(f'unsupported release edition: {edition}')
return os.environ.get(
'PKG_PLATFORM_URL',
f'{PKG_BASE_URL_DEFAULT}/gptadmin-{_release_platform_tag()}-{_release_arch_tag()}-{edition}.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 / 'bin' / 'gptadmin-hub'] + [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_runtime_binary(src: Path, dst: Path) -> None:
"""Install a runtime binary by atomic replacement.
Replacing the directory entry is safe while the old executable is running;
copying directly to ``dst`` is not (Linux returns ETXTBSY/Text file busy).
"""
dst.parent.mkdir(parents=True, exist_ok=True)
tmp_name = None
try:
with tempfile.NamedTemporaryFile(
dir=dst.parent, prefix=f'.{dst.name}.', suffix='.new', delete=False
) as tmp:
tmp_name = Path(tmp.name)
shutil.copy2(src, tmp_name)
os.chmod(tmp_name, 0o755)
os.replace(tmp_name, dst)
finally:
if tmp_name is not None:
tmp_name.unlink(missing_ok=True)
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'
_install_runtime_binary(c, dst)
_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] = [tdp / 'bin' / 'shellmcp']
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'
_install_runtime_binary(c, dst)
_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 _grepmesh_binary_candidates(tdp: Path) -> list[Path]:
arch = _arch_tag()
tags = [f'darwin_{arch}', f'macos_{arch}'] if IS_MACOS else [f'linux_{arch}']
out = [tdp / 'bin' / 'grepmesh-mcp', tdp / 'grepmesh-mcp']
for tag in tags:
out.extend([
tdp / 'grepmesh' / tag / 'grepmesh-mcp',
tdp / 'build' / 'grepmesh' / tag / 'grepmesh-mcp',
])
return out
def _install_grepmesh_binary_from_pkg(tdp: Path) -> bool:
"""Install the bundled GrepMesh binary when this platform package carries it.
GrepMesh is a default-on companion capability, but package portability remains
fail-open: older packages and unsupported cross-builds simply omit the binary.
Explicit --no-grepmesh controls activation, not package extraction.
"""
for candidate in _grepmesh_binary_candidates(tdp):
if candidate.exists() and candidate.is_file() and _binary_looks_native(candidate):
BIN_DIR.mkdir(parents=True, exist_ok=True)
dst = BIN_DIR / 'grepmesh-mcp'
_install_runtime_binary(candidate, dst)
_macos_unquarantine_and_codesign(dst)
return True
return False
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
if not IS_MACOS:
# Older Go-canary installs overrode both ExecStart and EnvironmentFile,
# leaving Hub and ShellMCP on different token sources after rotation.
# The canonical unit now reads only gptadmin.env; preserve unrelated
# drop-ins such as spool permissions and auto-update settings.
dropin_dir = SYSTEMD_DIR / f'{SYSTEMD_SHELLMCP}.d'
for obsolete_dropin in dropin_dir.glob('*go-primary*.conf'):
# Older installers used different numeric prefixes; any matching
# override can replace the canonical gptadmin.env credential.
obsolete_dropin.unlink(missing_ok=True)
# Older installs could pin ShellMCP itself to the operator account.
# The paired file:<host> target now needs a privileged filesystem boundary
# in system mode. ShellMCP therefore runs as root while shell_exec still
# defaults to SHELLMCP_DEFAULT_USER and only elevates when explicitly asked.
legacy_user_mode = dropin_dir / '100-gptadmin-user-mode.conf'
legacy_system_dropins = (
legacy_user_mode,
dropin_dir / '110-user-mode-no-self-update.conf',
dropin_dir / '120-config-dir-access.conf',
dropin_dir / 'zz-user-mode-no-self-update.conf',
)
if not IS_USER_INSTALL:
for legacy_dropin in legacy_system_dropins:
try:
legacy_dropin.unlink(missing_ok=True)
except OSError as exc:
print_warn(f'Could not retire legacy ShellMCP drop-in {legacy_dropin.name}: {exc}')
# Do not delete ad-hoc *.bak/*.old/*.new files here. They may be operator
# rollback artifacts unrelated to this update. Managed checkpoint/backup GC
# is explicit and scoped to its own store.
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)
_install_grepmesh_binary_from_pkg(tdp)
return
die(f'unknown component: {component}')
# ===== Service management =====
if IS_MACOS:
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'
script.write_text(
f'#!/bin/sh\n'
f'set -a; [ -f {ENV_FILE} ] && . {ENV_FILE}; set +a\n'
f'exec {bin_path}\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.
domains = _launchd_domains()
# 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.
for domain in domains:
_launchctl_capture(['launchctl', 'bootout', _launchd_service_target(label, domain)])
for domain in domains:
bootstrap = _launchctl_capture(['launchctl', 'bootstrap', domain, str(unit_path)])
if bootstrap.returncode != 0 and not _launchd_is_loaded(label):
_launchctl_capture(['launchctl', 'remove', label])
time.sleep(0.2)
_launchctl_capture(['launchctl', 'bootstrap', domain, str(unit_path)])
if _launchd_is_loaded(label):
break
_launchctl_capture(['launchctl', 'enable', _launchd_loaded_target(label) or _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_loaded_target(label) or _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 _launchd_domains() -> list[str]:
"""Return interactive and SSH launchd domains for a user install."""
primary = _launchd_domain()
if not IS_USER_INSTALL:
return [primary]