Something went wrong. Try again.
small gleam coding and (not yet) persistent agent daemon with a detachable cli forked from okami.mom/albedo
Something went wrong. Try again.
21 kB · 551 lines
Python
at main
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552"""agents: spawn children, look up any session and read its messages, cancelor close your own children.Talking is mail.submit. Spawn returns once the child exists; its answerarrives later as mail and starts your next turn."""
from __future__ import annotations
import asyncioimport osimport timefrom dataclasses import dataclass, fieldfrom typing import cast
import albedo_resourcesfrom albedo_api import Host, PythonApi, Record, nested_recordfrom albedo_plugins import hook, runfrom albedo_plugins.worktrees import Worktree, _worktree
host: Host_models_seen = False_last_progress = 0.0
async def _act(method: str, args: dict[str, object]) -> object: """A host call that changes another session, reported to the hooks.""" return await hook.around(method, args, lambda given: host(method, given))
class MessagePage(Record): """page.content and page["content"] both work; next_offset is None at the end."""
seq: int offset: int content: str next_offset: int | None
class MessageMatches(Record): """matches.rows is a list of {seq, kind, preview}; read one with messages(seq=...)."""
pattern: str offset: int count: int next_offset: int | None rows: list[dict]
@dataclass(frozen=True)class Agent: """A handle to one agent. `running` and `closed` are set on snapshots from get(), children(), siblings(), and sessions(); None on handles that were not looked up. `cwd`, `model`, `last_active` (unix seconds of its last answer), and `matches` are set only on snapshots from sessions(). `worktree` is the Worktree the agent runs in, or None; closing the agent never removes it. `running=False` does not rule out a task waiting for kernel preparation."""
id: str name: str role: str | None started_by: str | None depth: int parent: "Agent | None" = None running: bool | None = None closed: bool | None = None cwd: str | None = None model: str | None = None last_active: int | None = None matches: list[dict] | None = field(default=None, compare=False) worktree: Worktree | None = None
async def spawn( self, task: str, *, name: str, model: str, effort: str | None = None, deliverable: str | None = None, evidence_bar: str | None = None, falsifier: str | None = None, verifier: str | None = None, cyber_access: str | None = None, worktree: Worktree | bool = False, ) -> "Agent": """Start a child with `task`. Returns at once; its answer comes as mail. `worktree=True` runs it in a fresh worktree of your repository, a Worktree runs it in that one; see child.worktree.""" if self.id != agents.self.id: raise PermissionError( "only agents.self.spawn(...) starts children: you spawn your own" ) for label, value in (("task", task), ("name", name), ("model", model)): if not isinstance(value, str) or not value.strip(): raise TypeError(f"{label} must be a non-empty str") if effort is not None and (not isinstance(effort, str) or not effort.strip()): raise TypeError("effort must be a non-empty str") # The flag dies with the kernel a rest replaces, so a model from the # list still spawns. if not _models_seen and not _listed(model, await _offered()): raise RuntimeError( "call await agents.models() first and pick a model from it" ) if verifier is not None and ( not isinstance(verifier, str) or not verifier.strip() ): raise TypeError("verifier must be a non-empty str") brief = _brief( task, name=name, deliverable=deliverable, evidence_bar=evidence_bar, falsifier=falsifier, verifier=verifier, ) payload: dict[str, object] = {"task": brief, "name": name, "model": model} if effort is not None: payload["effort"] = effort.strip().lower() if verifier is not None: payload["verifier"] = verifier.strip() if cyber_access is not None: if cyber_access != "daybreak_blue": raise ValueError("cyber_access must be daybreak_blue or None") payload["cyber_access"] = cyber_access if (wanted := _worktree_arg(worktree)) is not None: payload["worktree"] = wanted return _agent(cast(dict, await _act("agents.spawn", payload)))
async def children(self) -> list["Agent"]: if self.id != agents.self.id: raise PermissionError( "children() lists your own: use agents.self.children()" ) return [_agent(item) for item in cast(list, await host("agents.children", {}))]
async def siblings(self) -> list["Agent"]: if self.id != agents.self.id: raise PermissionError( "siblings() lists your own: use agents.self.siblings()" ) return [_agent(item) for item in cast(list, await host("agents.siblings", {}))]
async def cancel(self, *, tree: bool = False) -> bool: """Stop this child's running turn; it keeps its session and work. With `tree=True` its own children, and theirs, are stopped too. True when a turn was running.""" stopped = await _act("agents.cancel", {"id": self.id, "tree": tree}) return bool(cast(list, stopped))
async def switch(self, model: str) -> Record: """Return {model: "provider/model", pending: bool} for an owned child's switch. A running step finishes first; the next request uses the new model. A second switch replaces the pending one. Invalid models or incompatible history are refused now; a later projection failure keeps the old model and mails you. The saved reasoning choice is preserved. An explicit effort unsupported by the new model is refused; inherit follows the profile, and default follows the model default. New-session defaults are unchanged. """ if not isinstance(model, str) or not model.strip(): raise TypeError("model must be a non-empty str") return Record( cast(dict, await _act("agents.switch", {"id": self.id, "model": model})) )
async def set_verifier(self, command: str | None) -> bool: """Replace this child's verifier command, or clear it with None. Only its parent may; a cleared verifier stops gating at once, and the child is told.""" if command is not None and ( not isinstance(command, str) or not command.strip() ): raise TypeError("verifier must be a non-empty str or None") if command is not None and len(command.strip()) > 4096: raise ValueError("verifier is at most 4096 characters") payload = { "id": self.id, "command": None if command is None else command.strip(), } return bool(await _act("agents.set_verifier", payload))
async def close(self) -> bool: """Done with this child: stop it, keep its messages and files, free its kernel. Returns True after kernel cleanup succeeds. A cleanup error leaves the child closed; repeat close to reconcile. A timeout can leave cleanup pending. Its worktree, if any, is kept: remove it with worktrees.remove().""" wt = self.worktree closed = bool(await _act("agents.close", {"id": self.id})) if wt is not None: print( f"worktree {wt.id} ({wt.path}) will not be deleted automatically; " f"call await worktrees.remove({wt.id!r}) to delete it." ) return closed
async def messages( self, seq: int = 0, *, through: int | None = None, offset: int = 0, limit: int = 4000, ) -> MessagePage: """A page of this session's messages as text from row `seq` on, or through row `through`, so `messages(n, through=n)` reads exactly row n. `offset` and `limit` count characters, not rows (at most 8000). Any session may read any other.""" return MessagePage( cast( dict, await host( "agents.messages", { "id": self.id, "seq": seq, "through": through, "offset": offset, "limit": limit, }, ), ) )
async def search_messages( self, pattern: str, *, limit: int = 10, offset: int = 0, after_seq: int | None = None, before_seq: int | None = None, ) -> MessageMatches: """This session's message rows containing `pattern`, case-insensitively, oldest first; `after_seq` and `before_seq` search only the rows after and before a seq. A search of your own session does not count the call that runs it.""" return MessageMatches( cast( dict, await host( "agents.search_messages", { "id": self.id, "pattern": pattern, "limit": limit, "offset": offset, "after_seq": after_seq, "before_seq": before_seq, }, ), ) )
async def delete(self) -> None: await _act("agents.delete", {"id": self.id})
def _agent(raw: dict) -> Agent: parent = raw.get("parent") return Agent( id=raw["id"], name=raw["name"], role=raw.get("role"), started_by=raw.get("started_by"), depth=raw["depth"], parent=_agent(parent) if isinstance(parent, dict) else None, running=raw.get("running"), closed=raw.get("closed"), cwd=raw.get("cwd"), model=raw.get("model"), last_active=raw.get("last_active"), matches=raw.get("matches"), worktree=_worktree(wt) if isinstance(wt := raw.get("worktree"), dict) else None, )
def _worktree_arg(worktree: object) -> str | bool | None: """What the host is sent for `worktree=`: None for no worktree, True for a fresh one, or a Worktree's id.""" if worktree is False or worktree is None: return None if worktree is True: return True if isinstance(worktree, Worktree): return worktree.id raise TypeError( "worktree must be a Worktree or bool; use await worktrees.create(...), " "await worktrees.get(...), or worktree=True" )
def _directory(cwd: str | None) -> str: """A cwd filter as sessions store it: absolute, or "" for every directory.""" return os.path.abspath(os.path.expanduser(cwd)) if cwd else ""
async def _processes(owners: list[dict]) -> dict[str, list[dict]]: """Live processes by session id. Jobs this kernel has just started are spawned first, so a run() on the previous line is already visible.""" pending = [job._spawn() for job in list(run.active.values()) if job.process is None] await asyncio.gather(*pending, return_exceptions=True) own_jobs = { job.id: group.pgid for job in run.active.values() if (group := job.claim()) } return await albedo_resources.collect(owners, agents.self.id, own_jobs)
def _brief( task: str, *, name: str, deliverable: str | None, evidence_bar: str | None, falsifier: str | None, verifier: str | None = None,) -> str: parts = [f"Task:\n{task.strip()}"] if deliverable: parts.append( f"Deliverable: {deliverable.strip()}\nWrite it to {deliverable.strip()}.partial and rename it " "into place when finished, so a reader never sees half of it." ) if evidence_bar: parts.append(f"Evidence bar:\n{evidence_bar.strip()}") if falsifier: parts.append(f"Falsifier:\n{falsifier.strip()}") if verifier: parts.append( f'Verifier:\n`{verifier.strip()}` must exit 0 before `mail.submit("parent", ...)` or turn completion will succeed.' ) parts.append( 'When done: await mail.submit("parent", <short summary, with paths to anything large>).' ) return "\n\n".join(parts)
async def _offered(cyber_access: str | None = None) -> list[str]: arguments: dict[str, object] = ( {"cyber_access": cyber_access} if cyber_access else {} ) models = [ str(model) for model in cast(list, await host("agents.models", arguments)) ] if all("/" in model for model in models): return models # An older daemon lists bare ids for the caller's own profile. provider = cast(dict, await host("agents.self", {})).get("provider") return [ model if "/" in model or not provider else f"{provider}/{model}" for model in models ]
def _listed(model: str, models: list[str]) -> bool: """Whether `model` names one of `models`, bare names included.""" return any(model in (offered, offered.partition("/")[2]) for offered in models)
class Agents: self: Agent
async def models(self, *, cyber_access: str | None = None) -> list[str]: """Canonical choices; daybreak_blue filters to advertised account-scoped Blue models.""" if cyber_access not in (None, "daybreak_blue"): raise ValueError("cyber_access must be daybreak_blue or None") global _models_seen _models_seen = True return await _offered(cyber_access)
async def start( self, task: str, name: str, model: str, *, cwd: str | None = None, role: str | None = None, worktree: Worktree | bool = False, effort: str | None = None, ) -> "Agent": """Start a root peer owned by this session; its first letter is a request. `worktree=True` runs it in a fresh worktree of the repository at `cwd` (default yours), a Worktree runs it in that one.""" if not all( isinstance(value, str) and value.strip() for value in (task, name, model) ): raise TypeError("task, name, and model must be non-empty strings") if effort is not None and (not isinstance(effort, str) or not effort.strip()): raise TypeError("effort must be a non-empty str") payload: dict[str, object] = { "task": task, "name": name, "model": model, "cwd": _directory(cwd), "role": role or "", } if effort is not None: payload["effort"] = effort.strip().lower() if (wanted := _worktree_arg(worktree)) is not None: payload["worktree"] = wanted return _agent(cast(dict, await _act("agents.start", payload)))
async def cancel_all(self, *, tree: bool = True) -> list[str]: """Stop the running turn of every one of your children, and with `tree=True` (the default) everything beneath them. Returns the ids of the sessions that were running. They keep their sessions and work.""" stopped = await _act("agents.cancel_all", {"tree": tree}) return list(cast(list, stopped))
async def set_role(self, text: str, id: str | None = None) -> bool: """Set trimmed free-form role metadata on self, a child, or started peer.""" if not isinstance(text, str) or len(text.strip()) > 512: raise TypeError("role must be at most 512 characters") return bool( await _act("agents.set_role", {"role": text, "id": id or agents.self.id}) )
async def progress(self, text: str) -> bool: """A short status (≤512 chars) the agents view shows without starting a turn. At most one per 10 seconds; returns False when throttled.""" global _last_progress if not isinstance(text, str) or not text.strip(): raise TypeError("progress(text) takes a non-empty str") now = time.monotonic() if now - _last_progress < 10: return False _last_progress = now return bool(await host("agents.progress", {"text": text.strip()}))
async def get(self, to: object) -> Agent: """A live snapshot of "parent", a child or sibling by name, an agent handle, or any session id, resolved the way mail.submit resolves it.""" target = getattr(to, "id", to) if not isinstance(target, str) or not target.strip(): raise TypeError( 'agents.get(to): to is "parent", a name, a session id, or an agent handle' ) return _agent(cast(dict, await host("agents.get", {"to": target.strip()})))
async def sessions( self, query: str = "", *, cwd: str | None = None, limit: int = 20, offset: int = 0, ) -> list[Agent]: """Every session, most recently active first (at most 100 per call). A `query` keeps those whose title or name contains it, or whose messages do, case-insensitively; each snapshot's `matches` then holds up to 3 of its newest matching rows as {seq, preview}, to read with messages(seq=...). Your own messages are not searched. With `cwd`, only sessions opened in that directory.""" found = await host( "agents.sessions", { "query": query, "cwd": _directory(cwd), "limit": limit, "offset": offset, }, ) return [_agent(item) for item in cast(list, found)]
def spawn(self, *_: object, **__: object) -> None: raise AttributeError( "spawn lives on your handle: await agents.self.spawn(task, name=..., model=...)" )
class Resources: async def query( self, query: str = "", *, process: str | None = None, cwd: str | None = None, session: object = None, ) -> Record: """What every session's processes use, with session ids. `query` keeps processes whose name, command, or owning session name/id contains the text, case-insensitively; `process` matches only the process name or command; `cwd` keeps those running in that directory or below it (a relative or remote path matches as a substring). `session` is "self", "parent", a session name or id, or a handle, and limits the answer to that session; without it only sessions with a matching process are listed. Returns {sessions, processes, session_count, process_count, cpu_percent, memory_bytes, rss_bytes, total}; every figure counts the matching processes. Only processes on this machine are seen.""" arguments: dict[str, object] = {} if session is not None: target = getattr(session, "id", session) if not isinstance(target, str) or not target.strip(): raise TypeError( 'session is "self", "parent", a name, a session id, or an agent handle' ) arguments["to"] = target.strip() owners = cast(list, await host("agents.resources", arguments)) found = await _processes(owners) q = query.lower() proc = process.lower() if process else "" wanted = _directory(cwd) sessions, matching = [], [] for owner in owners: owner_text = f"{owner['name']}\n{owner['id']}".lower() kept = [ p for p in found.get(owner["id"], []) if (not q or q in f"{owner_text}\n{p['name']}\n{p['command']}".lower()) and (not proc or proc in f"{p['name']}\n{p['command']}".lower()) and _in_directory(p["cwd"], cwd, wanted) ] if kept or session is not None: sessions.append(albedo_resources.session_record(owner, kept)) matching += kept total = { "session_count": len(sessions), **albedo_resources.totals(matching), } return nested_record( { "sessions": sessions, "processes": matching, **total, "total": total, } )
def _in_directory(actual: str, given: str | None, normalized: str) -> bool: if not given: return True return ( actual == normalized or actual.startswith(normalized.rstrip("/") + "/") or given in actual )
resources = Resources()agents = Agents()
async def setup(api: PythonApi) -> dict[str, object]: global host host = api.host agents.self = _agent(cast(dict, await host("agents.self", {}))) return { "agents": agents, "resources": resources, "Agent": Agent, "AgentsError": api.HostError, }