Files

422 lines
17 KiB
Python

"""Local, read-only observer for CAD Factory."""
import argparse
from concurrent.futures import ThreadPoolExecutor
from hashlib import sha256
from http.client import HTTPConnection, HTTPException
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer as HTTPServer
import json
import os
from pathlib import Path
import re
import shutil
import socket
import stat
import subprocess
import sys
import time
from urllib.parse import urlencode
HERE = Path(__file__).resolve().parent
DEFAULT_PORT = 8765
PORT_ATTEMPTS = 8
MAX_CARD_BYTES = 256 * 1024
MAX_PREVIEW_BYTES = 8 * 1024 * 1024
PREVIEW_NAME = re.compile(
r"(?P<card>[A-Za-z0-9][A-Za-z0-9_-]{0,79})\."
r"(?P<revision>[A-Za-z0-9][A-Za-z0-9_-]{0,79})-(?:overview|detail)\.png"
)
PREVIEW_LINE = re.compile(r"^!\[([^\]\r\n]+)\]\(([^()\s]+)\)$")
AGENTS = {"cad-factory", "cad-analysis", "cad-modeling", "cad-verification"}
SESSION_ID = re.compile(r"ses[A-Za-z0-9_-]+")
FIELDS = {
"Текущее состояние": "status",
"Предлагаемая ревизия": "revision",
"Принятая база": "base",
"Поручение и режим": "task",
}
def parse_card(path, text, updated):
card = {"id": path.stem, "title": path.stem, "updated": updated, "markdown": text}
heading = re.search(r"^#\s+(.+)$", text, re.MULTILINE)
if heading:
title = heading[1].strip()
card["title"] = re.sub(rf"^{re.escape(path.stem)}\s+[—–-]\s+", "", title,
flags=re.IGNORECASE) or path.stem
for line in text.splitlines():
match = re.match(r"^\s*[-*]\s+([^:]+):\s*(.*)$", line)
if match and (key := FIELDS.get(match[1].strip().strip("*"))) and key not in card:
value = match[2].strip()
if match[1].lstrip().startswith("**") and not match[1].rstrip().endswith("**"):
value = value.removeprefix("**").lstrip()
card[key] = value.strip("`*").strip()
previews = {}
for line in text.splitlines():
image = PREVIEW_LINE.fullmatch(line.strip())
if image is None:
continue
name = PREVIEW_NAME.fullmatch(image[2])
if name and name["card"] == path.stem:
previews[image[2]] = {"file": image[2], "caption": image[1],
"revision": name["revision"]}
if previews:
card["previews"] = list(previews.values())
return card
def is_link_or_reparse(info):
return stat.S_ISLNK(info.st_mode) or bool(
getattr(info, "st_file_attributes", 0) & stat.FILE_ATTRIBUTE_REPARSE_POINT
)
def read_regular_file(path, limit):
parent = path.parent.lstat()
if is_link_or_reparse(parent) or not stat.S_ISDIR(parent.st_mode):
raise OSError("not a regular directory")
before = path.lstat()
if is_link_or_reparse(before) or not stat.S_ISREG(before.st_mode):
raise OSError("not a regular file")
flags = os.O_RDONLY | getattr(os, "O_BINARY", 0)
flags |= getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0)
with os.fdopen(os.open(path, flags), "rb") as file:
info = os.fstat(file.fileno())
current = path.lstat()
current_parent = path.parent.lstat()
if (is_link_or_reparse(current_parent) or not os.path.samestat(parent, current_parent)
or is_link_or_reparse(current) or not os.path.samestat(before, current)
or not os.path.samestat(current, info) or not stat.S_ISREG(info.st_mode)
or info.st_size > limit):
raise OSError("not a readable file")
data = file.read(limit + 1)
if len(data) > limit:
raise OSError("file grew past the limit")
return data, info.st_mtime
def read_cards(root):
folder = root / "changes"
cards, skipped = [], 0
try:
folder_info = folder.lstat()
except FileNotFoundError:
return {"cards": cards, "skipped": skipped}
if is_link_or_reparse(folder_info) or not stat.S_ISDIR(folder_info.st_mode):
raise OSError("changes must be a regular directory")
for path in sorted(folder.iterdir()):
if path.suffix != ".md" or path.name.startswith("."):
continue
try:
data, updated = read_regular_file(path, MAX_CARD_BYTES)
cards.append(parse_card(path, data.decode("utf-8-sig"), updated))
except (OSError, UnicodeError):
skipped += 1
return {"cards": sorted(cards, key=lambda card: (-card["updated"], card["id"])),
"skipped": skipped}
def read_preview(root, filename):
name = PREVIEW_NAME.fullmatch(filename)
if not name:
raise OSError("invalid preview name")
folder = root / "changes"
card_path = folder / f"{name['card']}.md"
data, updated = read_regular_file(card_path, MAX_CARD_BYTES)
card = parse_card(card_path, data.decode("utf-8-sig"), updated)
if not any(preview["file"] == filename for preview in card.get("previews", [])):
raise OSError("preview is not listed on the card")
data, _ = read_regular_file(folder / filename, MAX_PREVIEW_BYTES)
if not data.startswith(b"\x89PNG\r\n\x1a\n"):
raise OSError("not a PNG preview")
return data
class OpenCodeUnavailable(Exception):
pass
def opencode_executable():
if os.name != "nt":
return "opencode"
native = shutil.which("opencode.exe")
if native:
return native
shim = shutil.which("opencode.cmd")
if shim:
npm_exe = Path(shim).parent / "node_modules" / "@opencode" / "cli" / "bin" / "opencode.exe"
if npm_exe.is_file():
return str(npm_exe)
raise OpenCodeUnavailable
def opencode_get(root, path):
try:
result = subprocess.run([opencode_executable(), "api", "get", path], cwd=root,
capture_output=True, check=True, timeout=4)
return json.loads(result.stdout)["data"]
except (OSError, subprocess.SubprocessError, ValueError, KeyError, TypeError) as exc:
raise OpenCodeUnavailable from exc
def read_activity(root, api=opencode_get):
"""Read statuses only; scope sessions and job owners to the selected directory."""
with ThreadPoolExecutor(max_workers=8) as pool:
active_future = pool.submit(api, root, "/api/session/active")
jobs_future = pool.submit(api, root, "/api/experimental/job?" + urlencode(
{"kind": "subagent", "status": "running"}))
failed = 0
try:
active = active_future.result()
if not isinstance(active, dict):
raise OpenCodeUnavailable
except OpenCodeUnavailable:
active, failed = {}, 1
try:
jobs = jobs_future.result()
if not isinstance(jobs, list):
raise OpenCodeUnavailable
except OpenCodeUnavailable:
jobs, failed = [], failed + 1
if failed == 2:
raise OpenCodeUnavailable
state = "partial" if failed else "available"
def valid_id(value):
return isinstance(value, str) and SESSION_ID.fullmatch(value)
running = {key for key, value in active.items() if valid_id(key)
and isinstance(value, dict) and value.get("type") == "running"}
jobs = [job for job in jobs if isinstance(job, dict)
and job.get("kind") == "subagent" and job.get("status") == "running"
and isinstance(job.get("agent"), str) and job["agent"] in AGENTS
and valid_id(job.get("sessionID")) and valid_id(job.get("childSessionID"))]
owners = running | {job["sessionID"] for job in jobs}
lookups = {sid: pool.submit(api, root, f"/api/session/{sid}") for sid in sorted(owners)}
sessions = {}
for sid, future in lookups.items():
try:
session = future.result()
except OpenCodeUnavailable:
state = "partial"
continue
location = session.get("location") if isinstance(session, dict) else None
directory = location.get("directory") if isinstance(location, dict) else None
if (session and isinstance(directory, str) and Path(directory).is_absolute()
and Path(os.path.realpath(directory)) == root):
sessions[sid] = session
rows = {}
for sid in sorted(running & sessions.keys()):
agent = sessions[sid].get("agent")
if isinstance(agent, str) and agent in AGENTS:
rows[sid] = {"agent": agent, "kind": "session"}
for job in jobs:
if job["sessionID"] in sessions:
rows[job["childSessionID"]] = {"agent": job["agent"], "kind": "subagent"}
return {"state": state, "agents": sorted(rows.values(), key=lambda row: row["agent"])}
ASSETS = {
"/": ("index.html", "text/html; charset=utf-8"),
"/app.css": ("app.css", "text/css; charset=utf-8"),
"/app.js": ("app.js", "text/javascript; charset=utf-8"),
}
def install_dashboard(root):
"""Materialize the bundled panel without replacing project files."""
folder = root / "dashboard"
folder.mkdir(exist_ok=True)
info = folder.lstat()
if is_link_or_reparse(info) or not stat.S_ISDIR(info.st_mode):
raise OSError("dashboard must be a regular directory")
for name in ["serve.py"] + [filename for filename, _ in ASSETS.values()]:
data = (HERE / name).read_bytes()
try:
with (folder / name).open("xb") as file:
file.write(data)
except FileExistsError:
continue
def project_identity(root):
return {"service": "cad-factory-dashboard", "protocol": 3,
"project": sha256(os.fsencode(root)).hexdigest()}
def dashboard_state(root, port):
"""Identify a reusable panel without following redirects or using a proxy."""
connection = HTTPConnection("127.0.0.1", port, timeout=0.25)
try:
connection.request("GET", "/api/health")
response = connection.getresponse()
if response.status == 200 and json.loads(response.read(1024)) == project_identity(root):
return "matching"
except ConnectionRefusedError:
return "free"
except TimeoutError:
# Windows can time out rather than refuse an unused loopback port.
if os.name == "nt":
with socket.socket() as probe:
probe.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1)
try:
probe.bind(("127.0.0.1", port))
except OSError:
pass
else:
return "free"
except (OSError, HTTPException, ValueError):
pass
finally:
connection.close()
return "occupied"
class ThreadingHTTPServer(HTTPServer):
def server_bind(self):
if os.name == "nt":
self.allow_reuse_address = False
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1)
super().server_bind()
def launch_dashboard(root, port, cards_only):
command = [sys.executable, "-I", str(HERE / "serve.py"), "--root", str(root), "--port", str(port)]
if cards_only:
command.append("--cards-only")
return subprocess.Popen(command, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL, start_new_session=True)
def ensure_dashboard(root, start_port=DEFAULT_PORT, cards_only=False):
ports = range(start_port, min(start_port + PORT_ATTEMPTS, 65536))
available = []
for port in ports:
state = dashboard_state(root, port)
if state == "matching":
return port
if state == "free":
available.append(port)
for port in available:
child = launch_dashboard(root, port, cards_only)
ready = False
try:
deadline = time.monotonic() + 1.5
while time.monotonic() < deadline:
state = dashboard_state(root, port)
if state == "matching":
ready = True
return port
if state == "occupied" or child.poll() is not None:
# Another launcher may have won the bind; check its identity once more.
ready = dashboard_state(root, port) == "matching"
if ready:
return port
break
time.sleep(0.04)
finally:
if not ready and child.poll() is None:
child.terminate()
child.wait(timeout=1)
raise OSError("No available port for the CAD Factory dashboard")
class Handler(BaseHTTPRequestHandler):
def reply(self, status, mime, data):
self.send_response(status)
self.send_header("Content-Type", mime)
self.send_header("Content-Length", str(len(data)))
self.send_header("Cache-Control", "no-store")
self.send_header("X-Content-Type-Options", "nosniff")
self.send_header("Cross-Origin-Resource-Policy", "same-origin")
self.send_header("Content-Security-Policy",
"default-src 'self'; base-uri 'none'; frame-ancestors 'none'; "
"object-src 'none'; form-action 'none'")
self.end_headers()
self.wfile.write(data)
def json_reply(self, status, data):
self.reply(status, "application/json", json.dumps(data, ensure_ascii=False).encode())
def do_GET(self):
port = self.server.server_port
if (self.headers.get("Host") not in {f"127.0.0.1:{port}", f"localhost:{port}"}
or self.headers.get("Sec-Fetch-Site") == "cross-site"):
self.json_reply(403, {"error": "local requests only"})
elif self.path in ASSETS:
filename, mime = ASSETS[self.path]
self.reply(200, mime, (HERE / filename).read_bytes())
elif self.path == "/api/health":
self.json_reply(200, project_identity(self.server.root))
elif self.path == "/api/cards":
try:
self.json_reply(200, read_cards(self.server.root))
except OSError:
self.json_reply(503, {"error": "cannot read changes"})
elif self.path.startswith("/api/previews/"):
try:
data = read_preview(self.server.root, self.path.removeprefix("/api/previews/"))
except (OSError, UnicodeError):
self.json_reply(404, {"error": "preview not found"})
else:
self.reply(200, "image/png", data)
elif self.path == "/api/activity":
if not self.server.activity:
self.json_reply(200, {"state": "disabled", "agents": []})
return
try:
self.json_reply(200, read_activity(self.server.root))
except OpenCodeUnavailable:
self.json_reply(200, {"state": "unavailable", "agents": []})
else:
self.json_reply(404, {"error": "not found"})
def log_message(self, *_args):
pass
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--root", type=Path, default=Path.cwd(),
help="CAD project directory (default: current directory)")
parser.add_argument("--port", type=int, default=DEFAULT_PORT)
parser.add_argument("--cards-only", action="store_true", help="do not contact OpenCode")
parser.add_argument("--install", action="store_true",
help="copy missing panel files into the project's dashboard directory")
parser.add_argument("--ensure", action="store_true",
help="reuse or start a detached dashboard and print its URL")
args = parser.parse_args()
root = args.root.resolve()
if not root.is_dir():
parser.error("--root must be an existing directory")
if args.install:
try:
install_dashboard(root)
except OSError as exc:
parser.exit(1, f"CAD Factory: {exc}\n")
if not args.ensure:
return
if args.ensure:
if not 1 <= args.port <= 65535:
parser.error("--ensure requires a port between 1 and 65535")
try:
port = ensure_dashboard(root, args.port, args.cards_only)
except (OSError, subprocess.SubprocessError) as exc:
parser.exit(1, f"CAD Factory: {exc}\n")
print(f"http://127.0.0.1:{port}/")
return
with ThreadingHTTPServer(("127.0.0.1", args.port), Handler) as server:
server.root = root
server.activity = not args.cards_only
print(f"CAD Factory · http://127.0.0.1:{server.server_port}/", flush=True)
try:
server.serve_forever()
except KeyboardInterrupt:
pass
if __name__ == "__main__":
main()