Download app/procs.py from simonu5/TriChat: direct link, hf CLI and curl.
- Browser
- Download file 3.99 kB
-
https://huggingface.co/spaces/simonu5/TriChat/resolve/main/app/procs.py
- Command line
-
hf download hf://spaces/simonu5/TriChat/app/procs.py
-
curl -L -o procs.py https://huggingface.co/spaces/simonu5/TriChat/resolve/main/app/procs.py
3.99 kB
| """背景程序:讓 agent 啟動開發伺服器、watch、長時間任務,不會卡住對話。 | |
| 每個程序屬於一個專案(或暫存區),輸出保留最後 LOG_MAX 字元。 | |
| 啟動的伺服器可以用 curl http://127.0.0.1:<port> 測試,使用者也能從「預覽」連結打開。 | |
| """ | |
| import asyncio | |
| import os | |
| import re | |
| import signal | |
| import time | |
| from . import workspace | |
| LOG_MAX = 400_000 | |
| PORT_RE = re.compile(r"(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[::\]|port\s*[:=]?\s*)[:\s]?(\d{4,5})", re.I) | |
| class Proc: | |
| def __init__(self, name, command, cwd, project): | |
| self.name, self.command, self.cwd, self.project = name, command, cwd, project | |
| self.proc: asyncio.subprocess.Process | None = None | |
| self.log = "" | |
| self.started = time.time() | |
| self.ended: float | None = None | |
| self.ports: list[int] = [] | |
| self.reader: asyncio.Task | None = None | |
| def running(self): | |
| return self.proc is not None and self.proc.returncode is None | |
| def info(self): | |
| return {"name": self.name, "command": self.command, "running": self.running, | |
| "exit_code": None if self.running else (self.proc.returncode if self.proc else None), | |
| "ports": self.ports, "project_id": self.project, | |
| "uptime_s": int((self.ended or time.time()) - self.started)} | |
| procs: dict[str, Proc] = {} | |
| async def _pump(p: Proc): | |
| while True: | |
| chunk = await p.proc.stdout.read(4096) | |
| if not chunk: | |
| break | |
| text = chunk.decode(errors="replace") | |
| p.log = (p.log + text)[-LOG_MAX:] | |
| for m in PORT_RE.finditer(text): | |
| port = int(m.group(1)) | |
| if 1024 <= port <= 65535 and port not in p.ports: | |
| p.ports.append(port) | |
| await p.proc.wait() | |
| p.ended = time.time() | |
| p.log += f"\n[程序結束,exit code {p.proc.returncode}]\n" | |
| async def start(command: str, name: str | None, env: dict, preexec) -> dict: | |
| name = (name or command.split()[0] if command.strip() else "proc")[:40] | |
| old = procs.get(name) | |
| if old and old.running: | |
| return {"error": f"已經有一個叫 {name} 的程序在跑;先 stop_process 或換個 name"} | |
| p = Proc(name, command, str(workspace.current_dir()), workspace.current_project.get()) | |
| p.proc = await asyncio.create_subprocess_exec( | |
| "bash", "-c", command, cwd=p.cwd, env=env, stdin=asyncio.subprocess.DEVNULL, | |
| stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.STDOUT, preexec_fn=preexec) | |
| p.reader = asyncio.create_task(_pump(p)) | |
| procs[name] = p | |
| await asyncio.sleep(3) # 給它一點時間啟動,順便把最初的輸出帶回去 | |
| return {**p.info(), "output": p.log[-4000:]} | |
| def logs(name: str, tail: int = 200) -> dict: | |
| p = procs.get(name) | |
| if not p: | |
| return {"error": f"沒有叫 {name} 的程序", "processes": [x.name for x in procs.values()]} | |
| lines = p.log.splitlines()[-max(1, min(int(tail), 5000)):] | |
| return {**p.info(), "output": "\n".join(lines)} | |
| async def stop(name: str) -> dict: | |
| p = procs.get(name) | |
| if not p: | |
| return {"error": f"沒有叫 {name} 的程序"} | |
| if p.running: | |
| try: | |
| os.killpg(p.proc.pid, signal.SIGTERM) | |
| except ProcessLookupError: | |
| pass | |
| try: | |
| await asyncio.wait_for(p.proc.wait(), 5) | |
| except asyncio.TimeoutError: | |
| try: | |
| os.killpg(p.proc.pid, signal.SIGKILL) | |
| except ProcessLookupError: | |
| pass | |
| await p.proc.wait() | |
| procs.pop(name, None) | |
| return {"ok": True, "stopped": name, "last_output": p.log[-2000:]} | |
| def listing(project: str | None = "__all__") -> list[dict]: | |
| return [p.info() for p in procs.values() if project == "__all__" or p.project == project] | |
| async def stop_all(): | |
| for name in list(procs): | |
| try: | |
| await stop(name) | |
| except Exception: # noqa: BLE001 | |
| pass | |