"""A fresh interpreter waiting for one kernel identity, never reused.""" from __future__ import annotations import importlib import io import json import os import sys import albedo_bundle import albedo_cells import albedo_proc # Import trusted packaged modules only; setup needs the adopting session's host. PREIMPORT = ( "run work mail agents paperclips artifacts files memory commands remote browser web_search skills hook" ).split() def preimport() -> str: """Import the packaged plugins; returns the bundle digest they came from.""" bundle = albedo_bundle.digest() for name in PREIMPORT: importlib.import_module("albedo_plugins." + name) return bundle def main(bundle: str | None = None) -> None: """Serve one adoption over stdio. `bundle` is the digest a forked child's already imported code came from; adoption refuses a bundle edited since.""" # The daemon starts this directly; a kernel never shares its session. if os.getpgrp() != os.getpid(): os.setsid() if bundle is None: bundle = preimport() print( json.dumps( { "ready": bundle, "pid": os.getpid(), "pgid": os.getpgrp(), "leader": albedo_proc.leader_token(os.getpid()), } ), flush=True, ) line = sys.stdin.buffer.readline(1024 * 1024 + 1) if not line: return if len(line) > 1024 * 1024 or not line.endswith(b"\n"): raise ValueError("invalid spare adoption frame") spec = json.loads(line) if bundle != albedo_bundle.digest(): raise ValueError("spare bundle changed before adoption") if not isinstance(spec, dict) or not all( isinstance(spec.get(key), str) for key in ("cwd", "run_dir", "modules", "token") ): raise ValueError("invalid spare adoption identity") environment = spec.get("environment") if not isinstance(environment, dict) or not all( isinstance(key, str) and isinstance(value, str) for key, value in environment.items() ): raise ValueError("invalid spare adoption environment") os.makedirs(spec["run_dir"], mode=0o700, exist_ok=True) os.chdir(spec["cwd"]) os.environ.clear() os.environ.update(environment) # The ordinary detached handshake still reads the secret from stdin. sys.stdin = io.TextIOWrapper(io.BytesIO((spec["token"] + "\n").encode())) sys.argv = [sys.argv[0], "--run", spec["run_dir"], spec["modules"]] # Match cold kernels for imports of __main__ and pickled cell definitions. sys.modules["__main__"] = albedo_cells albedo_proc.set_name("kernel") albedo_cells.main() if __name__ == "__main__": main()