From 52a967889c7b37fbf5d8bedafe2caff2155afa44 Mon Sep 17 00:00:00 2001 From: "nekomimi.pet" Date: Thu, 15 Oct 2026 04:53:46 -0400 Subject: [PATCH] add request mail and role metadata primitives --- priv/python/albedo_plugins/agents.py | 10 ++ priv/python/albedo_plugins/mail.py | 18 ++++ robot-docs/agents.md | 6 ++ src/albedo/daemon/family.gleam | 27 ++++++ src/albedo/daemon/mail.gleam | 91 ++++++++++++++++++- .../migrations/conversation_columns.gleam | 1 + .../harness/extensions/agents/extension.gleam | 33 ++++++- .../harness/extensions/mail/extension.gleam | 19 +++- 8 files changed, 199 insertions(+), 6 deletions(-) diff --git a/priv/python/albedo_plugins/agents.py b/priv/python/albedo_plugins/agents.py index 20623a3d2..990b7bb57 100644 --- a/priv/python/albedo_plugins/agents.py +++ b/priv/python/albedo_plugins/agents.py @@ -52,6 +52,7 @@ class Agent: id: str name: str + role: str | None depth: int parent: "Agent | None" = None running: bool | None = None @@ -167,6 +168,7 @@ def _agent(raw: dict) -> Agent: return Agent( id=raw["id"], name=raw["name"], + role=raw.get("role"), depth=raw["depth"], parent=_agent(parent) if isinstance(parent, dict) else None, running=raw.get("running"), @@ -223,6 +225,14 @@ class Agents: 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.""" diff --git a/priv/python/albedo_plugins/mail.py b/priv/python/albedo_plugins/mail.py index 99f9635e2..9bd2f72a2 100644 --- a/priv/python/albedo_plugins/mail.py +++ b/priv/python/albedo_plugins/mail.py @@ -41,6 +41,24 @@ class Mail: cast(dict, await host("mail.submit", {"to": target.strip(), "body": body})) ) + @hook.reported("mail.request", {"to": "to", "body": "body"}) + async def request(self, to: object, body: str) -> Receipt: + """Send a request; the recipient owes a reply until sending any letter back.""" + target = getattr(to, "id", to) + if ( + not isinstance(target, str) + or not target.strip() + or not isinstance(body, str) + ): + raise TypeError("mail.request(to, body) takes a target and string body") + return Receipt( + cast(dict, await host("mail.request", {"to": target.strip(), "body": body})) + ) + + async def open(self) -> Record: + """Return {owed, awaiting} open request summaries.""" + return Record(cast(dict, await host("mail.open", {}))) + def read(self, *_: object, **__: object) -> None: raise AttributeError( "there is no mail.read: letters to you arrive in your conversation as blocks" diff --git a/robot-docs/agents.md b/robot-docs/agents.md index 1b549db36..bf37767e1 100644 --- a/robot-docs/agents.md +++ b/robot-docs/agents.md @@ -90,3 +90,9 @@ and their deadlines count wall time after the program starts. ## deletion failures Direct parent deletion requires a successful child lookup. Tree deletion collects the child-first walk before deleting any session. A failed lookup returns an error and leaves the sessions intact. A failure during deletion still reports how many sessions were already deleted. + +## requests, roles, and peers + +`await mail.request(to, body)` creates a request; the recipient owes the sender until it sends any letter. `await mail.open()` returns bounded `owed` and `awaiting` entries. `await agents.set_role(text, id=None)` stores optional trimmed metadata for workspace views; it is not prompt context. + +Peers are root sessions started with `await agents.start(task, name, model, cwd=None, role=None)`. They have no family parent and do not count against child limits. The starter alone may cancel or close its peers. Session snapshots expose role, provenance, pinned state, and open request counts. diff --git a/src/albedo/daemon/family.gleam b/src/albedo/daemon/family.gleam index 478bb4684..c0c9424f7 100644 --- a/src/albedo/daemon/family.gleam +++ b/src/albedo/daemon/family.gleam @@ -141,6 +141,33 @@ pub fn valid_name(name: String) -> Result(Nil, String) { } } +/// Read the optional free-form role metadata. +pub fn role(db: store.Store, session: String) -> Result(String, String) { + store.read( + db, + "SELECT role FROM sessions WHERE id=?", + [sqlight.text(session)], + decode.field(0, decode.string, decode.success), + ) + |> result.map(fn(rows) { list.first(rows) |> result.unwrap("") }) +} + +pub fn set_role( + db: store.Store, + session: String, + value: String, +) -> Result(Nil, String) { + let value = string.trim(value) + case string.length(value) <= 512 { + False -> Error("role is at most 512 characters") + True -> + store.write(db, "UPDATE sessions SET role=? WHERE id=?", [ + sqlight.text(value), + sqlight.text(session), + ]) + } +} + pub fn get(db: store.Store, session: String) -> Result(Option(Member), String) { store.read(db, members("WHERE session=?"), [sqlight.text(session)], decoder()) |> result.map(fn(found) { list.first(found) |> option.from_result }) diff --git a/src/albedo/daemon/mail.gleam b/src/albedo/daemon/mail.gleam index d14cae6e3..bf4229f0f 100644 --- a/src/albedo/daemon/mail.gleam +++ b/src/albedo/daemon/mail.gleam @@ -25,6 +25,8 @@ import sqlight pub type Kind { /// The brief a parent hands a child it spawned. Task + /// A request that must be answered by the recipient. + RequestLetter /// Anything one agent says to another. Message /// A child's answer. `unreviewed` marks one the daemon forwarded because the @@ -67,7 +69,7 @@ CREATE TABLE IF NOT EXISTS mail ( recipient TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE, sender TEXT REFERENCES sessions(id) ON DELETE SET NULL, sender_name TEXT NOT NULL, - kind TEXT NOT NULL CHECK(kind IN ('task','message','result','unreviewed','webhook')), + kind TEXT NOT NULL CHECK(kind IN ('task','request','message','result','unreviewed','webhook')), body TEXT NOT NULL, created_at INTEGER NOT NULL, delivered_at INTEGER, @@ -94,6 +96,7 @@ pub fn initialise(db: store.Store) -> Result(Nil, String) { pub fn kind_name(kind: Kind) -> String { case kind { Task -> "task" + RequestLetter -> "request" Message -> "message" Answer(False) -> "result" Answer(True) -> "unreviewed" @@ -104,6 +107,7 @@ pub fn kind_name(kind: Kind) -> String { fn parse_kind(name: String) -> Result(Kind, Nil) { case name { "task" -> Ok(Task) + "request" -> Ok(RequestLetter) "message" -> Ok(Message) "result" -> Ok(Answer(False)) "unreviewed" -> Ok(Answer(True)) @@ -134,7 +138,7 @@ pub fn parent_request_in( [parent, ..] -> store.rows( db, - "SELECT id,substr(body,1,512) FROM mail WHERE recipient=? AND sender=? AND kind IN ('task','message') AND delivered_at IS NOT NULL ORDER BY created_at DESC,id DESC LIMIT 1", + "SELECT id,substr(body,1,512) FROM mail WHERE recipient=? AND sender=? AND kind IN ('task','request','message') AND delivered_at IS NOT NULL ORDER BY created_at DESC,id DESC LIMIT 1", [sqlight.text(recipient), sqlight.text(parent)], { use id <- decode.field(0, decode.string) @@ -372,7 +376,7 @@ pub fn owes_reply( ) -> Result(Bool, String) { store.read( db, - "SELECT (SELECT max(delivered_at) FROM mail WHERE recipient=?1 AND sender=?2 AND kind IN ('task','message')), (SELECT max(created_at) FROM mail WHERE recipient=?2 AND sender=?1)", + "SELECT (SELECT max(delivered_at) FROM mail WHERE recipient=?1 AND sender=?2 AND kind IN ('task','request','message')), (SELECT max(created_at) FROM mail WHERE recipient=?2 AND sender=?1)", [sqlight.text(child), sqlight.text(parent)], { use asked <- decode.field(0, decode.optional(decode.int)) @@ -475,6 +479,16 @@ pub fn receipt_json(receipt: Receipt) -> json.Json { ]) } +/// Send a request that the recipient owes until it sends any letter back. +pub fn request( + db: store.Store, + from: String, + to: String, + body: String, +) -> Result(Receipt, String) { + send_kind(db, from, to, body, RequestLetter) +} + /// One agent writes to another: `to` is "parent", a session id, or a name in /// the sender's family. The letter is stored first, so it arrives even when /// the hand-off below cannot happen now. @@ -483,6 +497,16 @@ pub fn send( from: String, to: String, body: String, +) -> Result(Receipt, String) { + send_kind(db, from, to, body, Message) +} + +fn send_kind( + db: store.Store, + from: String, + to: String, + body: String, + kind: Kind, ) -> Result(Receipt, String) { use address <- result.try(family.resolve(db, from, to)) use letter <- result.try(post( @@ -491,7 +515,7 @@ pub fn send( address.session, Some(from), family.name_of(db, from), - Message, + kind, body, )) let status = case deliver(letter) { @@ -502,6 +526,65 @@ pub fn send( Ok(Receipt(letter.id, address.session, address.name, status)) } +/// Open requests this session owes and requests it sent without a reply. +pub fn open_json( + db: store.Store, + session: String, +) -> Result(json.Json, String) { + let row = fn(recipient: String, sender: String) { + store.read( + db, + "SELECT sender,substr(body,1,512),created_at FROM mail WHERE recipient=? AND sender=? AND kind='request' AND delivered_at IS NOT NULL ORDER BY created_at DESC,id DESC LIMIT 1", + [sqlight.text(recipient), sqlight.text(sender)], + { + use sender <- decode.field(0, decode.string) + use body <- decode.field(1, decode.string) + use since <- decode.field(2, decode.int) + decode.success( + json.object([ + #("session", json.string(sender)), + #("name", json.string(family.name_of(db, sender))), + #("letter", json.string(body)), + #("since", json.int(since)), + ]), + ) + }, + ) + } + use owed <- result.try(store.read( + db, + "SELECT DISTINCT sender FROM mail WHERE recipient=? AND sender IS NOT NULL AND kind='request' AND delivered_at IS NOT NULL", + [sqlight.text(session)], + decode.field(0, decode.string, decode.success), + )) + use awaiting <- result.try(store.read( + db, + "SELECT DISTINCT recipient FROM mail WHERE sender=? AND kind='request' AND delivered_at IS NOT NULL", + [sqlight.text(session)], + decode.field(0, decode.string, decode.success), + )) + let owed = + list.fold(owed, [], fn(found, sender) { + case owes_reply(db, session, sender), row(session, sender) { + Ok(True), Ok([item, ..]) -> [item, ..found] + _, _ -> found + } + }) + let awaiting = + list.fold(awaiting, [], fn(found, recipient) { + case owes_reply(db, recipient, session), row(recipient, session) { + Ok(True), Ok([item, ..]) -> [item, ..found] + _, _ -> found + } + }) + Ok( + json.object([ + #("owed", json.array(owed, fn(x) { x })), + #("awaiting", json.array(awaiting, fn(x) { x })), + ]), + ) +} + /// Hand a stored letter to its recipient's actor now. Ok(True) means it waits /// in the recipient's queue behind a running turn. An error leaves the letter /// for the dispatcher, woken at once, so senders do not need to retry. diff --git a/src/albedo/daemon/migrations/conversation_columns.gleam b/src/albedo/daemon/migrations/conversation_columns.gleam index 4bfe6fdb3..6814e7000 100644 --- a/src/albedo/daemon/migrations/conversation_columns.gleam +++ b/src/albedo/daemon/migrations/conversation_columns.gleam @@ -39,6 +39,7 @@ pub fn apply(db: sqlight.Connection) -> Result(Nil, String) { #("family_revision", "INTEGER NOT NULL DEFAULT 0"), #("deletion_id", "TEXT"), #("context_window", "INTEGER"), + #("role", "TEXT NOT NULL DEFAULT ''"), ]), ) use _ <- result.try( diff --git a/src/albedo/harness/extensions/agents/extension.gleam b/src/albedo/harness/extensions/agents/extension.gleam index d0df72dd7..b8c5004b1 100644 --- a/src/albedo/harness/extensions/agents/extension.gleam +++ b/src/albedo/harness/extensions/agents/extension.gleam @@ -26,7 +26,7 @@ import gleam/result import gleam/string const instructions = - "Agents are sessions you spawn to work in parallel; every call is async. agents.self is your handle (id, name, depth, parent). Call await agents.models() once before spawning; other providers appear as provider/model, and selecting one routes the child through that provider. Then child = await agents.self.spawn(task, name=\"scout\", model=, deliverable=None, evidence_bar=None, falsifier=None): it returns as soon as the child exists, never with its answer. Answers arrive later as in your conversation and start your next turn, so spawn independent children back to back and end your turn instead of waiting; never sleep or poll. Talk with await mail.submit(child, text). await agents.self.children() and siblings() return live snapshots (running, closed). running=False means no active turn; a new child may still be waiting for its kernel and have no transcript yet. It does not prove spawn failed; wait for its mail rather than cancelling it on that snapshot. await child.cancel() stops its turn, and child.cancel(tree=True) the turns of everything beneath it; await agents.cancel_all(tree=True) stops every child you have, and their descendants, in one call, so use it when the user says to stop the swarm; await child.close() when you are done with it keeps its messages and files and frees its kernel. await agents.get(to) returns a live handle for \"parent\", a family name, or any session id. On any handle, await h.messages(seq=0, offset=0, limit=4000) reads a page of that session's messages from row seq on (content, next_offset) and await h.search_messages(pattern) finds rows by seq: any session may read any other, so you can see what a child or another session did without waiting for mail. await agents.sessions(query=\"\", cwd=None, limit=20, offset=0) lists every session, most recently active first, as snapshots that also carry cwd, model, last_active, and matches; with a query it keeps sessions whose title or name contains it or whose messages do, and matches holds up to 3 of each one's newest matching rows as {seq, preview} to read with messages(seq=...). cwd keeps one directory. Only the user deletes agents: if one should go, ask them. Children nest at most 3 deep and 12 open per parent; mail any session by id instead of nesting to reach it. Children share your workspace, so give two children the same files only if one only reads." + "Agents are sessions you spawn to work in parallel; every call is async. A lead session can keep a few long-lived peers for distinct areas, reusing useful context and starting fresh when context is unrelated; the right set depends on the project. agents.self is your handle (id, name, depth, parent). Call await agents.models() once before spawning; other providers appear as provider/model, and selecting one routes the child through that provider. Then child = await agents.self.spawn(task, name=\"scout\", model=, deliverable=None, evidence_bar=None, falsifier=None): it returns as soon as the child exists, never with its answer. Answers arrive later as in your conversation and start your next turn, so spawn independent children back to back and end your turn instead of waiting; never sleep or poll. Talk with await mail.submit(child, text). await agents.self.children() and siblings() return live snapshots (running, closed). running=False means no active turn; a new child may still be waiting for its kernel and have no transcript yet. It does not prove spawn failed; wait for its mail rather than cancelling it on that snapshot. await child.cancel() stops its turn, and child.cancel(tree=True) the turns of everything beneath it; await agents.cancel_all(tree=True) stops every child you have, and their descendants, in one call, so use it when the user says to stop the swarm; await child.close() when you are done with it keeps its messages and files and frees its kernel. await agents.get(to) returns a live handle for \"parent\", a family name, or any session id. On any handle, await h.messages(seq=0, offset=0, limit=4000) reads a page of that session's messages from row seq on (content, next_offset) and await h.search_messages(pattern) finds rows by seq: any session may read any other, so you can see what a child or another session did without waiting for mail. await agents.sessions(query=\"\", cwd=None, limit=20, offset=0) lists every session, most recently active first, as snapshots that also carry cwd, model, last_active, and matches; with a query it keeps sessions whose title or name contains it or whose messages do, and matches holds up to 3 of each one's newest matching rows as {seq, preview} to read with messages(seq=...). cwd keeps one directory. Only the user deletes agents: if one should go, ask them. Children nest at most 3 deep and 12 open per parent; mail any session by id instead of nesting to reach it. Children share your workspace, so give two children the same files only if one only reads." pub fn extension() -> extension.Extension { extension.Extension( @@ -239,6 +239,29 @@ fn dispatch( Error( "only the user deletes agents, because deleting loses the child's work. Ask them; they can delete it from the session browser. close() keeps everything and frees its kernel.", ) + "agents.set_role" -> { + use role <- result.try(text(args, "role")) + let target = + decode.run( + args, + decode.optional_field( + "id", + None, + decode.optional(decode.string), + decode.success, + ), + ) + |> result.unwrap(None) + |> option.unwrap(session) + use _ <- result.try( + case target == session || ownable(db, session, target) { + True -> Ok(Nil) + False -> + Error("you can only set your own, a child, or a peer you started") + }, + ) + family.set_role(db, target, role) |> result.map(fn(_) { json.bool(True) }) + } "agents.progress" -> { use note <- result.try(text(args, "text")) case string.trim(note), string.length(note) > 512 { @@ -301,6 +324,13 @@ fn stop_each( }) } +fn ownable(db: store.Store, caller: String, target: String) -> Bool { + case family.get(db, target) { + Ok(Some(member)) -> member.parent == caller + _ -> False + } +} + fn own_child( db: store.Store, session: String, @@ -391,6 +421,7 @@ fn found_json(db: store.Store, found: sessions.Found) -> json.Json { json.object( list.append(status_fields(db, info.id, member), [ #("cwd", json.string(info.cwd)), + #("role", json.string(family.role(db, info.id) |> result.unwrap(""))), #("model", json.string(info.model)), #("last_active", json.nullable(info.last_assistant_at, json.int)), #( diff --git a/src/albedo/harness/extensions/mail/extension.gleam b/src/albedo/harness/extensions/mail/extension.gleam index f941f66b6..4a94f1fd8 100644 --- a/src/albedo/harness/extensions/mail/extension.gleam +++ b/src/albedo/harness/extensions/mail/extension.gleam @@ -16,7 +16,7 @@ pub fn extension() -> extension.Extension { ["python"], [ extension.ToolPlugin( - "await mail.submit(to, body) sends a letter as this session. `to` is \"parent\", the name of a child or sibling, an agent handle, or any session id; names outside your family do not resolve, so use the id. It returns a receipt (id, to, name, status): \"delivered\" was accepted by an idle recipient (its kernel may still be booting), \"queued\" waits behind its running turn, \"pending\" is stored and arrives once that session is running. There is no mail.read: letters to you arrive in your conversation as blocks. Bodies over 1 MiB fail; write big results to a file and send the path.", + "await mail.submit(to, body) sends a letter; await mail.request(to, body) sends a request that stays open until the recipient sends any letter back; await mail.open() returns {owed, awaiting}. `to` is \"parent\", the name of a child or sibling, an agent handle, or any session id; names outside your family do not resolve, so use the id. It returns a receipt (id, to, name, status): \"delivered\" was accepted by an idle recipient (its kernel may still be booting), \"queued\" waits behind its running turn, \"pending\" is stored and arrives once that session is running. There is no mail.read: letters to you arrive in your conversation as blocks. Bodies over 1 MiB fail; write big results to a file and send the path.", [], ["mail"], [ @@ -37,6 +37,23 @@ fn handle( args: decode.Dynamic, ) -> Result(json.Json, #(String, String)) { case method { + "mail.request" -> { + let decoder = { + use to <- decode.field("to", decode.string) + use body <- decode.field("body", decode.string) + decode.success(#(to, body)) + } + case decode.run(args, decoder) { + Ok(#(to, body)) -> + mail.request(db, session, to, body) + |> result.map(mail.receipt_json) + |> result.map_error(fn(m) { #("invalid", m) }) + Error(_) -> + Error(#("invalid", "mail.request(to, body) takes two strings")) + } + } + "mail.open" -> + mail.open_json(db, session) |> result.map_error(fn(m) { #("invalid", m) }) "mail.submit" -> { let decoder = { use to <- decode.field("to", decode.string) -- knotmirror 0.0.1