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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135"""Forward framed HTTP calls from a source daemon to this host's daemon.
A source daemon moving a session here runs this over ssh, from the bundlethe host probe staged (robot-docs/workspaces.md, "moving a session toanother daemon"). It reads ``daemon.json`` from ``$ALBEDO_HOME`` (default``~/.albedo``) and calls the loopback daemon it names with that token, sothe token never leaves this host.
Every frame is a 4-byte big-endian length and its payload, on stdin andstdout. The relay first writes a hello, ``{"home", "port"}`` or``{"error"}`` when no daemon is recorded here. Each call is two frames, aJSON header ``{"method", "path", "content_type", "timeout"}`` (``timeout``in seconds, optional) and the raw body; each answer is twoframes, ``{"status"}`` (or ``{"error"}`` when the daemon did not answer)and the raw response body. stdin closing ends the relay."""
from __future__ import annotations
import http.clientimport jsonimport osimport structimport sysfrom typing import BinaryIO
TIMEOUT = 60 # seconds a call to the local daemon may take, unless it says
def read_frame(stream: BinaryIO) -> bytes | None: header = stream.read(4) if len(header) < 4: return None (length,) = struct.unpack(">I", header) payload = stream.read(length) return payload if len(payload) == length else None
def write_frame(stream: BinaryIO, payload: bytes) -> None: stream.write(struct.pack(">I", len(payload)) + payload) stream.flush()
def write_json(stream: BinaryIO, value: object) -> None: write_frame(stream, json.dumps(value).encode())
def record(home: str) -> tuple[int, str] | str: """The port and token of this home's daemon, or why there are none.""" path = os.path.join(home, "daemon.json") try: with open(path, encoding="utf-8") as handle: data = json.load(handle) except FileNotFoundError: return f"no albedo daemon has run here ({path} is missing)" except (OSError, ValueError) as error: return f"{path} is unreadable: {error}" port, token = data.get("port"), data.get("token") if not isinstance(port, int) or not isinstance(token, str): return f"{path} names no daemon port and token" return port, token
class Daemon: """One keep-alive connection to the loopback daemon, reopened on failure."""
def __init__(self, port: int, token: str) -> None: self.port = port self.token = token self.connection: http.client.HTTPConnection | None = None
def call( self, method: str, path: str, content_type: str, body: bytes, timeout: float ) -> tuple[int, bytes]: for attempt in (1, 2): if self.connection is None: self.connection = http.client.HTTPConnection( "127.0.0.1", self.port, timeout=timeout ) self.connection.timeout = timeout if self.connection.sock is not None: self.connection.sock.settimeout(timeout) headers = {"Authorization": f"Bearer {self.token}"} if content_type: headers["Content-Type"] = content_type try: self.connection.request(method, path, body or None, headers) response = self.connection.getresponse() return response.status, response.read() except (OSError, http.client.HTTPException): self.connection.close() self.connection = None # A kept-alive connection the daemon closed fails once. if attempt == 2: raise raise AssertionError("unreachable")
def main() -> int: source, sink = sys.stdin.buffer, sys.stdout.buffer home = os.environ.get("ALBEDO_HOME") or os.path.expanduser("~/.albedo") found = record(home) if isinstance(found, str): write_json(sink, {"error": found}) return 0 daemon = Daemon(*found) write_json(sink, {"home": home, "port": found[0]}) while True: header = read_frame(source) body = read_frame(source) if header is None or body is None: return 0 call = json.loads(header) try: status, answer = daemon.call( call["method"], call["path"], call.get("content_type", ""), body, float(call.get("timeout") or TIMEOUT), ) except (OSError, http.client.HTTPException) as error: write_json( sink, {"error": f"the albedo daemon here is not answering: {error}"}, ) write_frame(sink, b"") continue write_json(sink, {"status": status}) write_frame(sink, answer)
if __name__ == "__main__": sys.exit(main())