-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
2420 lines (2043 loc) · 83.2 KB
/
Copy pathmain.py
File metadata and controls
2420 lines (2043 loc) · 83.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
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
# script_manager_bot.py
# -*- coding: utf-8 -*-
"""
Telegram Script Manager Bot
Features:
- Manage Python scripts: upload/edit/run/stop/logs/env/autostart
- Apps from archives (.zip/.tar.gz/.tgz/.tar/.7z): auto-extract, detect requirements.txt,
detect entry point (main.py / single file / ask), each app gets its own isolated venv
- Apps from GitHub repos (optionally a subfolder): clone, detect same as above, plus a
Sync button to re-pull latest code and offer to install any new dependencies
- Script versioning: keep last 10 versions with timestamps + rollback menu (also for apps)
- Better /list and /menu with emojis and extra info
- /monitoring: CPU/MEM (and some optional stats) for running scripts (uses psutil if installed)
- pip installs are stored in requirements.txt and installed on manager startup
Env:
- BOT_TOKEN (required)
- OWNER_ID (required, int)
- DATA_DIR (optional, default: /data)
"""
import os
import sys
import json
import re
import shlex
import asyncio
import logging
import shutil
import tarfile
import zipfile
from pathlib import Path
from typing import Dict, Any, Optional, List, Tuple
from collections import deque
from datetime import datetime
from telegram import Update, InlineKeyboardMarkup, InlineKeyboardButton
from telegram.ext import (
Application,
CommandHandler,
MessageHandler,
CallbackQueryHandler,
ContextTypes,
filters,
)
# Optional monitoring dependency
try:
import psutil # type: ignore
except Exception:
psutil = None # type: ignore
# Paths
DATA_DIR = Path(os.getenv("DATA_DIR", "/data"))
SCRIPTS_DIR = DATA_DIR / "scripts"
LOGS_DIR = DATA_DIR / "logs"
VERSIONS_DIR = DATA_DIR / "versions"
META_FILE = DATA_DIR / "meta.json"
REQUIREMENTS_FILE = DATA_DIR / "requirements.txt"
# New: multi-file apps (from archives or GitHub repos), each with its own isolated venv
APPS_DIR = DATA_DIR / "apps"
APP_VERSIONS_DIR = DATA_DIR / "app_versions"
VENVS_DIR = DATA_DIR / "venvs"
GITREPOS_DIR = DATA_DIR / "gitrepos"
TMP_DIR = DATA_DIR / "tmp"
DATA_DIR.mkdir(parents=True, exist_ok=True)
SCRIPTS_DIR.mkdir(parents=True, exist_ok=True)
LOGS_DIR.mkdir(parents=True, exist_ok=True)
VERSIONS_DIR.mkdir(parents=True, exist_ok=True)
APPS_DIR.mkdir(parents=True, exist_ok=True)
APP_VERSIONS_DIR.mkdir(parents=True, exist_ok=True)
VENVS_DIR.mkdir(parents=True, exist_ok=True)
GITREPOS_DIR.mkdir(parents=True, exist_ok=True)
TMP_DIR.mkdir(parents=True, exist_ok=True)
# Directories to ignore when scanning a project for .py files / requirements.txt
IGNORED_PROJECT_DIRS = {
".git", "__pycache__", "venv", ".venv", "env", ".env", "node_modules",
".idea", ".vscode", ".mypy_cache", ".pytest_cache", "site-packages",
"dist", "build", ".github", "__MACOSX",
}
ARCHIVE_EXTENSIONS = (".tar.gz", ".tgz", ".tar", ".zip", ".7z")
GITHUB_TREE_URL_RE = re.compile(
r'^https?://github\.com/(?P<owner>[^/\s]+)/(?P<repo>[^/\s]+?)(?:\.git)?/tree/(?P<branch>[^/\s]+)/(?P<path>[^\s]+?)/?$'
)
GITHUB_REPO_URL_RE = re.compile(
r'^https?://github\.com/(?P<owner>[^/\s]+)/(?P<repo>[^/\s]+?)(?:\.git)?/?$'
)
# Logging
bot_log_path = DATA_DIR / "bot.log"
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
handlers=[
logging.StreamHandler(sys.stdout),
logging.FileHandler(str(bot_log_path), encoding="utf-8"),
],
)
logger = logging.getLogger("script-bot")
BOT_TOKEN = os.getenv("BOT_TOKEN")
OWNER_ID_ENV = os.getenv("OWNER_ID")
if not BOT_TOKEN:
raise RuntimeError("BOT_TOKEN env is required")
if not OWNER_ID_ENV:
raise RuntimeError("OWNER_ID env is required")
OWNER_ID = int(OWNER_ID_ENV)
# Telegram callback_data limit is 64 bytes-ish; keep it short
MAX_VERSIONS_PER_SCRIPT = 10
LOG_TAIL_LINES = 10
def is_authorized(update: Update) -> bool:
user = update.effective_user
ok = bool(user and user.id == OWNER_ID)
if not ok:
logger.warning("Unauthorized access attempt from user_id=%s", getattr(user, "id", None))
return ok
def now_ts_str() -> str:
# Example: 01.12.2025-12-25-09
return datetime.now().strftime("%d.%m.%Y-%H-%M-%S")
def pretty_dt_from_ts(ts: str) -> str:
# Accept "dd.mm.yyyy-HH-MM-SS"
try:
d = datetime.strptime(ts, "%d.%m.%Y-%H-%M-%S")
return d.strftime("%d.%m.%Y %H:%M:%S")
except Exception:
return ts
def safe_trim_text(text: str, limit: int = 3800) -> str:
# Telegram message hard limit is 4096; keep some headroom.
if len(text) <= limit:
return text
return "...\n" + text[-limit:]
def extract_env_keys(source: str) -> set[str]:
keys: set[str] = set()
pattern1 = r"(?:os\.)?(?:getenv|environ\.get)\(\s*['\"]([A-Za-z_][A-Za-z0-9_]*)['\"]"
pattern2 = r"(?:os\.)?environ\[\s*['\"]([A-Za-z_][A-Za-z0-9_]*)['\"]\s*\]"
for pat in (pattern1, pattern2):
for m in re.findall(pat, source):
keys.add(m)
return keys
def read_text_file(path: Path) -> str:
return path.read_text(encoding="utf-8", errors="replace")
def write_text_file_atomic(path: Path, content: str) -> None:
tmp = path.with_suffix(path.suffix + ".tmp")
tmp.write_text(content, encoding="utf-8")
tmp.replace(path)
def sanitize_id(name: str) -> str:
# Used only for NEW app ids (archives / github repos) - kept separate from the
# legacy script id derivation to not change behavior of existing scripts (BWC).
name = (name or "").strip().replace(" ", "_")
name = re.sub(r"[^A-Za-z0-9_.-]", "_", name)
name = name.strip("_.- ")
return name or "app"
def venv_python_path(venv_dir: Path) -> Path:
if os.name == "nt":
return venv_dir / "Scripts" / "python.exe"
return venv_dir / "bin" / "python"
async def create_venv(venv_dir: Path) -> Tuple[bool, str]:
py = venv_python_path(venv_dir)
if py.exists():
return True, "venv already exists"
venv_dir.parent.mkdir(parents=True, exist_ok=True)
logger.info("Creating venv at %s", venv_dir)
proc = await asyncio.create_subprocess_exec(
sys.executable,
"-m",
"venv",
"--system-site-packages",
str(venv_dir),
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.STDOUT,
)
out, _ = await proc.communicate()
text = out.decode("utf-8", errors="replace")
ok = proc.returncode == 0 and py.exists()
if not ok:
logger.error("venv creation failed for %s: %s", venv_dir, text)
return ok, text
def strip_archive_ext(filename: str) -> str:
lower = filename.lower()
for ext in ARCHIVE_EXTENSIONS:
if lower.endswith(ext):
return filename[: -len(ext)]
return Path(filename).stem
def archive_ext_of(filename: str) -> str:
# Path(filename).suffix would truncate ".tar.gz" down to ".gz" - keep the full
# multi-part extension so downstream extraction picks the correct code path.
lower = filename.lower()
for ext in ARCHIVE_EXTENSIONS:
if lower.endswith(ext):
return filename[len(filename) - len(ext):]
return Path(filename).suffix
def _validate_zip_members(zf: "zipfile.ZipFile", dest_dir: Path) -> None:
dest_resolved = dest_dir.resolve()
for name in zf.namelist():
target = (dest_dir / name).resolve()
if not str(target).startswith(str(dest_resolved)):
raise ValueError(f"Unsafe path in archive: {name}")
def _validate_tar_members(tf: "tarfile.TarFile", dest_dir: Path) -> None:
dest_resolved = dest_dir.resolve()
for member in tf.getmembers():
target = (dest_dir / member.name).resolve()
if not str(target).startswith(str(dest_resolved)):
raise ValueError(f"Unsafe path in archive: {member.name}")
def extract_archive(archive_path: Path, dest_dir: Path) -> None:
dest_dir.mkdir(parents=True, exist_ok=True)
lower = str(archive_path).lower()
if lower.endswith(".zip"):
with zipfile.ZipFile(archive_path) as zf:
_validate_zip_members(zf, dest_dir)
zf.extractall(dest_dir)
elif lower.endswith(".tar.gz") or lower.endswith(".tgz"):
with tarfile.open(archive_path, "r:gz") as tf:
_validate_tar_members(tf, dest_dir)
tf.extractall(dest_dir, filter="data")
elif lower.endswith(".tar"):
with tarfile.open(archive_path, "r:") as tf:
_validate_tar_members(tf, dest_dir)
tf.extractall(dest_dir, filter="data")
elif lower.endswith(".7z"):
try:
import py7zr # type: ignore
except ImportError as e:
raise RuntimeError("py7zr is not installed on the manager, cannot extract .7z archives") from e
with py7zr.SevenZipFile(archive_path, mode="r") as zf:
names = zf.getnames()
dest_resolved = dest_dir.resolve()
for name in names:
target = (dest_dir / name).resolve()
if not str(target).startswith(str(dest_resolved)):
raise ValueError(f"Unsafe path in archive: {name}")
zf.extractall(path=dest_dir)
else:
raise ValueError(f"Unsupported archive type: {archive_path.suffix}")
def find_extraction_root(staging: Path) -> Path:
# Many archives (e.g. GitHub zip exports) wrap everything in one top-level folder.
entries = [p for p in staging.iterdir() if p.name not in IGNORED_PROJECT_DIRS]
if len(entries) == 1 and entries[0].is_dir():
return entries[0]
return staging
def discover_python_files(root: Path) -> List[str]:
result: List[str] = []
root = root.resolve()
for dirpath, dirnames, filenames in os.walk(root):
dirnames[:] = [d for d in dirnames if d not in IGNORED_PROJECT_DIRS and not d.startswith(".")]
for fn in filenames:
if fn.lower().endswith(".py"):
rel = str(Path(dirpath, fn).relative_to(root)).replace("\\", "/")
result.append(rel)
result.sort()
return result
def find_requirements_file(root: Path) -> Optional[Path]:
direct = root / "requirements.txt"
if direct.exists():
return direct
for dirpath, dirnames, filenames in os.walk(root):
dirnames[:] = [d for d in dirnames if d not in IGNORED_PROJECT_DIRS and not d.startswith(".")]
for fn in filenames:
if fn.lower() == "requirements.txt":
return Path(dirpath) / fn
return None
def find_requirements_pkgs(root: Path) -> List[str]:
req = find_requirements_file(root)
if not req:
return []
try:
return [
line.strip()
for line in read_text_file(req).splitlines()
if line.strip() and not line.strip().startswith("#")
]
except Exception:
return []
def pick_entry_from_candidates(py_files: List[str]) -> Tuple[Optional[str], bool]:
"""Returns (entry_or_None, ambiguous)."""
mains = [f for f in py_files if Path(f).name.lower() == "main.py"]
if mains:
mains.sort(key=lambda p: p.count("/"))
return mains[0], False
if len(py_files) == 1:
return py_files[0], False
if len(py_files) == 0:
return None, False
return None, True
def parse_github_url(text: str) -> Optional[Dict[str, Any]]:
url = (text or "").strip()
m = GITHUB_TREE_URL_RE.match(url)
if m:
owner, repo, branch, path = m.group("owner"), m.group("repo"), m.group("branch"), m.group("path")
folder = path.rstrip("/").split("/")[-1]
app_id = sanitize_id(f"{repo}-{folder}")
return {"owner": owner, "repo": repo, "branch": branch, "path": path, "app_id": app_id}
m = GITHUB_REPO_URL_RE.match(url)
if m:
owner, repo = m.group("owner"), m.group("repo")
app_id = sanitize_id(repo)
return {"owner": owner, "repo": repo, "branch": None, "path": None, "app_id": app_id}
return None
async def _run_cmd(*args: str) -> Tuple[bool, str]:
proc = await asyncio.create_subprocess_exec(
*args,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.STDOUT,
)
out, _ = await proc.communicate()
text = out.decode("utf-8", errors="replace")
return proc.returncode == 0, text
async def git_clone_or_pull(repo_url: str, branch: Optional[str], dest: Path) -> Tuple[bool, str]:
if (dest / ".git").exists():
ok, out1 = await _run_cmd("git", "-C", str(dest), "fetch", "--depth", "1", "origin", branch or "HEAD")
if not ok:
return False, out1
target = f"origin/{branch}" if branch else "FETCH_HEAD"
ok, out2 = await _run_cmd("git", "-C", str(dest), "reset", "--hard", target)
return ok, out1 + "\n" + out2
# Clean up any partial/failed previous clone attempt so `git clone` doesn't
# refuse to write into a non-empty directory.
if dest.exists():
shutil.rmtree(dest, ignore_errors=True)
dest.parent.mkdir(parents=True, exist_ok=True)
cmd = ["git", "clone", "--depth", "1"]
if branch:
cmd += ["--branch", branch]
cmd += [repo_url, str(dest)]
return await _run_cmd(*cmd)
async def git_current_branch(repo_dir: Path) -> str:
ok, out = await _run_cmd("git", "-C", str(repo_dir), "rev-parse", "--abbrev-ref", "HEAD")
if ok:
branch = out.strip()
if branch and branch != "HEAD":
return branch
return "main"
class ScriptManager:
def __init__(self) -> None:
self.meta: Dict[str, Any] = {"global_env": {}, "scripts": {}}
# runtime state
self.processes: Dict[str, asyncio.subprocess.Process] = {}
self.log_handles: Dict[str, Any] = {} # file handles
self.watch_tasks: Dict[str, asyncio.Task] = {}
self.start_times: Dict[str, float] = {} # monotonic-ish not required; store epoch
self.psutil_procs: Dict[str, Any] = {} # psutil.Process objects
# pending user flows
self.pending_new: Dict[int, str] = {}
self.pending_edit: Dict[int, str] = {}
self.pending_env_value: Dict[int, Dict[str, str]] = {}
self.pending_pip: Dict[int, Optional[str]] = {}
self.pending_entry_choice: Dict[str, List[str]] = {} # app_id -> candidate py files
self.load_meta()
def load_meta(self) -> None:
if META_FILE.exists():
try:
self.meta = json.loads(read_text_file(META_FILE))
except Exception:
logger.exception("Failed to load meta.json, starting with empty meta")
self.meta = {"global_env": {}, "scripts": {}}
# Ensure structure
self.meta.setdefault("global_env", {})
self.meta.setdefault("scripts", {})
# Ensure per-script keys
for sid, s in self.meta["scripts"].items():
if not isinstance(s, dict):
self.meta["scripts"][sid] = {}
s = self.meta["scripts"][sid]
s.setdefault("env", {})
s.setdefault("autostart", False)
s.setdefault("versions", []) # list[{ts, file}]
s.setdefault("updated_at", None)
s.setdefault("type", "script") # "script" (legacy .py) | "project" (archive) | "git"
self.save_meta()
def save_meta(self) -> None:
try:
write_text_file_atomic(META_FILE, json.dumps(self.meta, indent=2, ensure_ascii=False))
except Exception:
logger.exception("Failed to save meta.json")
def list_scripts(self) -> Dict[str, Any]:
return self.meta.get("scripts", {})
def get_global_env(self) -> Dict[str, str]:
return self.meta.get("global_env", {})
def set_global_env(self, key: str, value: str) -> None:
self.meta.setdefault("global_env", {})[key] = value
self.save_meta()
logger.info("Set global env %s", key)
def del_global_env(self, key: str) -> bool:
env = self.meta.setdefault("global_env", {})
existed = key in env
env.pop(key, None)
self.save_meta()
if existed:
logger.info("Deleted global env %s", key)
return existed
# requirements.txt handling
def _read_requirements_lines(self, path: Optional[Path] = None) -> List[str]:
p = path or REQUIREMENTS_FILE
if not p.exists():
return []
lines = []
for raw in read_text_file(p).splitlines():
line = raw.strip()
if not line or line.startswith("#"):
continue
lines.append(line)
return lines
def add_requirements(self, pkgs: List[str], path: Optional[Path] = None) -> bool:
if not pkgs:
return False
p = path or REQUIREMENTS_FILE
existing = self._read_requirements_lines(p)
existing_set = set(existing)
changed = False
for pkg in pkgs:
if pkg and pkg not in existing_set:
existing.append(pkg)
existing_set.add(pkg)
changed = True
if changed:
content = "\n".join(existing) + "\n"
write_text_file_atomic(p, content)
return changed
async def ensure_requirements_installed(self) -> None:
# Backward compatibility: migrate old meta pip_packages -> requirements.txt (if present)
old_pkgs = self.meta.get("pip_packages")
if isinstance(old_pkgs, list) and old_pkgs:
migrated = [str(x).strip() for x in old_pkgs if str(x).strip()]
if migrated:
self.add_requirements(migrated)
# keep meta key but stop using it
logger.info("Migrated meta pip_packages to requirements.txt (%d items)", len(migrated))
if not REQUIREMENTS_FILE.exists():
logger.info("No requirements.txt, skipping startup pip install")
return
req_lines = self._read_requirements_lines()
if not req_lines:
logger.info("requirements.txt is empty, skipping startup pip install")
return
logger.info("Ensuring requirements installed on startup: %s", str(REQUIREMENTS_FILE))
proc = await asyncio.create_subprocess_exec(
sys.executable,
"-m",
"pip",
"install",
"-r",
str(REQUIREMENTS_FILE),
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.STDOUT,
)
out, _ = await proc.communicate()
text = out.decode("utf-8", errors="replace")
text = safe_trim_text(text, 3500)
logger.info("Startup pip install exit=%s, output:\n%s", proc.returncode, text)
async def ensure_app_environments(self) -> None:
# Make sure every project/git app has a working venv + its deps installed,
# e.g. after a fresh volume or container rebuild.
scripts = self.meta.get("scripts", {})
for sid, s in list(scripts.items()):
if not isinstance(s, dict) or s.get("type") not in ("project", "git"):
continue
root = Path(s.get("root_dir") or "")
if not root.exists():
logger.warning("App %s root_dir missing (%s), skipping env setup", sid, root)
continue
venv_dir = Path(s.get("venv_dir") or self.app_venv_dir(sid))
ok, out = await create_venv(venv_dir)
if not ok:
logger.error("Failed to prepare venv for app %s: %s", sid, safe_trim_text(out, 1000))
continue
req_file = root / "requirements.txt"
if req_file.exists():
python_exe = venv_python_path(venv_dir)
proc = await asyncio.create_subprocess_exec(
str(python_exe),
"-m",
"pip",
"install",
"-r",
str(req_file),
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.STDOUT,
)
out2, _ = await proc.communicate()
logger.info(
"Startup pip install for app %s exit=%s:\n%s",
sid,
proc.returncode,
safe_trim_text(out2.decode("utf-8", errors="replace"), 2000),
)
# scripts
def _ensure_script_meta(self, script_id: str, file_path: str) -> None:
scripts = self.meta.setdefault("scripts", {})
script = scripts.get(script_id, {})
if not isinstance(script, dict):
script = {}
script.setdefault("env", {})
script.setdefault("autostart", False)
script.setdefault("versions", [])
script.setdefault("updated_at", None)
script["type"] = "script"
script["file"] = file_path
scripts[script_id] = script
self.save_meta()
def get_script(self, script_id: str) -> Optional[Dict[str, Any]]:
return self.meta.get("scripts", {}).get(script_id)
def get_type(self, script_id: str) -> str:
s = self.get_script(script_id)
return (s or {}).get("type", "script")
def is_project_type(self, script_id: str) -> bool:
return self.get_type(script_id) in ("project", "git")
def script_file_path(self, script_id: str) -> Path:
return SCRIPTS_DIR / f"{script_id}.py"
def versions_dir_for(self, script_id: str) -> Path:
d = VERSIONS_DIR / script_id
d.mkdir(parents=True, exist_ok=True)
return d
# apps (archives / github repos) - each gets its own root dir + isolated venv
def app_root_dir(self, script_id: str) -> Path:
return APPS_DIR / script_id
def app_venv_dir(self, script_id: str) -> Path:
return VENVS_DIR / script_id
def app_venv_python(self, script_id: str) -> Path:
return venv_python_path(self.app_venv_dir(script_id))
def app_versions_dir_for(self, script_id: str) -> Path:
d = APP_VERSIONS_DIR / script_id
d.mkdir(parents=True, exist_ok=True)
return d
def app_requirements_file(self, script_id: str) -> Optional[Path]:
script = self.get_script(script_id)
if not script:
return None
root = Path(script.get("root_dir") or "")
if not root.exists():
return None
return root / "requirements.txt"
def _ensure_app_meta(
self,
script_id: str,
app_type: str,
root_dir: Path,
entry: Optional[str],
venv_dir: Path,
git_info: Optional[Dict[str, Any]] = None,
) -> None:
scripts = self.meta.setdefault("scripts", {})
script = scripts.get(script_id, {})
if not isinstance(script, dict):
script = {}
script.setdefault("env", {})
script.setdefault("autostart", False)
script.setdefault("versions", [])
script.setdefault("updated_at", None)
script["type"] = app_type
script["root_dir"] = str(root_dir)
script["entry"] = entry
script["venv_dir"] = str(venv_dir)
if git_info is not None:
script["git"] = git_info
scripts[script_id] = script
self.save_meta()
async def setup_project_app(
self,
script_id: str,
extracted_root: Path,
app_type: str,
git_info: Optional[Dict[str, Any]] = None,
) -> Dict[str, Any]:
"""Moves extracted_root -> APPS_DIR/script_id (snapshotting previous content if any),
prepares an isolated venv, and detects the entry point + requirements."""
dest_root = self.app_root_dir(script_id)
existing = self.get_script(script_id)
if existing:
if existing.get("type", "script") == "script":
self.snapshot_current_version(script_id)
else:
self.snapshot_current_app_version(script_id)
if dest_root.exists():
shutil.rmtree(dest_root, ignore_errors=True)
dest_root.parent.mkdir(parents=True, exist_ok=True)
shutil.move(str(extracted_root), str(dest_root))
py_files = discover_python_files(dest_root)
entry, ambiguous = pick_entry_from_candidates(py_files)
venv_dir = self.app_venv_dir(script_id)
venv_ok, venv_out = await create_venv(venv_dir)
self._ensure_app_meta(script_id, app_type, dest_root, entry, venv_dir, git_info)
script = self.get_script(script_id)
if script:
script["updated_at"] = now_ts_str()
self.save_meta()
logger.info("App %s set up (type=%s, entry=%s, ambiguous=%s)", script_id, app_type, entry, ambiguous)
result: Dict[str, Any] = {
"app_id": script_id,
"venv_ok": venv_ok,
"venv_out": venv_out,
"requirements_pkgs": find_requirements_pkgs(dest_root),
"py_files": py_files,
}
if ambiguous:
self.pending_entry_choice[script_id] = py_files
result["status"] = "ambiguous"
result["candidates"] = py_files
else:
result["status"] = "ready"
result["entry"] = entry
return result
async def install_app_requirements(self, script_id: str) -> str:
script = self.get_script(script_id)
if not script:
return "❌ App not found."
root = Path(script.get("root_dir") or "")
req_file = root / "requirements.txt"
if not req_file.exists():
return "🟡 No requirements.txt found."
venv_dir = Path(script.get("venv_dir") or self.app_venv_dir(script_id))
python_exe = venv_python_path(venv_dir)
if not python_exe.exists():
ok, out = await create_venv(venv_dir)
if not ok:
return "❌ Failed to prepare venv:\n" + safe_trim_text(out, 1500)
proc = await asyncio.create_subprocess_exec(
str(python_exe),
"-m",
"pip",
"install",
"-r",
str(req_file),
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.STDOUT,
)
out, _ = await proc.communicate()
text = safe_trim_text(out.decode("utf-8", errors="replace"), 3200)
return f"📥 pip install -r requirements.txt (exit={proc.returncode})\n{text}"
def _push_version(self, script_id: str, version_file: Path, ts: str) -> None:
script = self.get_script(script_id)
if not script:
return
versions = script.setdefault("versions", [])
if not isinstance(versions, list):
versions = []
script["versions"] = versions
versions.insert(0, {"ts": ts, "file": str(version_file)})
# Trim versions list and delete old files
while len(versions) > MAX_VERSIONS_PER_SCRIPT:
tail = versions.pop()
try:
fp = Path(tail.get("file", ""))
if fp.exists():
fp.unlink()
except Exception:
logger.exception("Failed to delete old version file for %s", script_id)
self.save_meta()
@staticmethod
def _unique_version_path(vdir: Path, script_id: str, ts: str, ext: str) -> Path:
# now_ts_str() has 1-second resolution, so two snapshots taken in quick
# succession (rapid edits, or a snapshot-before-rollback right after a
# snapshot-on-upload) can land on the same name. Never reuse a version
# file name - that would silently overwrite a still-referenced version.
candidate = vdir / f"{script_id}_{ts}{ext}"
n = 1
while candidate.exists():
candidate = vdir / f"{script_id}_{ts}_{n}{ext}"
n += 1
return candidate
def snapshot_current_version(self, script_id: str) -> None:
script = self.get_script(script_id)
if not script:
return
current = script.get("file")
if not current:
return
cur_path = Path(current)
if not cur_path.exists():
return
ts = now_ts_str()
vdir = self.versions_dir_for(script_id)
version_file = self._unique_version_path(vdir, script_id, ts, ".py")
try:
shutil.copy2(cur_path, version_file)
self._push_version(script_id, version_file, ts)
logger.info("Snapshot version for %s -> %s", script_id, version_file.name)
except Exception:
logger.exception("Failed to snapshot version for %s", script_id)
def snapshot_current_app_version(self, script_id: str) -> None:
script = self.get_script(script_id)
if not script:
return
root = Path(script.get("root_dir") or "")
if not root.exists():
return
ts = now_ts_str()
vdir = self.app_versions_dir_for(script_id)
version_file = self._unique_version_path(vdir, script_id, ts, ".tar.gz")
try:
with tarfile.open(version_file, "w:gz") as tf:
tf.add(root, arcname=script_id)
self._push_version(script_id, version_file, ts)
logger.info("Snapshot app version for %s -> %s", script_id, version_file.name)
except Exception:
logger.exception("Failed to snapshot app version for %s", script_id)
def upsert_script_from_text(self, name: str, content: str) -> str:
script_id = name.strip().replace(" ", "_")
if not script_id:
raise ValueError("empty script name")
# If script already exists, snapshot before overwriting
if self.get_script(script_id) and self.script_file_path(script_id).exists():
self.snapshot_current_version(script_id)
file_path = self.script_file_path(script_id)
write_text_file_atomic(file_path, content)
self._ensure_script_meta(script_id, str(file_path))
# Update updated_at
script = self.get_script(script_id)
if script:
script["updated_at"] = now_ts_str()
self.save_meta()
logger.info("Script %s saved from text", script_id)
return script_id
def upsert_script_from_file(self, original_name: str, content_path: Path) -> str:
stem = Path(original_name).stem
script_id = stem.strip().replace(" ", "_")
if not script_id:
script_id = f"script_{len(self.meta.get('scripts', {})) + 1}"
# Snapshot before overwriting
if self.get_script(script_id) and self.script_file_path(script_id).exists():
self.snapshot_current_version(script_id)
content = read_text_file(content_path)
file_path = self.script_file_path(script_id)
write_text_file_atomic(file_path, content)
self._ensure_script_meta(script_id, str(file_path))
script = self.get_script(script_id)
if script:
script["updated_at"] = now_ts_str()
self.save_meta()
logger.info("Script %s saved from file %s", script_id, original_name)
return script_id
def set_script_env(self, script_id: str, key: str, value: str) -> None:
scripts = self.meta.setdefault("scripts", {})
script = scripts.setdefault(script_id, {"env": {}, "autostart": False, "versions": [], "updated_at": None})
env = script.setdefault("env", {})
env[key] = value
self.save_meta()
logger.info("Set env %s for script %s", key, script_id)
def del_script_env(self, script_id: str, key: str) -> bool:
script = self.get_script(script_id)
if not script:
return False
env = script.setdefault("env", {})
existed = key in env
env.pop(key, None)
self.save_meta()
if existed:
logger.info("Deleted env %s for script %s", key, script_id)
return existed
def set_autostart(self, script_id: str, value: bool) -> bool:
script = self.get_script(script_id)
if not script:
return False
script["autostart"] = bool(value)
self.save_meta()
logger.info("Set autostart=%s for script %s", value, script_id)
return True
def script_running(self, script_id: str) -> bool:
proc = self.processes.get(script_id)
return bool(proc and proc.returncode is None)
def log_path(self, script_id: str) -> Path:
return LOGS_DIR / f"{script_id}.log"
async def _watch_process(self, script_id: str, proc: asyncio.subprocess.Process) -> None:
try:
await proc.wait()
except Exception:
logger.exception("Wait failed for %s", script_id)
finally:
# Mark stop in logs
try:
with self.log_path(script_id).open("ab") as f:
f.write(b"\n=== FINISHED ===\n")
except Exception:
logger.exception("Failed to write FINISHED marker for %s", script_id)
# Close handle
h = self.log_handles.pop(script_id, None)
try:
if h:
h.flush()
h.close()
except Exception:
pass
# Cleanup runtime
self.processes.pop(script_id, None)
self.psutil_procs.pop(script_id, None)
self.start_times.pop(script_id, None)
self.watch_tasks.pop(script_id, None)
logger.info("Process finished for %s (code=%s)", script_id, proc.returncode)
async def start_script(self, script_id: str) -> str:
script = self.get_script(script_id)
if not script:
return "❌ Script not found."
proc = self.processes.get(script_id)
if proc and proc.returncode is None:
return "🟡 Already running."
app_type = script.get("type", "script")
if app_type == "script":
file_path = script.get("file")
if not file_path or not Path(file_path).exists():
return "❌ Script file not found."
python_exe = sys.executable
cwd = str(SCRIPTS_DIR)
run_target = file_path
else:
root = Path(script.get("root_dir") or "")
entry = script.get("entry")
if not entry:
return "❌ Entry point not set. Choose a file to run first."
entry_path = root / entry
if not entry_path.exists():
return f"❌ Entry file not found: {entry}"
venv_dir = Path(script.get("venv_dir") or self.app_venv_dir(script_id))
python_exe_path = venv_python_path(venv_dir)
if not python_exe_path.exists():
ok, out = await create_venv(venv_dir)
if not ok:
return "❌ Failed to create venv:\n" + safe_trim_text(out, 1500)
python_exe = str(python_exe_path)
cwd = str(root)
run_target = str(entry_path)
env = os.environ.copy()
env.update(self.meta.get("global_env", {}))
env.update(script.get("env", {}))
log_file = self.log_path(script_id)
log_file.parent.mkdir(parents=True, exist_ok=True)
with log_file.open("ab") as f:
f.write(b"\n=== START ===\n")
# Keep handle open while process runs (important!)
h = log_file.open("ab")
self.log_handles[script_id] = h
logger.info("Starting script %s via %s", script_id, python_exe)
proc = await asyncio.create_subprocess_exec(
python_exe,
run_target,
cwd=cwd,
env=env,
stdout=h,
stderr=h,
)
self.processes[script_id] = proc
self.start_times[script_id] = datetime.now().timestamp()
# Prime psutil cpu% calculation
if psutil is not None:
try:
p = psutil.Process(proc.pid)
p.cpu_percent(interval=None)
self.psutil_procs[script_id] = p
except Exception:
pass
# Watcher
self.watch_tasks[script_id] = asyncio.create_task(self._watch_process(script_id, proc))
return f"✅ Started *{script_id}* (PID `{proc.pid}`)".replace("*", "")
async def stop_script(self, script_id: str) -> str:
proc = self.processes.get(script_id)
if not proc:
return "🟡 Not running."
if proc.returncode is not None:
self.processes.pop(script_id, None)
return "🟡 Already finished."