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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
"""
EchoNet server - a GitHub-backed "VPS" shell you connect to over WebSocket.

Env vars (set these in Render's dashboard):
    GITHUB_TOKEN     - a GitHub personal access token with repo access
    GITHUB_REPO      - e.g. "Tenoco/EchoNet"
    GITHUB_BRANCH    - defaults to "main"
    SHELL_PASSWORD   - the password echonetshell.py must send to connect
"""

import os
import io
import json
import base64
import shutil
import shlex
import signal
import socket
import subprocess
import threading
import collections
import time
import uuid
import hashlib

import requests
from flask import Flask, request, Response
from flask_sock import Sock

import gradio as gr
import spaces


@spaces.GPU
def _zerogpu_probe_fn(x):
    # Never called by anything real - exists only so the ZeroGPU scanner
    # finds an actual Gradio component wired to a @spaces.GPU function.
    # This app is plain CPU/Flask; the GPU is never touched.
    return x


def _launch_zerogpu_probe_app():
    with gr.Blocks() as _probe_demo:
        _inp = gr.Textbox(visible=False)
        _out = gr.Textbox(visible=False)
        _inp.change(_zerogpu_probe_fn, _inp, _out)
    # Separate port from the main Flask/websocket server (7860), and
    # non-blocking so it doesn't take over the main thread.
    _probe_demo.launch(
        server_name="0.0.0.0",
        server_port=int(os.environ.get("GRADIO_PROBE_PORT", 7864)),
        prevent_thread_lock=True,
        quiet=True,
    )


_launch_zerogpu_probe_app()

# ---------------------------------------------------------------------------
# Config
# ---------------------------------------------------------------------------

GITHUB_TOKEN = os.environ.get("GITHUB_TOKEN", "")
GITHUB_REPO = os.environ.get("GITHUB_REPO", "Tenoco/EchoNet")
GITHUB_BRANCH = os.environ.get("GITHUB_BRANCH", "main")
SHELL_PASSWORD = os.environ.get("SHELL_PASSWORD", "tenoco123!")

GH_API = f"https://api.github.com/repos/{GITHUB_REPO}/contents"
GH_HEADERS = {
    "Authorization": f"token {GITHUB_TOKEN}",
    "Accept": "application/vnd.github+json",
}

WORKDIR = "/tmp/echonet_apps"
os.makedirs(WORKDIR, exist_ok=True)

BASH_WORKDIR = os.path.join(WORKDIR, "_bash")
os.makedirs(BASH_WORKDIR, exist_ok=True)

RESERVED_ROUTES = {"shell", "", "healthz"}

GH_STATE_PATH = ".echonet_state.json"


# ---------------------------------------------------------------------------
# System stats (RAM, CPU vs Render's quota, GitHub repo size)
# ---------------------------------------------------------------------------

def get_ram_stats():
    """Returns (total_mb, used_mb) scoped to this container, not the host.
    /proc/meminfo reports the underlying host's physical memory (which on
    Render's shared infra can be tens of GB) - the real 512MB-style limit
    only shows up via the cgroup. We read that first and fall back to
    /proc/meminfo only if cgroup info isn't available (e.g. running locally,
    outside a container)."""
    # cgroup v2
    try:
        with open("/sys/fs/cgroup/memory.max") as f:
            max_raw = f.read().strip()
        with open("/sys/fs/cgroup/memory.current") as f:
            current = int(f.read().strip())
        if max_raw != "max":
            total = int(max_raw)
            return round(total / 1024 / 1024, 1), round(current / 1024 / 1024, 1)
    except Exception:
        pass

    # cgroup v1
    try:
        with open("/sys/fs/cgroup/memory/memory.limit_in_bytes") as f:
            total = int(f.read().strip())
        with open("/sys/fs/cgroup/memory/memory.usage_in_bytes") as f:
            current = int(f.read().strip())
        if total < (1 << 62):  # sentinel value for "unlimited" on some systems
            return round(total / 1024 / 1024, 1), round(current / 1024 / 1024, 1)
    except Exception:
        pass

    # fallback: host-level /proc/meminfo (only reached outside a container)
    try:
        info = {}
        with open("/proc/meminfo") as f:
            for line in f:
                parts = line.split(":")
                if len(parts) == 2:
                    info[parts[0].strip()] = int(parts[1].strip().split()[0])  # kB
        total_kb = info.get("MemTotal", 0)
        avail_kb = info.get("MemAvailable", info.get("MemFree", 0))
        used_kb = max(total_kb - avail_kb, 0)
        return round(total_kb / 1024, 1), round(used_kb / 1024, 1)
    except Exception:
        return None, None


def _read_cgroup_cpu_limit():
    """Returns CPU limit in cores, e.g. 0.15, or None if not determinable."""
    try:
        # cgroup v2
        with open("/sys/fs/cgroup/cpu.max") as f:
            quota, period = f.read().split()
            if quota == "max":
                return None
            return round(int(quota) / int(period), 3)
    except Exception:
        pass
    try:
        # cgroup v1
        with open("/sys/fs/cgroup/cpu/cpu.cfs_quota_us") as f:
            quota = int(f.read().strip())
        with open("/sys/fs/cgroup/cpu/cpu.cfs_period_us") as f:
            period = int(f.read().strip())
        if quota <= 0:
            return None
        return round(quota / period, 3)
    except Exception:
        return None


def _read_cgroup_cpu_usage_usec():
    try:
        # cgroup v2
        with open("/sys/fs/cgroup/cpu.stat") as f:
            for line in f:
                if line.startswith("usage_usec"):
                    return int(line.split()[1])
    except Exception:
        pass
    try:
        # cgroup v1 (nanoseconds)
        with open("/sys/fs/cgroup/cpuacct/cpuacct.usage") as f:
            return int(f.read().strip()) / 1000  # ns -> us
    except Exception:
        return None


def get_cpu_stats(sample_seconds=0.25):
    """Returns (limit_cores_or_None, used_percent_of_limit_or_None)."""
    limit = _read_cgroup_cpu_limit()
    u0 = _read_cgroup_cpu_usage_usec()
    if u0 is None:
        # fall back to load average as a rough proxy
        try:
            load1, _, _ = os.getloadavg()
            cores = os.cpu_count() or 1
            return cores, round(min(load1 / cores, 1.0) * 100, 1)
        except Exception:
            return None, None
    time.sleep(sample_seconds)
    u1 = _read_cgroup_cpu_usage_usec()
    if u1 is None or limit is None:
        return limit, None
    delta_cores_used = (u1 - u0) / 1_000_000 / sample_seconds
    percent = round(min(delta_cores_used / limit, 1.0) * 100, 1) if limit else None
    return limit, percent


def get_github_storage():
    """Returns (used_mb, limit_description)."""
    try:
        r = requests.get(f"https://api.github.com/repos/{GITHUB_REPO}", headers=GH_HEADERS)
        r.raise_for_status()
        size_kb = r.json().get("size", 0)
        return round(size_kb / 1024, 2), "no hard cap (~5GB soft limit)"
    except Exception:
        return None, "unknown"


def get_full_stats():
    ram_total, ram_used = get_ram_stats()
    cpu_limit, cpu_used_pct = get_cpu_stats()
    gh_used, gh_limit = get_github_storage()
    with HOSTED_LOCK:
        apps_running = len(HOSTED)
    return {
        "ram_total_mb": ram_total,
        "ram_used_mb": ram_used,
        "cpu_limit_cores": cpu_limit,
        "cpu_used_percent": cpu_used_pct,
        "github_used_mb": gh_used,
        "github_limit": gh_limit,
        "apps_running": apps_running,
    }

app = Flask(__name__)
sock = Sock(app)

# ---------------------------------------------------------------------------
# GitHub-backed filesystem helpers
# ---------------------------------------------------------------------------

def gh_path(cwd, name=""):
    parts = [p for p in (cwd + "/" + name).split("/") if p]
    return "/".join(parts)


def resolve_user_path(cwd, raw):
    """Resolve a path argument typed by the user. This 'filesystem' is just
    a GitHub repo, so there's no real home directory - '~' and '~/x' are
    treated as shorthand for the repo root, so paths like
    '~/tenoco/tenocoservices/nexfund/nexfund.py' work no matter what
    directory you're currently in."""
    if raw is None:
        return cwd
    if raw == "~":
        return ""
    if raw.startswith("~/"):
        return gh_path("", raw[2:])
    return gh_path(cwd, raw)


def gh_list(path):
    """List a directory. Returns list of {'name','type'} or raises."""
    url = f"{GH_API}/{path}" if path else GH_API
    r = requests.get(url, headers=GH_HEADERS, params={"ref": GITHUB_BRANCH})
    if r.status_code == 404:
        return None
    r.raise_for_status()
    data = r.json()
    if isinstance(data, dict):
        # it's a file, not a dir
        return None
    return [{"name": item["name"], "type": item["type"]} for item in data]


def gh_get_file(path):
    """Returns (content_bytes, sha) or (None, None) if missing."""
    url = f"{GH_API}/{path}"
    r = requests.get(url, headers=GH_HEADERS, params={"ref": GITHUB_BRANCH})
    if r.status_code == 404:
        return None, None
    r.raise_for_status()
    data = r.json()
    if not isinstance(data, dict):
        # It's a directory listing, not a file - nothing to return.
        return None, None
    content = base64.b64decode(data["content"])
    return content, data["sha"]


def gh_put_file(path, content_bytes, message):
    _, sha = gh_get_file(path)
    url = f"{GH_API}/{path}"
    payload = {
        "message": message,
        "content": base64.b64encode(content_bytes).decode(),
        "branch": GITHUB_BRANCH,
    }
    if sha:
        payload["sha"] = sha
    r = requests.put(url, headers=GH_HEADERS, json=payload)
    r.raise_for_status()
    return r.json()


def gh_delete_file(path, message):
    _, sha = gh_get_file(path)
    if not sha:
        return False
    url = f"{GH_API}/{path}"
    r = requests.delete(
        url,
        headers=GH_HEADERS,
        json={"message": message, "sha": sha, "branch": GITHUB_BRANCH},
    )
    # Handle 409 Conflict by refetching and retrying once
    if r.status_code == 409:
        _, sha = gh_get_file(path)
        if not sha:
            return False
        r = requests.delete(
            url,
            headers=GH_HEADERS,
            json={"message": message, "sha": sha, "branch": GITHUB_BRANCH},
        )
    r.raise_for_status()
    return True


def gh_delete_dir(path, message):
    entries = gh_list(path)
    if entries is None:
        return False
    for e in entries:
        sub = f"{path}/{e['name']}" if path else e["name"]
        try:
            if e["type"] == "dir":
                gh_delete_dir(sub, message)
            else:
                gh_delete_file(sub, message)
        except Exception:
            # Continue deleting other files even if one fails
            pass
    return True


def gh_mkdir(path):
    # GitHub has no real directories - create a .gitkeep placeholder
    keep = f"{path}/.gitkeep" if path else ".gitkeep"
    gh_put_file(keep, b"", f"mkdir {path}")


# ---------------------------------------------------------------------------
# Persisted "should be running" state - so hosted apps survive restarts
# ---------------------------------------------------------------------------

STATE_LOCK = threading.Lock()


def load_hosted_state():
    try:
        content, _ = gh_get_file(GH_STATE_PATH)
        if content is None:
            return {"hosted": []}
        return json.loads(content)
    except Exception:
        return {"hosted": []}


def save_hosted_state(entries):
    with STATE_LOCK:
        gh_put_file(
            GH_STATE_PATH,
            json.dumps({"hosted": entries}, indent=2).encode(),
            "update hosted app state",
        )


def remember_hosted(name, cwd_path):
    state = load_hosted_state()
    entries = [e for e in state.get("hosted", []) if e.get("name") != name]
    entries.append({"name": name, "cwd": cwd_path})
    save_hosted_state(entries)


def forget_hosted(name):
    state = load_hosted_state()
    entries = [e for e in state.get("hosted", []) if e.get("name") != name]
    save_hosted_state(entries)


# ---------------------------------------------------------------------------
# Process manager (host / stop / logs)
# ---------------------------------------------------------------------------

class HostedApp:
    def __init__(self, name, cwd_path, port, local_dir=None):
        self.name = name
        self.cwd_path = cwd_path
        self.port = port
        self.local_dir = local_dir
        self.proc = None
        self.log = collections.deque(maxlen=500)
        self.started_at = time.time()
        # rel_path -> sha1 of last-synced content, so periodic sync only
        # pushes files that actually changed since the previous pass
        self.synced_hashes = {}

    def pump_output(self):
        for line in iter(self.proc.stdout.readline, b""):
            try:
                self.log.append(line.decode(errors="replace").rstrip())
            except Exception:
                pass


HOSTED = {}  # name -> HostedApp
HOSTED_LOCK = threading.Lock()

BOOT_ID = uuid.uuid4().hex[:8]
BOOT_EVENTS = []
BOOT_EVENTS_LOCK = threading.Lock()


def log_boot_event(msg):
    with BOOT_EVENTS_LOCK:
        BOOT_EVENTS.append(msg)


def free_port():
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind(("", 0))
    port = s.getsockname()[1]
    s.close()
    return port


def sync_dir_to_local(cwd_path, local_dir):
    """Pull an entire GitHub directory tree (files + subdirectories) down to
    a local temp dir, so imports / sibling files (requirements.txt, static/,
    templates/, instance/ etc) all work exactly like they would on a normal
    filesystem."""
    if os.path.exists(local_dir):
        shutil.rmtree(local_dir)
    os.makedirs(local_dir, exist_ok=True)
    _sync_dir_to_local_recursive(cwd_path, local_dir)


def _sync_dir_to_local_recursive(gh_dir, local_target_dir):
    entries = gh_list(gh_dir) or []
    os.makedirs(local_target_dir, exist_ok=True)
    for e in entries:
        if e["name"] == ".gitkeep":
            continue
        sub = f"{gh_dir}/{e['name']}" if gh_dir else e["name"]
        if e["type"] == "dir":
            _sync_dir_to_local_recursive(sub, os.path.join(local_target_dir, e["name"]))
            continue
        content, _ = gh_get_file(sub)
        if content is not None:
            with open(os.path.join(local_target_dir, e["name"]), "wb") as f:
                f.write(content)


SYNC_INTERVAL = 60  # seconds between periodic syncs of hosted-app dirs back to GitHub
SYNC_EXCLUDE_DIRS = {"__pycache__", ".git", "venv", ".venv", "node_modules"}
SYNC_EXCLUDE_EXT = {".pyc"}


def _hash_file(path):
    with open(path, "rb") as f:
        return hashlib.sha1(f.read()).hexdigest()


def _snapshot_local_hashes(local_dir):
    """Hash every file already in local_dir right after it's pulled down
    from GitHub, so the first periodic sync pass doesn't re-push files
    that haven't actually changed."""
    hashes = {}
    for root, dirs, files in os.walk(local_dir):
        dirs[:] = [d for d in dirs if d not in SYNC_EXCLUDE_DIRS]
        for fname in files:
            if os.path.splitext(fname)[1] in SYNC_EXCLUDE_EXT:
                continue
            full_path = os.path.join(root, fname)
            rel_path = os.path.relpath(full_path, local_dir).replace(os.sep, "/")
            try:
                hashes[rel_path] = _hash_file(full_path)
            except Exception:
                pass
    return hashes


def sync_hosted_app_to_github(hosted):
    """Push any new/changed files in a hosted app's local working dir back
    up to GitHub, transparent to the app itself. This is what makes local
    writes (SQLite databases, logs, anything the app saves to disk) survive
    a restart or redeploy - EchoNet syncs the directory both ways, not just
    down at start time."""
    local_dir = hosted.local_dir
    if not local_dir or not os.path.isdir(local_dir):
        return
    for root, dirs, files in os.walk(local_dir):
        dirs[:] = [d for d in dirs if d not in SYNC_EXCLUDE_DIRS]
        for fname in files:
            if os.path.splitext(fname)[1] in SYNC_EXCLUDE_EXT:
                continue
            full_path = os.path.join(root, fname)
            rel_path = os.path.relpath(full_path, local_dir).replace(os.sep, "/")
            try:
                digest = _hash_file(full_path)
            except Exception:
                continue
            if hosted.synced_hashes.get(rel_path) == digest:
                continue  # unchanged since last sync pass
            gh_target = gh_path(hosted.cwd_path, rel_path)
            try:
                with open(full_path, "rb") as f:
                    content = f.read()
                gh_put_file(gh_target, content, f"auto-sync {rel_path} from {hosted.name}")
                hosted.synced_hashes[rel_path] = digest
            except Exception as e:
                hosted.log.append(f"[echonet-sync] failed to sync {rel_path}: {e}")


def periodic_sync_loop():
    """Runs for the life of the server, pushing every hosted app's local
    changes back to GitHub every SYNC_INTERVAL seconds."""
    while True:
        time.sleep(SYNC_INTERVAL)
        with HOSTED_LOCK:
            apps = list(HOSTED.values())
        for hosted in apps:
            try:
                sync_hosted_app_to_github(hosted)
            except Exception as e:
                hosted.log.append(f"[echonet-sync] error: {e}")


def start_hosted_app(name, cwd_path, persist=True):
    with HOSTED_LOCK:
        if name in HOSTED:
            return f"{name} is already hosted. Use 'stop {name}' first."

    local_dir = os.path.join(WORKDIR, name.replace("/", "_").replace(".", "_"))
    sync_dir_to_local(cwd_path, local_dir)

    filepath = os.path.join(local_dir, os.path.basename(name))
    if not os.path.exists(filepath):
        return f"{name}: not found in current directory."

    port = free_port()
    env = os.environ.copy()
    env["PORT"] = str(port)
    env["HOST"] = "127.0.0.1"

    # optional: install requirements.txt if present, best-effort, no output noise
    req = os.path.join(local_dir, "requirements.txt")
    if os.path.exists(req):
        subprocess.run(
            ["pip", "install", "--quiet", "--break-system-packages", "-r", req],
            cwd=local_dir,
        )

    proc = subprocess.Popen(
        ["python3", os.path.basename(name)],
        cwd=local_dir,
        env=env,
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT,
    )

    hosted = HostedApp(name, cwd_path, port, local_dir=local_dir)
    hosted.proc = proc
    hosted.synced_hashes = _snapshot_local_hashes(local_dir)
    with HOSTED_LOCK:
        HOSTED[name] = hosted

    t = threading.Thread(target=hosted.pump_output, daemon=True)
    t.start()

    if persist:
        try:
            remember_hosted(name, cwd_path)
        except Exception:
            pass

    slug = os.path.splitext(os.path.basename(name))[0]
    try:
        base_url = request.url_root.rstrip("/")
    except RuntimeError:
        base_url = os.environ.get("RENDER_EXTERNAL_URL", "").rstrip("/")
    return f"Hosted {name} on internal port {port}. URL: {base_url}/{slug}"


def kill_by_name(name):
    """Best-effort: kill any process (tracked or orphaned) whose command
    line references this filename. Needed because a prior server restart
    can leave a subprocess running with no record of it in HOSTED."""
    try:
        result = subprocess.run(["pkill", "-f", os.path.basename(name)], timeout=5)
        return result.returncode == 0
    except Exception:
        return False


def stop_hosted_app(name):
    with HOSTED_LOCK:
        hosted = HOSTED.pop(name, None)

    killed_tracked = False
    if hosted:
        try:
            sync_hosted_app_to_github(hosted)
        except Exception:
            pass
        try:
            hosted.proc.send_signal(signal.SIGTERM)
            hosted.proc.wait(timeout=5)
        except Exception:
            try:
                hosted.proc.kill()
            except Exception:
                pass
        killed_tracked = True

    orphan_killed = kill_by_name(name)

    try:
        forget_hosted(name)
    except Exception:
        pass

    if killed_tracked:
        return f"Stopped {name}."
    elif orphan_killed:
        return f"{name} wasn't tracked (likely orphaned from an earlier restart) - killed it by name anyway."
    else:
        return f"{name} is not running."


def stop_all_hosted():
    with HOSTED_LOCK:
        tracked_names = list(HOSTED.keys())

    for name in tracked_names:
        stop_hosted_app(name)

    # sweep any orphaned processes from persisted state that were never
    # re-tracked (e.g. survived a restart with no in-memory record)
    state = load_hosted_state()
    for entry in state.get("hosted", []):
        name = entry.get("name")
        if name and name not in tracked_names:
            kill_by_name(name)

    with HOSTED_LOCK:
        HOSTED.clear()
    save_hosted_state([])

    count = len(tracked_names)
    return f"Stopped {count} tracked app(s), swept orphans, and cleared hosted state."


def logs_hosted_app(name, n=40):
    hosted = HOSTED.get(name)
    if not hosted:
        return f"{name} is not running."
    lines = list(hosted.log)[-n:]
    return "\n".join(lines) if lines else "(no output yet)"


def run_bash_command(shell_cmd, timeout=60):
    """Run an arbitrary shell command/script directly on the server. This
    runs in a local scratch dir (BASH_WORKDIR) - it is NOT the GitHub-backed
    'filesystem', so nothing here persists across restarts. Use it for
    quick utility stuff (pip installs, curl checks, one-off scripts); use
    ls/cd/nano/hostapp for anything that should live in the repo."""
    if not shell_cmd.strip():
        return "usage: bash <command>"
    try:
        result = subprocess.run(
            shell_cmd,
            shell=True,
            cwd=BASH_WORKDIR,
            capture_output=True,
            timeout=timeout,
            text=True,
        )
        out = ((result.stdout or "") + (result.stderr or "")).strip()
        if not out:
            out = f"(exit {result.returncode}, no output)"
        return out
    except subprocess.TimeoutExpired:
        return f"bash: command timed out after {timeout}s"
    except Exception as e:
        return f"bash: {e}"


def list_hosted():
    with HOSTED_LOCK:
        if not HOSTED:
            return "No apps currently hosted."
        rows = []
        for name, h in HOSTED.items():
            slug = os.path.splitext(os.path.basename(name))[0]
            alive = h.proc.poll() is None
            rows.append(f"{name:20s} /{slug:15s} port={h.port:<6d} {'running' if alive else 'dead'}")
        return "\n".join(rows)


# ---------------------------------------------------------------------------
# Reverse proxy for hosted apps: /<slug>/<subpath>
# ---------------------------------------------------------------------------

@app.route("/<slug>", defaults={"subpath": ""}, methods=["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"], strict_slashes=False)
@app.route("/<slug>/<path:subpath>", methods=["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"])
def proxy(slug, subpath):
    if slug in RESERVED_ROUTES:
        return "Not found", 404
    # Answer CORS preflight immediately — forwarding it to the hosted app is
    # unnecessary and was previously impossible anyway since OPTIONS wasn't
    # even in the allowed methods above, causing every preflighted cross-
    # origin POST (e.g. from the web app) to fail before it got here.
    if request.method == "OPTIONS":
        resp = Response("", 204)
        resp.headers["Access-Control-Allow-Origin"] = request.headers.get("Origin", "*")
        resp.headers["Access-Control-Allow-Methods"] = "GET, POST, PUT, DELETE, PATCH, OPTIONS"
        resp.headers["Access-Control-Allow-Headers"] = request.headers.get("Access-Control-Request-Headers", "Content-Type, Authorization")
        resp.headers["Access-Control-Max-Age"] = "86400"
        return resp

    target = None
    with HOSTED_LOCK:
        for name, h in HOSTED.items():
            if os.path.splitext(os.path.basename(name))[0] == slug:
                target = h
                break
    if not target:
        return f"No app hosted at /{slug}", 404

    url = f"http://127.0.0.1:{target.port}/{subpath}"
    forward_headers = {k: v for k, v in request.headers if k.lower() != "host"}
    forward_headers["X-Script-Name"] = f"/{slug}"
    try:
        resp = requests.request(
            method=request.method,
            url=url,
            headers=forward_headers,
            data=request.get_data(),
            params=request.args,
            cookies=request.cookies,
            timeout=30,
            allow_redirects=False,
        )
    except requests.exceptions.ConnectionError:
        return f"{slug} is not responding yet (still starting up?)", 502

    excluded = {"content-encoding", "content-length", "transfer-encoding", "connection"}
    headers = []
    for k, v in resp.raw.headers.items():
        if k.lower() in excluded:
            continue
        if k.lower() == "location" and v.startswith("/") and not v.startswith(f"/{slug}"):
            v = f"/{slug}{v}"
        headers.append((k, v))
    return Response(resp.content, resp.status_code, headers)


@app.route("/healthz")
def healthz():
    return "ok"


# ---------------------------------------------------------------------------
# Shell command dispatcher
# ---------------------------------------------------------------------------

class Session:
    def __init__(self):
        self.cwd = ""  # path relative to repo root, "" = root
        self.pending_nano = None  # filename waiting for __write__


def handle_command(sess, cmdline):
    cmdline = cmdline.strip()
    if not cmdline:
        return ""

    # __write__ carries raw file content (arbitrary code, arbitrary quotes) -
    # it must never go through shlex, which chokes on unbalanced quotes in
    # real-world source files. Handle it before any parsing happens.
    if cmdline.startswith("__write__ "):
        rest = cmdline[len("__write__ "):]
        if " " not in rest:
            return "error: usage __write__ <filename> <content>"
        fname, content = rest.split(" ", 1)
        target = gh_path(sess.cwd, fname)
        try:
            gh_put_file(target, content.encode(), f"edit {fname} via echonetshell")
            return f"saved {fname}"
        except Exception as e:
            return f"error: {e}"

    if cmdline.startswith("__read__ "):
        fname = cmdline[len("__read__ "):].strip()
        target = gh_path(sess.cwd, fname)
        try:
            content, sha = gh_get_file(target)
            if content is None:
                return f"error: {fname} not found"
            return json.dumps({"content_b64": base64.b64encode(content).decode()})
        except Exception as e:
            return f"error: {e}"

    if cmdline.startswith("bash "):
        return run_bash_command(cmdline[len("bash "):])

    try:
        parts = shlex.split(cmdline)
    except ValueError as e:
        return f"error: {e}"
    cmd, args = parts[0], parts[1:]

    try:
        if cmd == "pwd":
            return "/" + sess.cwd

        if cmd == "ls":
            target = resolve_user_path(sess.cwd, args[0]) if args else sess.cwd
            entries = gh_list(target)
            if entries is None:
                return f"ls: cannot access '{args[0] if args else '.'}': No such directory"
            items = sorted(
                (e for e in entries if e["name"] != ".gitkeep"),
                key=lambda e: e["name"].lower(),
            )
            return json.dumps({"type": "ls", "entries": items})

        if cmd == "cd":
            if not args or args[0] in ("/", "~"):
                sess.cwd = ""
                return ""
            if args[0] == "..":
                sess.cwd = "/".join(sess.cwd.split("/")[:-1]) if sess.cwd else ""
                return ""
            target = resolve_user_path(sess.cwd, args[0])
            entries = gh_list(target)
            if entries is None:
                return f"cd: no such directory: {args[0]}"
            sess.cwd = target
            return ""

        if cmd == "mkdir":
            if not args:
                return "usage: mkdir <name>"
            gh_mkdir(resolve_user_path(sess.cwd, args[0]))
            return f"created {args[0]}"

        if cmd == "rm":
            if not args:
                return "usage: rm <name>"
            target = resolve_user_path(sess.cwd, args[0])
            content, sha = gh_get_file(target)
            if sha:
                gh_delete_file(target, f"rm {args[0]}")
                return f"removed {args[0]}"
            if gh_delete_dir(target, f"rm -r {args[0]}"):
                return f"removed directory {args[0]}"
            return f"rm: no such file or directory: {args[0]}"

        if cmd == "nano":
            if not args:
                return "usage: nano <filename>"
            fname = args[0]
            target = resolve_user_path(sess.cwd, fname)
            content, _ = gh_get_file(target)
            sess.pending_nano = fname
            return json.dumps({
                "type": "nano",
                "filename": fname,
                "content": content.decode(errors="replace") if content else "",
            })

        if cmd in ("hostapp", "host") and args and args[0] != "ls":
            resolved = resolve_user_path(sess.cwd, args[0])
            if "/" in resolved:
                dir_part, file_part = resolved.rsplit("/", 1)
            else:
                dir_part, file_part = "", resolved
            return start_hosted_app(file_part, dir_part)

        if cmd == "host" and args and args[0] == "ls":
            return list_hosted()

        if cmd == "stop":
            if not args:
                return "usage: stop <name> | stop all"
            if args[0] == "all":
                return stop_all_hosted()
            return stop_hosted_app(os.path.basename(args[0]))

        if cmd == "logs":
            if not args:
                return "usage: logs <name>"
            return logs_hosted_app(os.path.basename(args[0]))

        if cmd == "stats":
            return json.dumps({"type": "stats", "stats": get_full_stats()})

        if cmd == "bash":
            return "usage: bash <command>"

        if cmd == "help":
            return (
                "ls, cd, mkdir, rm, nano, upload, download, hostapp/host <file>, "
                "host ls, logs <name>, stop <name>, stop all, stats, pwd, bash <cmd>\n"
                "paths accept '~/' as shorthand for the repo root, e.g.\n"
                "  hostapp ~/tenoco/tenocoservices/nexfund/nexfund.py\n"
                "client-side only: launch, clear, exit"
            )

        return f"{cmd}: command not found"

    except requests.exceptions.HTTPError as e:
        return f"GitHub error: {e}"
    except Exception as e:
        return f"error: {e}"


# ---------------------------------------------------------------------------
# WebSocket shell endpoint
# ---------------------------------------------------------------------------

@sock.route("/shell")
def shell(ws):
    # first message must be the password
    raw = ws.receive()
    try:
        first = json.loads(raw)
    except Exception:
        ws.send(json.dumps({"type": "error", "message": "bad handshake"}))
        return

    if first.get("password") != SHELL_PASSWORD:
        ws.send(json.dumps({"type": "error", "message": "wrong password"}))
        return

    ws.send(json.dumps({
        "type": "auth_ok",
        "message": "connected to EchoNet",
        "boot_id": BOOT_ID,
        "boot_events": BOOT_EVENTS,
        "running": list_hosted(),
        "stats": get_full_stats(),
    }))

    sess = Session()
    while True:
        raw = ws.receive()
        if raw is None:
            break
        try:
            msg = json.loads(raw)
        except Exception:
            continue

        if "upload" in msg:
            up = msg["upload"]
            fname = up.get("filename", "")
            b64 = up.get("content_b64", "")
            try:
                raw_bytes = base64.b64decode(b64)
                target = gh_path(sess.cwd, fname)
                gh_put_file(target, raw_bytes, f"upload {fname} via echonetshell")
                output = f"uploaded {fname} ({len(raw_bytes)} bytes)"
            except Exception as e:
                output = f"upload error: {e}"
            ws.send(json.dumps({"type": "output", "cwd": sess.cwd, "output": output}))
            continue

        cmd = msg.get("cmd", "")
        output = handle_command(sess, cmd)
        ws.send(json.dumps({"type": "output", "cwd": sess.cwd, "output": output}))


if __name__ == "__main__":
    port = int(os.environ.get("PORT", 7860))
    app.run(host="0.0.0.0", port=port)


# ---------------------------------------------------------------------------
# Startup tasks - run once when gunicorn (or `python server.py`) loads this
# module. With -w 1 this runs exactly once per boot.
# ---------------------------------------------------------------------------

def restore_hosted_apps():
    """Re-host whatever was running before the last restart/spin-down."""
    time.sleep(5)  # let the server finish booting first
    state = load_hosted_state()
    entries = state.get("hosted", [])
    if not entries:
        log_boot_event("no previously hosted apps to restore")
        return
    for entry in entries:
        name = entry.get("name")
        cwd_path = entry.get("cwd", "")
        if not name:
            continue
        try:
            result = start_hosted_app(name, cwd_path, persist=False)
            log_boot_event(f"restored {name}: {result}")
        except Exception as e:
            log_boot_event(f"failed to restore {name}: {e}")


def self_ping_loop():
    """Ping our own public URL every 5 minutes to discourage Render's free
    tier from spinning the instance down. Requires RENDER_EXTERNAL_URL,
    which Render sets automatically for web services."""
    self_url = os.environ.get("RENDER_EXTERNAL_URL") or os.environ.get("SELF_URL")
    if not self_url:
        return
    health_url = f"{self_url.rstrip('/')}/healthz"
    while True:
        time.sleep(300)
        try:
            requests.get(health_url, timeout=15)
        except Exception:
            pass


threading.Thread(target=restore_hosted_apps, daemon=True).start()
threading.Thread(target=self_ping_loop, daemon=True).start()
threading.Thread(target=periodic_sync_loop, daemon=True).start()