Spaces:
Running

File size: 4,291 Bytes
fd5dd94
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Start WorkPilot inside a Hugging Face Docker Space (see deploy/hf/Dockerfile).

1. Start an embedded Postgres 16 + pgvector (pgserver) in /tmp. The Space has no persistent
   disk, so the database is rebuilt on every start: a clean public demo each time.
2. Bootstrap the two roles with random passwords, run the release step (config check,
   migrations, tool index) and seed the demo tenant.
3. Run the API (127.0.0.1:8000), the DBOS worker and the Next.js server (0.0.0.0:7860, which
   forwards /backend/* to the API). If any of them exits, stop the rest and exit non-zero so
   the Space restarts.

Space secrets read here (Settings > Variables and secrets): a model key (GOOGLE_API_KEY,
GROQ_API_KEY or ANTHROPIC_API_KEY) and the WP_MODEL_* tiers; WP_JWT_SECRET is optional
(random per start otherwise, which only logs everyone out on restart).
"""

from __future__ import annotations

import os
import secrets
import shutil
import signal
import subprocess
import sys
import time
from pathlib import Path

ROOT = Path(__file__).resolve().parents[2]
PGDATA = Path(os.environ.get("WP_HF_PGDATA", "/tmp/workpilot-pg"))  # noqa: S108
PORT = int(os.environ.get("PORT", "7860"))
DB = "workpilot"
NODE = shutil.which("node") or "/usr/local/bin/node"


def log(msg: str) -> None:
    print(f"[start] {msg}", flush=True)


def prepare_database(env: dict[str, str]) -> None:
    import pgserver

    from core.db.bootstrap import bootstrap, role_url

    su = str(pgserver.get_server(str(PGDATA), cleanup_mode=None).get_uri())
    owner_pw, app_pw = secrets.token_urlsafe(24), secrets.token_urlsafe(24)
    bootstrap(su, DB, owner_pw, app_pw)
    env["WP_DATABASE_URL"] = role_url(su, "workpilot_app", app_pw, DB)
    env["WP_OWNER_DATABASE_URL"] = role_url(su, "workpilot_owner", owner_pw, DB)
    log(f"postgres ready ({PGDATA})")


def defaults(env: dict[str, str]) -> None:
    env.setdefault("WP_ENV", "production")
    if len(env.get("WP_JWT_SECRET", "")) < 32:
        env["WP_JWT_SECRET"] = secrets.token_urlsafe(48)
    # Public demo: cap model calls per tenant per day so visitors cannot drain the key.
    env.setdefault("WP_MAX_LLM_CALLS_PER_TENANT_PER_DAY", "200")
    env.setdefault("WP_WORKER_EXECUTOR_ID", "hf-0")
    env["WP_RELEASE_SEED_DEMO"] = "1"
    host = env.get("SPACE_HOST")  # set by Hugging Face, e.g. user-space.hf.space
    origins = [f"http://127.0.0.1:{PORT}"] + ([f"https://{host}"] if host else [])
    env.setdefault("WP_CORS_ORIGINS", "[" + ", ".join(f'"{o}"' for o in origins) + "]")


def main() -> int:
    env = dict(os.environ)
    defaults(env)
    os.environ.update(env)  # bootstrap below reads settings from the environment
    prepare_database(env)
    os.environ.update(env)
    subprocess.run(["/bin/sh", "deploy/scripts/release.sh"], cwd=ROOT, env=env, check=True)

    web_env = {
        **env,
        "PORT": str(PORT),
        "HOSTNAME": "0.0.0.0",  # noqa: S104 - the Space's public port
        "WP_API_URL": "http://127.0.0.1:8000",
        "NEXT_TELEMETRY_DISABLED": "1",
    }
    procs = {
        "api": subprocess.Popen(
            [sys.executable, "-m", "core.serve", "--host", "127.0.0.1", "--port", "8000"],
            cwd=ROOT,
            env=env,
        ),
        "worker": subprocess.Popen([sys.executable, "-m", "core.worker"], cwd=ROOT, env=env),
        "web": subprocess.Popen([NODE, "server.js"], cwd=ROOT / "web", env=web_env),  # noqa: S603
    }
    log(f"started {', '.join(procs)}; web on :{PORT}")

    def stop(*_: object) -> None:
        for p in procs.values():
            if p.poll() is None:
                p.terminate()

    signal.signal(signal.SIGTERM, stop)
    signal.signal(signal.SIGINT, stop)
    try:
        while True:
            for name, p in procs.items():
                code = p.poll()
                if code is not None:
                    log(f"{name} exited with {code}; stopping the Space")
                    stop()
                    for q in procs.values():
                        try:
                            q.wait(timeout=20)
                        except subprocess.TimeoutExpired:
                            q.kill()
                    return code or 1
            time.sleep(1)
    finally:
        stop()


if __name__ == "__main__":
    sys.exit(main())