Something went wrong. Try again.
small gleam coding and persistent agent daemon with a detachable cli and a canvas ui forked from okami.mom/albedo
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315"""Build the home a UI review starts from, from scratch.
Compiles a daemon snapshot and a web build, makes two small git workspaces,then boots a private daemon on a fresh ALBEDO_HOME with the fake model fromreplies.py and seeds named chats through the HTTP API. The daemon, the fakemodel and home-matching processes are checked during cleanup. Cleanup failuresraise rather than reporting success. Run it from the checkout inside `nix develop`:
python3 test/manual/ux/seed.py [--base /tmp/albedo-review]
Writes <base>/daemon, <base>/dist, <base>/ws and <base>/seed (the home kit.pycopies for each review run)."""
from __future__ import annotations
import argparseimport jsonimport osimport secretsimport shutilimport subprocessimport sysimport timeimport urllib.errorimport urllib.requestimport uuidfrom pathlib import Pathfrom contextlib import ExitStack
from lifecycle_support import acquire_base, reap
ROOT = Path(__file__).resolve().parents[3]HERE = Path(__file__).resolve().parentCLI = ROOT / "cli/bin/albedo"# Disable remote model-list refreshes and cache-TTL requests.OFFLINE = {"models": {"refreshHours": 0}, "cacheTtl": {"url": None}}PROFILE = "ux"
def web_build(dist: Path) -> list[str]: """The command that builds the web client into dist, never web/dist.""" return [ "npm", "--prefix", str(ROOT / "web"), "run", "build", "--", "--outDir", str(dist), "--emptyOutDir", ] # fmt: skip
def daemon_env(home: Path, daemon: str, parent: int) -> dict[str, str]: """What a review daemon needs on top of the caller's environment.""" return { "ALBEDO_HOME": str(home), "ALBEDO_DAEMON": daemon, "ALBEDO_PARENT_PID": str(parent), "ALBEDO_NO_BROWSER": "1", "ALBEDO_PRELOAD": "0", "ALBEDO_STANDBY": "0", "ALBEDO_KERNEL_GRACE_SECONDS": "5", }
def fake_model_argv() -> tuple[list[str], dict[str, str]]: """fake_provider.py on replies.py: its argv after the interpreter, and its extra env.""" return ( [str(ROOT / "test/e2e/fake_provider.py"), str(HERE / "replies.py")], {"PYTHONPATH": f"{ROOT / 'test/e2e'}:{HERE}"}, )
# (name, workspace, messages): the reply each message gets is in replies.py.CHATS = [ ("hello chat", "alpha", ["hi there"]), ( "markdown, code and tables", "alpha", [ "what's a section?", "show me some code", "a table please", "think about where this goes", ], ), ( "a very long chat", "alpha", ["long please", "long again", "and long once more", "hi"], ), ("tools and file edits", "beta", ["run a tool", "edit the files", "hi"]), ("a failing turn", "beta", ["this will fail"]), *( (f"short {n}", "alpha" if i % 2 else "beta", ["hi"]) for i, n in enumerate(["one", "two", "three", "four", "five"]) ),]
def operation_id() -> str: """A UUIDv7, the identity the daemon wants for a new session or input.""" bits = (int(time.time() * 1000) << 80) | (7 << 76) | secrets.randbits(76) return str(uuid.UUID(int=(bits & ~(3 << 62)) | (2 << 62)))
def sh(*argv: str | Path, **kwargs) -> str: return subprocess.run( [str(a) for a in argv], check=True, capture_output=True, text=True, **kwargs ).stdout
def workspace(path: Path) -> None: shutil.rmtree(path, ignore_errors=True) (path / "src").mkdir(parents=True) (path / "src/app.ts").write_text( "export function greet(name: string) {\n return `hello ${name}`;\n}\n" ) (path / "README.md").write_text(f"# {path.name}\n\na workspace for the ui review\n") sh("git", "init", "-q", cwd=path) sh("git", "add", ".", cwd=path) sh( "git", "-c", "user.email=ux@albedo", "-c", "user.name=ux", "commit", "-qm", "init", cwd=path, )
class Daemon: """The seed's private daemon, reached with the token in its daemon.json."""
def __init__(self, home: Path, env: dict[str, str]): self.home, self.env = home, env
def start(self) -> None: sh(CLI, "daemon", env=self.env) connection = json.loads((self.home / "daemon.json").read_text()) self.base = f"http://127.0.0.1:{connection['port']}" self.token = connection["token"]
def api( self, method: str, path: str, body: dict | None = None, headers: dict | None = None, ): request = urllib.request.Request( self.base + path, data=None if body is None else json.dumps(body).encode(), method=method, headers={ "Authorization": "Bearer " + self.token, "Content-Type": "application/merge-patch+json" if method == "PATCH" else "application/json", **(headers or {}), }, ) with urllib.request.urlopen(request, timeout=30) as response: return json.load(response), response.headers
def chat(self, workspace: Path) -> str: session = operation_id() body = {"kind": "new", "workspace": str(workspace), "provider_profile": PROFILE} self.api("PUT", f"/sessions/{session}", body, {"If-None-Match": "*"}) return session
def say(self, session: str, message: str) -> None: self.api( "PUT", f"/sessions/{session}/inputs/{operation_id()}", {"kind": "message", "text": message}, ) deadline = time.monotonic() + 60 while time.monotonic() < deadline: try: snapshot, _ = self.api("GET", f"/sessions/{session}?tail=0") except urllib.error.HTTPError as failure: if failure.code != 503: raise else: if ( snapshot["status"]["phase"] == "idle" and not snapshot["pending_inputs"] ): return time.sleep(0.2) raise SystemExit(f"{session} did not settle after {message!r}")
def name(self, session: str, name: str) -> None: _, headers = self.api("GET", f"/sessions/{session}?view=configuration") self.api( "PATCH", f"/sessions/{session}?view=configuration", {"name": name}, {"If-Match": headers["ETag"]}, )
def stop(self) -> None: failures: list[Exception] = [] try: subprocess.run( [str(CLI), "daemon", "--stop"], env=self.env, capture_output=True, check=True, timeout=60, ) except Exception as error: failures.append(error) try: remaining = reap(self.home) if remaining: failures.append( RuntimeError(f"home-matching processes remain: {remaining}") ) except Exception as error: failures.append(error) if failures: raise ExceptionGroup("seed daemon cleanup incomplete", failures)
def fake_model(env: dict[str, str]) -> tuple[subprocess.Popen, str]: """Start fake_provider.py on replies.py; returns it and its base URL.""" argv, extra = fake_model_argv() process = subprocess.Popen( [sys.executable, *argv], env={**env, **extra}, stdout=subprocess.PIPE, text=True, ) assert process.stdout try: url = process.stdout.readline().strip() if not url.startswith("http://"): raise RuntimeError("fake provider exited without a URL") return process, url except BaseException: stop_process(process) raise
def stop_process(process: subprocess.Popen) -> None: process.terminate() try: process.wait(timeout=10) except subprocess.TimeoutExpired: process.kill() process.wait(timeout=10)
def main() -> None: parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument( "--base", type=Path, default=Path(os.environ.get("ALBEDO_UX", "/tmp/albedo-review")), ) base = parser.parse_args().base.resolve() with acquire_base(base, exclusive=True): active = list((base / "runs").glob("*/.active")) if active: raise RuntimeError(f"unfinished review runs prevent reseeding: {active}") seed(base)
def seed(base: Path) -> None: if not CLI.exists(): raise SystemExit( f"{CLI} is missing: go -C cli build -o bin/albedo ./cmd/albedo" ) base.mkdir(parents=True, exist_ok=True) print("daemon snapshot", flush=True) executable = sh(ROOT / "test/snapshot-daemon.sh", base / "daemon").strip() print("web build", flush=True) sh(*web_build(base / "dist")) for name in ("alpha", "beta"): workspace(base / "ws" / name)
home = base / "seed" shutil.rmtree(home, ignore_errors=True) home.mkdir() env = {**os.environ, **daemon_env(home, executable, os.getpid())} with ExitStack() as cleanup: fake, url = fake_model(env) cleanup.callback(stop_process, fake) provider = { "extension": "openai", "baseUrl": url, "apiKey": "ux", "model": PROFILE, "protocol": "chat_completions", } (home / "config.json").write_text( json.dumps({"providers": {PROFILE: provider}, "active": PROFILE}) ) (home / "extensions.json").write_text(json.dumps(OFFLINE)) daemon = Daemon(home, env) cleanup.callback(daemon.stop) daemon.start() for name, where, messages in CHATS: session = daemon.chat(base / "ws" / where) for message in messages: daemon.say(session, message) daemon.name(session, name) print("seeded", name, flush=True) print(home)
if __name__ == "__main__": main()