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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450"""Mail and agent handles between two daemons after a move.
The source daemon's PATH holds a loopback ssh, as in move_test, whose host`vassago` runs commands with ALBEDO_HOME set to the peer daemon's home anda login shell that reads no profile. The `down` switch makes every ssh failas an unreachable host does (a laptop's peer asleep). There is no ssh theother way: the target never reaches the source, as with a laptop.
A child of a session moves to vassago; its parent stays here. Letters go toit through the source's pusher, and its letters to "parent" come backthrough the long-poll the source keeps open."""
import jsonimport osimport shleximport shutilimport sqlite3import subprocessimport sysimport tempfileimport timeimport unittestfrom contextlib import closingfrom pathlib import Path
from harness import ( Albedo, Provider, exclusive_class, operation_id, peer_daemon, prompt_text, python, text,)
FAKE_SSH = """#!/bin/shquery=while [ $# -gt 0 ]; do case "$1" in -o) shift 2 ;; -G) query=1; shift ;; -*) shift ;; *) break ;; esacdonetarget=$1shift[ -n "$query" ] && exit 0if [ -e {down} ]; then echo "ssh: connect to host $target port 22: Network is unreachable" >&2 exit 255fiexec env -i HOME={home} ALBEDO_HOME="$(cat {hosts}/"$target")" PATH={path} SHELL={login} /bin/sh -c "$*""""
# The host's login shell. It sources no profile: /etc/profile may replace PATH# (NixOS's does), dropping the fake host's python3 for the system's or none.LOGIN_SHELL = """#!/bin/sh[ "$1" = -l ] && shiftexec /bin/sh "$@""""
ELSEWHERE = "which this daemon can't reach; ask from there"
def wait_for(predicate, timeout=60, message="condition not met"): """`message` may be a function, read when the wait gives up.""" deadline = time.monotonic() + timeout while time.monotonic() < deadline: result = predicate() if result: return result time.sleep(0.05) raise AssertionError(message() if callable(message) else message)
def rows(home, sql, *args): with closing(sqlite3.connect(Path(home) / "albedo.sqlite", timeout=10)) as db: return db.execute(sql, args).fetchall()
class Forwarding(unittest.TestCase): """A parent here and its child moved to vassago, with what the tests need to drive both daemons. It has no tests of its own."""
remote_home: Path hosts: Path down: Path
def setUp(self): self.addCleanup(self.recover)
def prepare(app): root = Path(tempfile.mkdtemp(prefix="host-", dir=app.root)) self.remote_home = app.root / "remote-home" self.hosts = root / "hosts" self.down = root / "down" self.hosts.mkdir() local, remote = app.root / "local-bin", root / "remote-bin" for directory in (self.remote_home, local, remote): directory.mkdir(exist_ok=True) os.symlink(shutil.which("python3") or sys.executable, remote / "python3") login = local / "loginsh" login.write_text(LOGIN_SHELL) login.chmod(0o755) path = app.daemon.env["PATH"] ssh = local / "ssh" ssh.write_text( FAKE_SSH.format( down=self.down, hosts=self.hosts, home=self.remote_home, path=shlex.quote(f"{remote}{os.pathsep}{path}"), login=login, ) ) ssh.chmod(0o755) app.daemon.env["PATH"] = f"{local}{os.pathsep}{path}"
self.provider = Provider(lambda _request: text("done")) self.addCleanup(self.provider.close) self.app = Albedo(self.provider, protocol="responses", prepare=prepare) self.app.__enter__() self.addCleanup(self.app.__exit__, None, None, None)
def target_prepare(peer): # The source's profile, with its key: the moved child runs there. for name in ("config.json", "creds.json"): if (self.app.home / name).exists(): shutil.copy(self.app.home / name, peer.home / name)
self.target = peer_daemon("forward-target", prepare=target_prepare) (self.hosts / "vassago").write_text(str(self.target.home)) destination = Path(tempfile.mkdtemp(prefix="dest-", dir=self.remote_home))
self.parent = self.app.session() self.app.prompt(self.parent, "hello").close() self.app.idle(self.parent) self.child = operation_id() self.app.api( f"/sessions/{self.child}", { "kind": "child", "parent_id": self.parent, "address": "kid", "name": "kid", "initial_input_id": operation_id(), "task": "wait for letters", }, method="PUT", headers={"If-None-Match": "*"}, ).close() self.app.idle(self.child, timeout=60) self.app.idle(self.parent, timeout=60)
transfer = operation_id() self.app.api( f"/sessions/{self.child}/move", {"transfer_id": transfer, "target": f"vassago:{destination}"}, ).close() move = wait_for( lambda: ( (move := self.read(transfer))["state"] in ("checklist", "active", "failed") and move ), 90, lambda: f"the move never reached its checklist: {self.read(transfer)}", ) self.assertEqual(move["state"], "checklist", move) with self.app.api(f"/transfers/{transfer}/finish", {}) as response: self.assertEqual(json.load(response)["state"], "active")
def recover(self): self.down.unlink(missing_ok=True)
def read(self, transfer): with self.app.api(f"/transfers/{transfer}") as response: return json.load(response)
def execute(self, daemon, session, source): """Runs one python cell in `session` on `daemon` (the app or the target) and answers the cell's tool result as text.""" marker = "forward cell " + operation_id() answer = self.provider.script
def dispatch(request): messages = request.get("messages", request.get("input", [])) if messages[-1].get("role") == "user" and prompt_text(request) == marker: return python(source) return answer(request)
self.provider.script = dispatch try: daemon.api( f"/sessions/{session}/inputs/{operation_id()}", {"kind": "message", "text": marker}, method="PUT", ).close() idle(daemon, session) finally: self.provider.script = answer with daemon.api(f"/sessions/{session}/history") as response: items = json.load(response)["items"] [cell] = [item for item in items if item["kind"] == "tool_result"][-1:] return json.dumps(cell)
def arrived(self, home, recipient, body): return rows( home, "SELECT id,sender,sender_name,created_at FROM mail WHERE recipient=? AND body=?", recipient, body, )
def idle(daemon, session, timeout=60): deadline = time.monotonic() + timeout while time.monotonic() < deadline: with daemon.api(f"/sessions/{session}?tail=0") as response: snapshot = json.load(response) if snapshot["status"]["phase"] == "idle" and not snapshot["pending_inputs"]: return snapshot time.sleep(0.05) raise AssertionError(f"session did not settle: {snapshot}")
# exclusive: the daemon's PATH holds the loopback ssh, and a test kills its# relays@exclusive_classclass MoveForwardTests(Forwarding): def test_a_letter_to_a_moved_session_arrives_there_once(self): cell = self.execute( self.app, self.parent, f"r = await mail.submit({self.child!r}, 'hello over there')\n" "print('STATUS', r.status, r.forwarding)", ) self.assertIn("STATUS queued queued for vassago", cell) [(letter, sender, name, _)] = wait_for( lambda: self.arrived(self.target.home, self.child, "hello over there"), 30, "the letter never reached the target", ) # Its sender lives on the source: kept with where it lives. self.assertIsNone(sender) [(remote, host)] = rows( self.target.home, "SELECT sender,host FROM mail_remote WHERE letter=?", letter, ) self.assertEqual(remote, self.parent) self.assertTrue(host) wait_for( lambda: rows( self.app.home, "SELECT 1 FROM mail_outbox WHERE id=? AND delivered_at IS NOT NULL", letter, ), 30, "the source never settled the letter", ) # A resend (an ack the relay dropped) is taken again without a copy. with self.target.api( "/mail/forwarded", { "origin": "source", "host": host, "letters": [ { "id": letter, "recipient": self.child, "sender": self.parent, "sender_name": name, "kind": "message", "body": "hello over there", } ], }, ) as response: [ack] = json.load(response)["acks"] self.assertEqual(ack, {"id": letter, "error": None, "retry": False}) self.assertEqual( len(self.arrived(self.target.home, self.child, "hello over there")), 1 ) # And the moved child reads it there. idle(self.target, self.child) with self.target.api(f"/sessions/{self.child}/history") as response: self.assertIn("hello over there", response.read().decode())
def test_a_letter_waits_while_the_target_is_out_of_reach(self): self.down.touch() self.execute( self.app, self.parent, f"await mail.request({self.child!r}, 'while you were away')", ) wait_for( lambda: rows( self.app.home, "SELECT 1 FROM mail_peers WHERE unreachable_since IS NOT NULL", ), 60, "the source never found the target out of reach", ) cell = self.execute( self.app, self.parent, "print('AWAITING', [a['forwarding'] for a in (await mail.open())['awaiting']])", ) self.assertIn("AWAITING ['queued for vassago, unreachable since ", cell) self.assertEqual( self.arrived(self.target.home, self.child, "while you were away"), [] ) self.down.unlink() wait_for( lambda: self.arrived(self.target.home, self.child, "while you were away"), 60, "the letter never arrived once the target was back", )
def test_a_moved_child_writes_to_its_parent_here(self): self.execute( self.app, self.parent, f"await mail.request({self.child!r}, 'report back')" ) wait_for(lambda: self.arrived(self.target.home, self.child, "report back"), 30) idle(self.target, self.child) cell = self.execute( self.target, self.child, "import time\n" "sent = time.time()\n" "r = await mail.submit('parent', 'reporting from vassago')\n" "print('SENT', sent, r.status, r.forwarding)", ) self.assertIn("SENT", cell) sent = float(cell.split("SENT ", 1)[1].split(" ", 1)[0]) [(_, sender, _, created)] = wait_for( lambda: self.arrived(self.app.home, self.parent, "reporting from vassago"), 30, "the parent never got the letter", ) self.assertEqual(sender, self.child) latency = created / 1000 - sent print(f"collect latency {latency:.3f}s", file=sys.stderr) self.assertLess(latency, 5) # The answer closes the request on the side that opened it. idle(self.app, self.parent) cell = self.execute( self.app, self.parent, "print('AWAITING', (await mail.open())['awaiting'])" ) self.assertIn("AWAITING []", cell)
# The long-poll survives its connection dying: the source opens it # again and the next letter still comes. subprocess.run(["pkill", "-f", "albedo_transfer_relay"], check=False) self.execute( self.target, self.child, "await mail.submit('parent', 'after the drop')" ) wait_for( lambda: self.arrived(self.app.home, self.parent, "after the drop"), 60, "the parent never got the letter sent after the connection dropped", )
def test_handles_reach_a_moved_session_and_not_the_other_way(self): cell = self.execute( self.app, self.parent, f"h = await agents.get({self.child!r})\n" "page = await h.messages()\n" "print('READ', 'wait for letters' in str(page))\n" "print('CANCELLED', await h.cancel())", ) self.assertIn("READ True", cell) self.assertIn("CANCELLED", cell) self.assertNotIn("Error", cell)
cell = self.execute( self.target, self.child, "p = await agents.get('parent')\n" "try:\n" " await p.messages()\n" "except AgentsError as error:\n" " print('REFUSED', error)\n" "try:\n" " await p.cancel()\n" "except AgentsError as error:\n" " print('REFUSED', error)", ) self.assertEqual(cell.count(ELSEWHERE), 2, cell)
# exclusive: restarts the source daemon with its timers 3600 times faster@exclusive_classclass MoveForwardBounceTests(Forwarding): def test_a_letter_bounces_after_a_day_out_of_reach(self): self.down.touch() cell = self.execute( self.app, self.parent, f"r = await mail.request({self.child!r}, 'anyone there?')\n" "print('STATUS', r.status, r.forwarding)", ) self.assertIn("STATUS queued queued for vassago", cell) [(sent,)] = rows( self.app.home, "SELECT created_at FROM mail_outbox WHERE body='anyone there?'", )
# A day is 24 s from here; python's kernel does not live at that # speed, so the request went out first. def faster(app): app.daemon.env["ALBEDO_TEST_TIME_SCALE"] = "3600" app.daemon.env["ALBEDO_SCHEDULE_TICK_MS"] = "60000"
self.app.restart(prepare=faster) [(sender, body, bounced)] = wait_for( lambda: rows( self.app.home, "SELECT sender,body,created_at FROM mail WHERE recipient=? AND body LIKE 'not delivered:%'", self.parent, ), 90, lambda: ( "the letter never bounced: " + repr(rows(self.app.home, "SELECT * FROM mail_outbox")) ), ) self.assertGreaterEqual(bounced - sent, 24_000) self.assertEqual(sender, self.child) self.assertIn("vassago was out of reach for a day", body)
# The bounce answers the request: the sender awaits nothing. self.app.restart( prepare=lambda app: app.daemon.env.pop("ALBEDO_TEST_TIME_SCALE") ) idle(self.app, self.parent) cell = self.execute( self.app, self.parent, "print('AWAITING', (await mail.open())['awaiting'])" ) self.assertIn("AWAITING []", cell)
if __name__ == "__main__": unittest.main()