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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296"""CLI attachment and startup must preserve an independently owned real daemon."""
import hashlibimport jsonimport osimport ptyimport selectimport socketimport statimport termiosimport timeimport unittest
from build_identity_support import PackageBuildfrom inspect_support import Inspectionfrom harness import Albedo, Provider, alive, exclusive, operation_id, python, text
def direct_start(daemon): daemon.start_launcher() daemon.await_ready()
def runtime_limits(app): expression = ( "Limits = [Call(erlang, system_info, [Key]) " "|| Key <- [process_limit, port_limit, schedulers_online]], " "io:put_chars(json:encode(Limits))" ) return json.loads(Inspection(app).evaluate(expression, timeout=20))
class TerminalCommand: def __init__(self, app, *arguments): self.master, slave = pty.openpty() termios.tcsetwinsize(slave, (24, 100)) self.process = app.daemon.start_cli( *arguments, stdin=slave, stdout=slave, stderr=slave ) os.close(slave) self.output = b""
def prompt(self, timeout=10): deadline = time.monotonic() + timeout while time.monotonic() < deadline: readable, _, _ = select.select( [self.master], [], [], max(0, deadline - time.monotonic()) ) if readable: try: chunk = os.read(self.master, 65536) except OSError as error: raise AssertionError( "CLI exited before restart prompt: " + self.output.decode(errors="replace") ) from error self.output += chunk if b"\x1b[6n" in chunk: os.write(self.master, b"\x1b[1;1R") if b"\x1b[c" in chunk: os.write(self.master, b"\x1b[?1;2c") if b"[y/N]" in self.output or b"[Y/n]" in self.output: return raise AssertionError( "CLI did not offer a restart: " + self.output.decode(errors="replace") )
def answer(self, value): os.write(self.master, (value + "\r").encode()) result = self.process.wait(timeout=20) os.close(self.master) return result
# exclusive: owns daemon startup and restart behavior@exclusiveclass LifecycleTest(unittest.TestCase): def test_a_launcher_run_without_the_cli_matches_it(self): # The shipped launcher, started directly as a service manager would: # a launch that cannot publish its discovery record exits and leaves # the home free for the next one, which then uses the default home # (mode 0700, daemon.json 0600), a generated token, and the CLI's VM # limits, and honours ALBEDO_TOKEN and ERL_FLAGS on restart. failed = {}
def start(daemon): blocked = daemon.home / "daemon.json" blocked.mkdir() process = daemon.start_launcher() failed["exit"] = process.wait(timeout=20) failed["pid"] = process.pid blocked.rmdir() direct_start(daemon)
def prepare(app): app.home = app.daemon.home = app.root / "user-home" / ".albedo" app.home.mkdir(mode=0o755) app.env.pop("ALBEDO_HOME") app.env.pop("ALBEDO_TOKEN", None) app.env["ALBEDO_INSPECT"] = "1" app.daemon.boot_action = start
with Albedo(prepare=prepare) as app: self.assertNotEqual(failed["exit"], 0) self.assertNotEqual(app.connection["pid"], failed["pid"]) direct = dict(app.connection) self.assertGreaterEqual(len(direct["token"]), 32) self.assertEqual(stat.S_IMODE(app.home.stat().st_mode), 0o700) self.assertEqual( stat.S_IMODE((app.home / "daemon.json").stat().st_mode), 0o600 ) connection = socket.create_connection( ("127.0.0.1", direct["port"]), timeout=5 ) with connection: connection.sendall( f"GET /server HTTP/1.1\r\nHost: localhost:{direct['port']}\r\nConnection: close\r\n\r\n".encode() ) self.assertIn(b"401", connection.recv(1024).split(b"\r\n", 1)[0]) direct_limits = runtime_limits(app) session = app.session() app.prompt(session, "independent daemon is usable").close() app.idle(session) self.assertIn( "ok", [ part["text"] for entry in app.history(session)["items"] for part in entry["content"] if part["kind"] == "text" ], ) self.assertEqual(app.connection, direct) app.restart() self.assertNotEqual(app.connection["pid"], direct["pid"]) self.assertNotEqual(app.connection["token"], direct["token"]) self.assertEqual(runtime_limits(app), direct_limits) app.restart( prepare=lambda fixture: fixture.env.update( ERL_FLAGS=fixture.env["ERL_FLAGS"] + " +P 131072 +Q 32768", ALBEDO_TOKEN="operator-chosen-authentication-token", ) ) self.assertEqual(runtime_limits(app)[:2], [131072, 32768]) self.assertEqual( app.connection["token"], "operator-chosen-authentication-token" ) with app.api("/server") as response: self.assertEqual(response.status, 200) self.assertEqual(json.load(response)["pid"], app.connection["pid"])
def test_an_upgrade_offered_for_a_package_rebuild_keeps_sessions_and_effects( self, ): # The CLI compares its build's digest with the daemon's. An unchanged # build attaches without asking; a rebuilt dependency (the root's own # files unchanged) is offered as an upgrade, and yes drains the old # daemon into the new build. An idle session keeps its history, and # one running an uncertain tool recovers it once: its input committed, # its turn abandoned with a restart note, its effect applied once. fixture = {} builds = []
def prepare(app): builds.append(PackageBuild(app))
def script(request): messages = request["messages"] if any( "daemon restart" in str(message.get("content", "")) for message in messages ): return text("recovered after upgrade") if messages[-1]["role"] == "tool": return text("tool finished") if "apply an effect" in str(messages[-1].get("content", "")): return python( "from pathlib import Path\nimport threading\n" f"with Path({str(fixture['effect'])!r}).open('a') as effect:\n" " effect.write('effect applied\\n')\n" " effect.flush()\n" "threading.Event().wait(60)" ) return text("ok")
provider = Provider(script) self.addCleanup(provider.close) with Albedo(provider, prepare=prepare) as app: build = builds[0] fixture["effect"] = app.workspace / "effect" previous = dict(app.connection) session = app.session() app.prompt(session, "keep this session through the package upgrade").close() app.idle(session) history = app.history(session)["items"] expression = "io:put_chars(Call('albedo_bytes@build_probe', value, []))" self.assertEqual(Inspection(app).evaluate(expression), "before") # A terminal would prompt for an unknown identity. With the same # complete identity it exits without waiting for an answer. unchanged = TerminalCommand(app, "daemon") self.assertEqual(unchanged.process.wait(timeout=20), 0) os.close(unchanged.master) self.assertEqual( json.loads((app.home / "daemon.json").read_text()), previous )
# Another session's tool has applied its effect and still runs. working = app.session() operation = operation_id() app.api( f"/sessions/{working}/inputs/{operation}", {"kind": "message", "text": "apply an effect then wait"}, method="PUT", ).close() deadline = time.monotonic() + 20 while ( not fixture["effect"].exists() or fixture["effect"].read_text() != "effect applied\n" ): if time.monotonic() > deadline: app._fail("tool never published its external effect") time.sleep(0.02) self.assertEqual( json.load(app.api(f"/sessions/{working}?tail=0"))["status"]["phase"], "running", )
root_files = { str(path.relative_to(build.output)): hashlib.sha256( path.read_bytes() ).hexdigest() for path in (build.output / "albedo").rglob("*") if path.is_file() } build.rebuild("after") self.assertEqual( root_files, { str(path.relative_to(build.output)): hashlib.sha256( path.read_bytes() ).hexdigest() for path in (build.output / "albedo").rglob("*") if path.is_file() }, ) self.assertEqual(Inspection(app).evaluate(expression), "before") self.assertEqual( json.load(app.api("/server"))["digest"], previous["digest"] ) terminal = TerminalCommand(app, "daemon") terminal.prompt() self.assertEqual(terminal.answer("y"), 0) app.daemon._refresh() self.assertNotEqual(app.connection["pid"], previous["pid"]) self.assertNotEqual(app.connection["digest"], previous["digest"]) self.assertFalse(alive(previous["pid"])) self.assertEqual(Inspection(app).evaluate(expression), "after") self.assertEqual(app.history(session)["items"], history)
app.idle(working) receipt = json.load(app.api(f"/sessions/{working}/inputs/{operation}")) self.assertEqual(receipt["delivery"], "committed") self.assertEqual(receipt["turn"]["state"], "abandoned") entries = app.history(working)["items"] self.assertEqual( sum(entry["input_id"] == operation for entry in entries), 1 ) self.assertTrue( any( entry["kind"] == "note" and any( part["kind"] == "text" and "restart" in part["text"] for part in entry["content"] ) for entry in entries ) ) self.assertTrue( any( part["kind"] == "text" and part["text"] == "recovered after upgrade" for entry in entries for part in entry["content"] ) ) self.assertEqual(fixture["effect"].read_text(), "effect applied\n")
app.prompt(session, "continue after upgrade").close() app.idle(session) unchanged = TerminalCommand(app, "daemon") self.assertEqual(unchanged.process.wait(timeout=20), 0) os.close(unchanged.master) self.assertEqual( json.loads((app.home / "daemon.json").read_text())["pid"], app.connection["pid"], )