Open source Grok Bot alternative, Bring your own agent and subscription: message Claude Code, Codex, Gemini CLI, Cursor, Copilot and 40+ AI agents as bots on your own computer, from iPhone, Mac, Windows, Linux or terminal. Agent-agnostic and free. Also a Muse and Dots alternative. Built in Rust.
Rust acpagent-client-protocolai-agentsai-assistantclaudeclaude-codecodexcoding-agentscursorgeminigemini-cligrok-bot-alternativeiosiphonelinuxmacosmcpopen-sourcerustself-hosted
feat(host): bots message each other without waiting
leepokaie8ccab5296ec
diff --git a/README.md b/README.mdindex 283a7b29..4e489013 100644--- a/README.md+++ b/README.md@@ -86,7 +86,7 @@ Host notifications → APNs worker (relay/) → iPhone- **Bots** have a name, a character avatar, standing instructions, an agent backend, a project folder and a permission policy. Each bot has **one persistent chat**, where you can reply to any message; the agent sessions underneath are an implementation detail (resumed with `session/load`, restarted with *New session*).- **Group chats** hold several bots and you. Each message starts a short room turn: the bots you @-mention (or everyone) reply one at a time, each in its own session, and can react to each other, up to 3 rounds. See [group chats and replies](docs/features/groups-and-replies.md).-- **Bots can ask each other for help.** Tell one “ask Reviewer to check these changes.” The built-in `team` MCP server lets it discover your other visible bots and wait for a reply. Requests appear in both chats; each recipient keeps its own agent, folder and approvals. Native subagents stay under the coding agent's control. See [bot collaboration](docs/features/bot-collaboration.md).+- **Bots can ask each other for help.** Tell one “ask Reviewer to check these changes.” The built-in `team` MCP server lets it discover your other visible bots and message one; the reply comes back to it as a new turn, and it answers you then. Requests appear in both chats; each recipient keeps its own agent, folder and approvals. Native subagents stay under the coding agent's control. See [bot collaboration](docs/features/bot-collaboration.md).- **The chat only shows what matters**: your messages, each turn's final reply, approval cards and notices. Every tool call, diff, plan and thought is one tap away in *Full conversation*. While a bot works, its row shows what it's doing right now.- **Agents are detected automatically**: the host hydrates PATH from your login shell (plus Homebrew, ~/.local/bin, nvm, bun, volta, asdf, mise, pnpm…), finds every harness you have installed, and prefers its native ACP mode. Anything else in the official [ACP registry](https://agentclientprotocol.com/registry) can be picked too — Codync fetches it on first use (npx, uvx or a checksummed binary).- **codync-host** (Rust, macOS, Windows and Linux) runs on your computer. It speaks the [Agent Client Protocol](https://agentclientprotocol.com) to each agent, keeps transcripts in SQLite, and serves the phone. Every change carries a global `rev`, so the phone reconnects with `since: rev` and never misses anything.diff --git a/docs/architecture/conversation-runtime.md b/docs/architecture/conversation-runtime.mdindex 9ffcb4c0..d450587b 100644--- a/docs/architecture/conversation-runtime.md+++ b/docs/architecture/conversation-runtime.md@@ -5,6 +5,6 @@- **Agent processes**: a bot's agent starts on its first message and keeps its sessions loaded between messages. A session unused for 30 minutes is closed (agents with `session/close`; a routine run's session as soon as the run ends), and once all of them are idle the agent stops with its process group, as it does right after a routine run when no other session is open; the next message starts it again and loads the session (`agent/bot/lifecycle.rs`). Nothing is released mid-turn or while a queue, approval or request waits. Agents that can't load sessions stay, and so do agents with something running detached in a session of its own, like a dev server from Claude Code's shell tool (stopping the agent would orphan it); MCP servers don't count, even in a process group of their own as Codex starts them. Codex frees a closed session's thread and its MCP servers within about a minute, but codex-acp never closes the thread it titles each new session in, so that thread's MCP servers from the user's Codex config stay until the agent stops ([codex-acp#628](https://github.com/agentclientprotocol/codex-acp/issues/628)). Windows agents are never stopped for idleness: without process groups a dev server can't be told from an MCP server, and stopping ends the whole tree.- **Group chats and replies** are host features every client drives through the same methods (`send` with `replyTo`, `createBot {kind: group}`); clients never route, parse mentions or build quotes themselves. A group is a roster row whose members answer in their own sessions (Grok Bot's room turns); a reply stays in its chat and session, its quote read before its text: [docs/features/groups-and-replies.md](../features/groups-and-replies.md).- **A session that fails** with an internal error its agent gives no category (JSON-RPC `-32603` without `data.errorKind`) is closed right after the turn, when the agent can close and load sessions: Claude's adapter otherwise answers every later prompt on it with "The Claude Agent session has ended". The next message loads it again and the conversation carries on (`acp::may_end_session`).-- Bot collaboration: built-in `team` MCP (`chat/team.rs`) lists visible bots and asks one for a reply or sends it an independent message through its actor queue. Asks are separate turns, cycle-checked and cancellable; native subagents stay with the harness. See [docs/features/bot-collaboration.md](../features/bot-collaboration.md).+- Bot collaboration: built-in `team` MCP (`chat/team.rs`) lists visible bots and sends one a request through its actor queue (`message_bot`); nothing waits, and the reply comes back to the sender as a turn of its own in its main chat. Requests and replies are separate turns, bounded by the chain's hop count; native subagents stay with the harness. See [docs/features/bot-collaboration.md](../features/bot-collaboration.md).- **Context & memory**: frozen instruction snapshot per session + compaction epoch (Claude gets it as a system prompt), profile edits as update blocks, memory in the host (a layer shared by all bots and one per bot, written by the user, the bots' tools and dreaming), busy-time messages folded into one turn, interrupted turns resumed: [docs/features/context-and-memory.md](../features/context-and-memory.md).- **Chat shows only**: user messages, the bot's messages (`data.final`: each `send_message` call from the built-in `chat` MCP, Grok Bot's way; a turn that sent none falls back to its last text, unless it reacted to the user's message instead or passed), permission cards, notices. Nothing streams into a bubble; narration, thoughts, tool calls, plans are trace entries (Full conversation sheet): [docs/features/chat-messages.md](../features/chat-messages.md).diff --git a/docs/features/bot-collaboration.md b/docs/features/bot-collaboration.mdindex 5189a633..0087f572 100644--- a/docs/features/bot-collaboration.md+++ b/docs/features/bot-collaboration.md@@ -4,7 +4,7 @@ Create two or more bots normally, giving each a clear name, description, project> Ask Reviewer to inspect the changes in /path/to/project. Have it report bugs without editing files, then summarize its findings for me.-Every bot receives the built-in `team` MCP server. `list_bots` returns the other visible bots' IDs, descriptions, agents, folders and status. `ask_bot(botId, message)` sends a self-contained request and waits for the recipient's final text reply. The requesting bot incorporates that answer into its response to you. `message_bot(botId, message)` queues a request and returns immediately; the recipient reports to you in its own chat. The same tools work across ACP backends that support MCP servers.+Every bot receives the built-in `team` MCP server. `list_bots` returns the other visible bots' IDs, descriptions, agents, folders and status. `message_bot(botId, message)` queues a self-contained request and returns at once, so the sender never waits: it ends its turn (or keeps working) and the recipient's final reply comes back to it later as a new turn in its own chat, where it answers you. The same tools work across ACP backends that support MCP servers.The host records each exchange as one notice in both chats. Every client shows it as a compact row (centered in the apps, one ` · ` line in the terminal UI), "Messaged [avatar] Owen" in the sender's chat and "Message from [avatar] Egan" in the recipient's, with no request text. In a chat a run of consecutive exchanges with the same peer, in either direction, is one row, "3 messages with [avatar] Owen"; anything else the chat shows (a message, another notice, a card, an exchange with another peer) ends the run, trace entries do not, and the run is marked failed if any exchange failed. Only a failure is marked (danger color and a warning mark). Tapping the row opens a read-only "Egan ⇄ Owen" conversation sheet with the pair's whole history: author-labelled grey bubbles for each request and reply, time separators, "Waiting for Owen…" or the failure detail under a pending or failed exchange. It is laid out like the Full conversation sheet, with the pair as its title and an X to close. Tool details also remain in the trace. There is no additional team setup screen; a lead bot can set up the team itself (see Team management).@@ -26,7 +26,7 @@ They add one optional structured field:}```-`text` is the original request. Completed asks add `reply` (at most 4,000 bytes);+`text` is the original request. Completed requests add `reply` (at most 4,000 bytes);failures and cancellations add `detail`. The existing notice `status` determineswhether the exchange is pending, completed, failed or cancelled. The base noticeheading and rendered text remain unchanged for clients that display plain notices.@@ -43,47 +43,33 @@ the Control scope. Clients merge these with the live chat (the higher `rev` winsand keep the result in the sheet; it is never added to the chat mirror, so mainhistory paging is unaffected.-## Ask execution+## How a message runs-- Each bot still owns an ACP process (its main session, plus one per routine run) and runs one turn at a time. A busy recipient queues the request. Different bots can work concurrently.-- Requests have their own reply channel and never merge with user messages or another request. Contiguous user messages keep the existing batching behavior.-- An ask's final reply is addressed to the requesting bot. It appears in the request notice- and the recipient's trace, without a second bubble in the recipient's main chat. The recipient- returns the answer directly rather than sending another `message_bot` request back.-- The recipient uses its own folder, tools, memory and permission policy. Permission cards appear in its chat. The requesting bot's entire transcript is not copied; only the request is passed. Requests are not treated as user facts by the memory keeper.-- The host rejects self-delegation, duplicate outstanding requests to the same recipient, and direct or indirect wait cycles, including queued requests. Up to 64 requests can be outstanding host-wide.+- Each bot still owns an ACP process (its main session, plus one per routine run) and runs one turn at a time. A busy recipient queues the request. Different bots work concurrently, so a bot that messages several teammates has them work in parallel.+- `message_bot` returns `{requestId, status: "queued"}` as soon as the request is admitted. Nothing waits on another bot, so there are no wait cycles to guard against and no wait limit: the recipient takes as long as the work needs.+- Requests never merge with user messages or another request. Contiguous user messages keep the existing batching behavior.+- The recipient's final reply is addressed to the sender. It appears in both request notices (`botMessage.reply`) and the recipient's trace, without a bubble in the recipient's main chat; `send_message`, `send_file` and `message_bot` are refused in a request turn (a reply to a message sent from there would land in the recipient's own chat, and the sender would never get it). A recipient that needs another bot's help says so in its reply.+- The reply then reaches the sender's queue as a turn of its own in its main chat (`[Codync: Owen replied to your message_bot request <id> ("<request>").]`, quoting the first 1,000 bytes of the request, since the session taking the reply, the main one, may not be the one that sent it: a routine run's, or one replaced by a new session). Replies that arrive while the sender is busy are taken together in one turn. That turn's final reply is an ordinary message to you, with the usual "done" push; the request turn itself sends no push. A failed request comes back the same way (`couldn't finish …`), so the sender can tell you.+- A reply turn isn't the user speaking: memory doesn't take it as your words. If the sender wants another bot to have the answer, it messages that bot.+- The recipient uses its own folder, tools, memory and permission policy. Permission cards appear in its chat. The sender's transcript is not copied; only the request is passed. Requests are not treated as user facts by the memory keeper.+- In a group room turn `message_bot` is refused: the reply would land in the member's own chat, away from the room. Members @-mention each other there instead ([groups](groups-and-replies.md#how-a-group-answers-hostsrcchatgrouprs-grok-bots-design)).- Native Claude Code/Codex subagents remain managed by the harness. Codync does not turn them into permanent bots or override their delegation settings.-## Ask stops, failures and restart+The team tools add no task scheduler or isolated worktrees. Give bots explicit file ownership when they share a working directory.-- The wait limit is ten minutes, including queue and approval time. Failure is a tool error, not a fabricated successful reply. `ask_bot` is not automatically retried.-- Stopping the requesting bot cancels its outgoing requests. A queued request is removed; a running delegated turn's ACP process is stopped. Unrelated queued messages on the recipient remain. Stopping the recipient also releases its requesters once its turn stops.-- Deleting either bot cancels affected requests. Recipient startup failures, crashes, refusals and empty replies surface to the requester.-- Pending request notices are persisted with IDs and statuses. After host restart they become interrupted errors; delegated turns are not automatically replayed. Check partial work before retrying. Ordinary user turns retain their existing session-resume behavior.-- Completion push notifications come from the requesting bot; delegated replies do not send a second “done” push. Recipient permission requests still use the usual “needs you” notifications.+## Stops, failures and restart-`ask_bot` uses synchronous request/reply over MCP; neither tool adds a task scheduler or isolated worktrees. Give bots explicit file ownership when they share a working directory. Rebuild and restart the host to load the new built-in MCP server.+- Accepted requests survive the sender's completion, Stop, disconnection and deletion. Stop on the sender drops replies still queued for it; a deleted sender's replies are dropped (both notices still show the outcome).+- Stopping or deleting the recipient cancels its queued requests and stops running work; started work may have left partial changes. A cancellation the user caused doesn't wake the sender; its notices show it.+- Recipient startup failures, crashes, refusals and empty replies mark both notices failed and come back to the sender as a failed reply.+- Pending request notices are persisted with IDs and statuses. After host restart they become interrupted errors; request turns are not automatically replayed. Check partial work before retrying. There is no automatic retry. Ordinary user turns and running reply turns retain their existing session-resume behavior.+- A reply still queued for a busy sender lives only in memory: a host restart drops it, and the sender never relays it. Both notices are already completed and keep the reply (`botMessage.reply`), so it stays readable in the conversation sheet.-## Independent messages+## Limits-`message_bot(botId, message)` queues a bot request and returns immediately, without waiting for a reply. The recipient reports to you in its own chat. Messages use the same queue as asks, run one turn at a time, and never merge with user messages or other requests. Both chats show bot-attributed notices rather than user messages. Up to 64 messages can be outstanding host-wide, with at most 16 from any one sender, separately from asks. Queued and running messages both count. A slot is freed when the recipient finishes, fails or cancels the request, or admission fails. Stopping, restarting or deleting the sender does not free slots for its already accepted messages.+The host rejects messages to the bot itself, to hidden or deleted bots, and empty or oversized (over 32,000 bytes) ones. Up to 64 messages can be outstanding host-wide, with at most 16 from any one sender. Queued and running messages both count. A slot is freed when the recipient finishes, fails or cancels the request, or admission fails. Stopping, restarting or deleting the sender does not free slots for its already accepted messages.-The recipient can use `send_message` for user-facing updates and its report. If it sends none,-its final text becomes the main-chat report. The request notice shows completion-status; it does not copy this user-facing report into a bot reply.--Each independent request includes reporting guidance, even when it reuses a-session that previously handled an ask. The ask's reply restrictions apply-only to that ask; later user turns and independent requests can report in-the recipient's chat normally.--Accepted messages survive sender completion, Stop, disconnection and deletion. Recipient Stop or deletion cancels queued messages and stops running work; started work may have left partial changes. Outcomes update both notices; failures mark them as failed. The recipient uses its normal completion notifications. Messages have no ask timeout or automatic retry and are not replayed after host restart.--Bot request chains can make at most eight handoffs. Both `message_bot` and-`ask_bot` carry the count into the recipient's turn, including queued work;-finishing an earlier request does not reset it. This bounds repeated A → B → A-messages even when few requests are outstanding. At the limit, the tool reports-an error without queuing more work. A new user turn starts a fresh allowance.+Bot request chains can make at most eight handoffs. A request turn messages no one, so a chain goes on only from reply turns: each reply carries the count into the sender's reply turn (the highest of the replies it takes), and finishing an earlier request does not reset it. This bounds repeated A → B → A messages even when few requests are outstanding. At the limit, the tool reports an error without queuing more work. A new user turn starts a fresh allowance.## Team management@@ -101,13 +87,13 @@ A bot made this way records its creator (`createdBy`, next to `createdAt`); clie## Code and verification-- `host/src/chat/team.rs`: discovery, request lifetime and persisted notices and structured conversation data.+- `host/src/chat/team.rs`: discovery, request lifetime, persisted notices, structured conversation data and the reply that goes back (`BotReply`, `reply_prompt`).- `host/src/store/entries.rs` (`bot_conversation`, `expire_pending`) and `host/src/api/bots.rs` (`botConversation`): the pair history and restart cleanup.- `host/src/tui/app/exchange.rs`, `manage/bot_chat.rs`, `view/bot_chat.rs`: the terminal client's row logic, keys and conversation sheet.-- `host/src/chat/team/requests.rs`: admission, wait graph, capacity and chain hop limit.-- `host/src/agent/bot/` (`queue.rs`, `turn.rs`): queue boundaries, recipient execution, completion and targeted cancellation.+- `host/src/chat/team/requests.rs`: admission, capacity and chain hop limit.+- `host/src/agent/bot/` (`queue.rs`, `turn.rs`): queue boundaries, recipient execution, completion and the sender's reply turn.- `host/src/mcp.rs`: the authenticated local MCP → HTTP bridge.-- `host/tests/team_e2e.rs`: a real host and MCP subprocess, with scripted ACP agents, covering discovery → delegation → recipient approval → reply → client sync. No paid provider calls.+- `host/tests/team_e2e.rs`: a real host and MCP subprocess, with scripted ACP agents, covering discovery → message → recipient approval → reply turn in the sender's chat → client sync, and the hop limit. No paid provider calls.- `host/src/chat/manage.rs` (+ `Cmd::Approve` in `agent/bot/updates.rs`): team management; `host/tests/manage_e2e.rs` walks an allowed `create_bot`, a denied `update_bot`, and cards that end when the turn stops or the agent cancels the call, through the real `manage` MCP process.Run `cargo test` and `cargo clippy --all-targets -- -D warnings` in `host/`.diff --git a/docs/features/chat-messages.md b/docs/features/chat-messages.mdindex 32afc0e0..f3a1928b 100644--- a/docs/features/chat-messages.md+++ b/docs/features/chat-messages.md@@ -22,12 +22,11 @@ it has no pointer tooltip or link-opening action.- File cards are separate final entries. Sharing a file preserves an intended final textreply; a files-only turn uses its filename for the completion summary. See[file attachments](file-attachments.md#files-from-a-bot).-- Group room turns, `ask_bot` requests and routines reject `send_message` and `send_file`: their reply is the- turn's last text, as before (`chat/group.rs`, `chat/team.rs`, `routines`).-- An `ask_bot` reply stays in the recipient's trace and the request notice; it does- not also become a message to the user. The requesting bot uses it to answer the user.- Independent `message_bot` turns report to the user in the recipient's main chat, through- `send_message` or the final-text fallback, and do not add that report to the request notice.+- Group room turns, bot requests (`message_bot`) and routines reject `send_message` and `send_file`: their reply+ is the turn's last text, as before (`chat/group.rs`, `chat/team.rs`, `routines`).+- A bot request's reply stays in the recipient's trace and the request notice; it does+ not also become a message to the user. It goes back to the requesting bot as a turn of its own in+ that bot's main chat, and that turn's reply is an ordinary message to the user.- The rules reach the agent twice: the MCP server's instructions, and the frozen instructionsnapshot (`chat/context.rs`).- The same server has `set_name {name}` and `set_instructions {instructions}` (`host/src/chat/profile.rs`): the@@ -35,7 +34,7 @@ it has no pointer tooltip or link-opening action.settings would, and a notice ("Renamed to …", "Instructions updated") shows it in the main chat. A name set thisway ends automatic naming. Its `save_skill` writes a skill for the bot, which the user can turn on for others([skills bots write](marketplace.md)).-- A bot-to-bot exchange (`ask_bot`, `message_bot`) is one compact notice row, "Messaged Owen" /+- A bot-to-bot exchange (`message_bot`) is one compact notice row, "Messaged Owen" /"Message from Egan". Its text lives only in the bot conversation sheet it opens; follow-upsare normal bubbles. Consecutive exchanges with the same peer in the main chat (eitherdirection, trace entries ignored) collapse into one "3 messages with Owen" row ([bot collaboration](bot-collaboration.md#notice-data)).diff --git a/docs/features/context-and-memory.md b/docs/features/context-and-memory.mdindex 1ebbfb13..01949f79 100644--- a/docs/features/context-and-memory.md+++ b/docs/features/context-and-memory.md@@ -180,8 +180,8 @@ Claude Code's own memory; the rules live in the `codync-mem` crate, and `chat/me## Turns- Messages sent while the agent works are folded into one next turn, joined by blank lines.-- Bot-to-bot requests occupy separate turns in the same queue; user messages are only folded together up to the next request. Requests never feed dreaming. See [bot collaboration](bot-collaboration.md).-- Delegated turns do not set the restart marker: their waiter disappears on restart. Pending delegation notices become interrupted errors instead of automatically replaying work.+- Bot-to-bot requests and the replies to them occupy separate turns in the same queue (replies waiting together are one turn); user messages are only folded together up to the next request or reply. Neither feeds dreaming. See [bot collaboration](bot-collaboration.md).+- A request turn (the recipient's) doesn't set the restart marker: its pending notices become interrupted errors instead of automatically replaying work. A reply turn is the sender's own chat turn and sets it, so it resumes like a user turn.- Stop sends `session/cancel`; an agent still running 15 seconds later is stopped (it resumes its session onthe next turn). `session/new`, `session/load` and `session/fork` get three minutes before the agent isstopped. Connector or computer changes restart an agent that can resume sessions before its next turn; onediff --git a/docs/features/groups-and-replies.md b/docs/features/groups-and-replies.mdindex e5b13633..b6ab406b 100644--- a/docs/features/groups-and-replies.md+++ b/docs/features/groups-and-replies.md@@ -45,10 +45,16 @@ quotes itself.## How a group answers (`host/src/chat/group.rs`, Grok Bot's design)- The user's message starts a *room turn* in the group: up to 3 rounds, 10 replies in all.-- Who answers each round: the members @-mentioned (full name, name without spaces, or first- word; `@all` / `@everyone`) or replied to since the user's last message, or everyone if none- is. A reply to a member's message counts like `@`-mentioning it. Members speak one at a- time; each round starts one member later.+- Who answers the first round: the members the user @-mentioned (full name, name without+ spaces, or first word; `@all` / `@everyone`) or replied to, or everyone if none is. A reply to+ a member's message counts like `@`-mentioning it.+- Who answers a later round: only the members another member @-mentioned in this room turn+ (a member's `@all` / `@everyone`: all the others) and who haven't spoken or been asked since+ (one that passed after seeing the mention isn't asked again). Nobody named,+ and the room turn ends after the round: a member brings a teammate in by naming it, and a+ `(pass)` costs no extra rounds. Members speak one at a time; each round starts one member later.+- `message_bot` is refused in a room turn (its reply would go to the member's own chat); members+ @-mention each other instead ([bot collaboration](bot-collaboration.md)).- A group's `description` ("About") tells its members what the room is for.- A member runs the turn in its **own main session** (its history is unified across chats),told who's in the room and what was said since it last spoke there, framed asdiff --git a/host/src/agent/bot/mod.rs b/host/src/agent/bot/mod.rsindex 71cc051d..2f58a5a2 100644--- a/host/src/agent/bot/mod.rs+++ b/host/src/agent/bot/mod.rs@@ -61,6 +61,8 @@ pub enum Cmd {text: String,},BotRequest(crate::chat::team::BotRequest),+ /// How a request this bot sent came out: a turn of its own, with any others that arrive meanwhile.+ BotReply(crate::chat::team::BotReply),/// `send_message` from the bot's `chat` MCP server: a message for the user, now.SendToUser {text: String,@@ -79,9 +81,6 @@ pub enum Cmd {cancelled: Arc<std::sync::atomic::AtomicBool>,reply: tokio::sync::oneshot::Sender<Result<()>>,},- CancelAsk {- id: String,- },/// Its turn in a group's room turn.Group(GroupTurn),/// The group's room turns stopped: drop its queued turns, stop a running one.@@ -114,6 +113,7 @@ enum Queued {text: String,},BotRequest(crate::chat::team::BotRequest),+ BotReply(crate::chat::team::BotReply),/// A compaction the host decided on (see `compaction`); `idle` while the user is away.Compact {idle: bool,@@ -172,6 +172,7 @@ pub fn spawn(hub: Arc<Hub>, base: BotConfig) -> BotHandle {turn: None,queue: VecDeque::new(),active_request: None,+ reply_hops: None,seg: Seg::None,tools: HashMap::new(),plan_entry: None,@@ -329,6 +330,8 @@ struct Actor {turn: Option<i64>,queue: VecDeque<Queued>,active_request: Option<crate::chat::team::BotRequest>,+ /// During a turn that takes bot replies: the hops of their chain (see `chat::team::BotReply`).+ reply_hops: Option<u8>,seg: Seg,tools: HashMap<String, String>,plan_entry: Option<String>,@@ -433,7 +436,7 @@ impl Actor {}}self.files.cancel();- self.hub.team.cancel_from(&self.cfg.id);+ self.hub.team.end_turn(&self.cfg.id);self.complete_request(Err(anyhow!("recipient shut down")), true);self.complete_group(Err(anyhow!("bot shut down")));if let Some(c) = self.conn.take() {diff --git a/host/src/agent/bot/queue.rs b/host/src/agent/bot/queue.rsindex bcc1807d..ae23af6c 100644--- a/host/src/agent/bot/queue.rs+++ b/host/src/agent/bot/queue.rs@@ -17,25 +17,12 @@ impl Actor {Cmd::RefreshTools => {self.tools_changed = true;}- Cmd::Routine(id) => {- self.queue.push_back(Queued::Routine(id));- if self.turn.is_none() {- self.next_in_queue(done_tx).await;- }- }- Cmd::Send { lane, entry_id, text } => {- self.queue.push_back(Queued::User { lane, entry_id, text });- if self.turn.is_none() {- self.next_in_queue(done_tx).await;- }- }+ Cmd::Routine(id) => self.enqueue(Queued::Routine(id), done_tx).await,+ Cmd::Send { lane, entry_id, text } => self.enqueue(Queued::User { lane, entry_id, text }, done_tx).await,Cmd::Group(turn) => {// The room asks again: this turn answers for any still waiting there.self.queue.retain(|q| !matches!(q, Queued::Group(g) if g.lane == turn.lane));- self.queue.push_back(Queued::Group(turn));- if self.turn.is_none() {- self.next_in_queue(done_tx).await;- }+ self.enqueue(Queued::Group(turn), done_tx).await;}Cmd::CancelGroup { chat } => {// Dropping a queued turn's reply tells the room it won't come.@@ -44,24 +31,8 @@ impl Actor {self.cancel_turn().await;}}- Cmd::BotRequest(ask) => {- self.queue.push_back(Queued::BotRequest(ask));- if self.turn.is_none() {- self.next_in_queue(done_tx).await;- }- }- Cmd::CancelAsk { id } => {- self.queue.retain(|q| !matches!(q, Queued::BotRequest(a) if a.expects_reply() && a.id == id));- if self.active_request.as_ref().is_some_and(|a| a.expects_reply() && a.id == id) {- self.hub.team.cancel_from(&self.cfg.id);- self.stop_requested = true;- // The request has expired. Kill only its process so a harness- // ignoring cooperative cancellation cannot block the queue.- if let Some(c) = self.conn.take() {- c.acp.kill().await;- }- }- }+ Cmd::BotRequest(request) => self.enqueue(Queued::BotRequest(request), done_tx).await,+ Cmd::BotReply(reply) => self.enqueue(Queued::BotReply(reply), done_tx).await,Cmd::SendToUser { text, reply } => {let _ = reply.send(self.send_to_user(text));}@@ -131,8 +102,16 @@ impl Actor {true}+ /// Queues `item`, and starts it right away when the bot is free.+ async fn enqueue(&mut self, item: Queued, done_tx: &mpsc::UnboundedSender<Done>) {+ self.queue.push_back(item);+ if self.turn.is_none() {+ self.next_in_queue(done_tx).await;+ }+ }+pub(super) async fn stop(&mut self) {- self.hub.team.cancel_from(&self.cfg.id);+ self.hub.team.end_turn(&self.cfg.id);if let Err(error) = self.hub.routines.cancel_queued(&self.hub.store, &self.cfg.id) {tracing::error!(error = format!("{error:#}"), "couldn't cancel queued routines");}@@ -219,22 +198,34 @@ impl Actor {continue;}Some(Queued::BotRequest(_)) => {- let Some(Queued::BotRequest(mut ask)) = self.queue.pop_front() else {- unreachable!("front is an ask")+ let Some(Queued::BotRequest(mut request)) = self.queue.pop_front() else {+ unreachable!("front is a bot request")};- if ask.reply_closed() {- continue;- }- let ids = [ask.entry_id.clone()];- let prompt = ask.prompt.clone();- ask.mark_started();- self.active_request = Some(ask);+ let ids = [request.entry_id.clone()];+ let prompt = request.prompt.clone();+ request.mark_started();+ self.active_request = Some(request);let result = self.start_turn(main.clone(), &ids, &prompt, false, done_tx).await;if let Err(e) = result {self.start_error(e, done_tx).await;}continue;}+ Some(Queued::BotReply(_)) => {+ // Replies that came in while the bot worked are one turn, as the user's messages are.+ let mut replies = Vec::new();+ while let Some(Queued::BotReply(_)) = self.queue.front() {+ if let Some(Queued::BotReply(reply)) = self.queue.pop_front() {+ replies.push(reply);+ }+ }+ self.reply_hops = replies.iter().map(crate::chat::team::BotReply::hops).max();+ let prompt = crate::chat::team::reply_prompt(&replies);+ if let Err(e) = self.start_turn(main.clone(), &[], &prompt, false, done_tx).await {+ self.start_error(e, done_tx).await;+ }+ continue;+ }Some(Queued::Group(_)) => {let Some(Queued::Group(mut turn)) = self.queue.pop_front() else {unreachable!("front is a group turn")@@ -268,7 +259,7 @@ impl Actor {_ => {}}// Messages sent while the agent worked go out together as its next turn- // without crossing a bot request or another lane: each gets its own reply.+ // without crossing a bot request or reply or another lane: each gets its own reply.let Some(Queued::User { lane, .. }) = self.queue.front() else { continue };let lane = lane.clone();let mut batch = Vec::new();@@ -306,6 +297,7 @@ impl Actor {// What the chain carried in (a recap, a takeover) was this turn's; the user's handoff waits for the next.self.relay.carried = None;self.turn = None;+ self.reply_hops = None;memory::turns::drop_turn(&self.cfg.id);if self.routine_completion.is_none() {self.set_inflight(false);@@ -318,7 +310,7 @@ impl Actor {r.message = None;r.session = None;});- self.hub.team.cancel_from(&self.cfg.id);+ self.hub.team.end_turn(&self.cfg.id);}/// When `e` asks for signing in: marks the harness signed out and puts a sign-in card in the@@ -344,8 +336,8 @@ impl Actor {}pub(super) fn complete_request(&mut self, result: Result<String>, cancelled: bool) {- if let Some(ask) = self.active_request.take() {- ask.complete(result, cancelled);+ if let Some(request) = self.active_request.take() {+ request.complete(result, cancelled);}}diff --git a/host/src/agent/bot/turn.rs b/host/src/agent/bot/turn.rsindex edef1c87..f18dcabe 100644--- a/host/src/agent/bot/turn.rs+++ b/host/src/agent/bot/turn.rs@@ -1,4 +1,4 @@-//! Starting a turn and wrapping it up: final reply, notices, replies to waiters, alerts and memory.+//! Starting a turn and wrapping it up: final reply, notices, the reply to a requesting bot or room, alerts and memory.use super::{Actor, Conn, Done, Instructions, NoticeStyle, Queued, Reacted, Seg};use crate::agent::acp::{self, Incoming};@@ -81,8 +81,7 @@ impl Actor {let turn = entry_ids.last().and_then(|id| self.hub.store.entry(id)).map_or_else(|| {run_turn.unwrap_or_else(|| {- self.hub.store.max_turn(&lane.chat)- + i64::from(self.active_group.is_some() || self.active_routine.is_some())+ self.hub.store.max_turn(&lane.chat) + i64::from(self.source() != TurnSource::User)})},|e| e.turn,@@ -97,15 +96,19 @@ impl Actor {self.lane = lane.clone();self.turn = Some(turn);// Only the user's own words feed memory: not another bot's, a room's or a routine's.- let from_user =- !hidden && self.active_request.is_none() && self.active_group.is_none() && self.active_routine.is_none();+ let from_user = !hidden && self.source() == TurnSource::User;self.turn_text = from_user.then(|| text.to_owned());self.turn_entries = if from_user { entry_ids.to_vec() } else { Vec::new() };self.turn_memory_revision.clear();self.announce = None;self.stop_requested = false;self.cancel_deadline = None;- self.hub.team.start_turn(&self.cfg.id, self.active_request.as_ref());+ let team_turn = if self.active_request.is_some() {+ crate::chat::team::Turn::Request+ } else {+ crate::chat::team::Turn::Chat(self.reply_hops.unwrap_or(0))+ };+ self.hub.team.start_turn(&self.cfg.id, team_turn);self.exit_tail = None;self.seg = Seg::None;self.tools.clear();@@ -120,8 +123,8 @@ impl Actor {} else {self.relay_turn(&lane, entry_ids, text).await;}- // A delegated or group turn has no live waiter after a host restart. Its persisted- // notices are marked interrupted instead of silently repeating work.+ // A bot request or room turn isn't resumed after a host restart (the room that waited is gone): a request's+ // persisted notices are marked interrupted instead of silently repeating work. A reply turn is resumed.self.set_inflight(self.active_request.is_none() && self.active_group.is_none() && self.active_routine.is_none(),);@@ -173,7 +176,7 @@ impl Actor {if self.routine_completion.is_none() {self.set_inflight(false);}- self.hub.team.cancel_from(&self.cfg.id);+ self.hub.team.end_turn(&self.cfg.id);self.hub.set_runtime(&self.id(), |r| {r.status = BotStatus::Idle;r.activity = String::new();@@ -242,7 +245,7 @@ impl Actor {let mut final_text = None;let routine = self.active_routine.is_some();let grouped = self.active_group.is_some() || routine;- let delegated = self.active_request.as_ref().is_some_and(crate::chat::team::BotRequest::expects_reply);+ let delegated = self.active_request.is_some();let sent = std::mem::take(&mut self.sent);let reacted = std::mem::take(&mut self.reacted);if !sent.is_empty() {@@ -257,10 +260,9 @@ impl Actor {&& let Some(mut e) = self.hub.store.entry(&id){let text = e.data["text"].as_str().map(str::to_owned);- // A pass stays in the trace: neither a room nor the user sees it (an ask's reply goes back as it is).+ // A pass stays in the trace: neither a room nor the user sees it (a bot request's reply goes back as it is).if delegated || !text.as_deref().is_none_or(crate::chat::group::is_pass) {- // An ask's answer belongs to its requesting bot and exchange notice.- // Independent messages still report to the user in this chat.+ // A bot request's answer belongs to the bot that sent it and the exchange notice.if !delegated {e.data["final"] = true.into();self.hub.set_entry(&id, &e.data);@@ -325,8 +327,6 @@ impl Actor {let text = (status == crate::routines::Status::Succeeded).then(|| final_text.clone()).flatten();self.finish_routine(status, detail, text);}- let message_failed =- !stopped && reply.is_err() && self.active_request.as_ref().is_some_and(|r| !r.expects_reply());self.complete_request(reply, stopped);self.complete_group(if stopped || failed || stop_reason != "end_turn" {Err(anyhow!("turn did not complete ({stop_reason})"))@@ -334,6 +334,7 @@ impl Actor {Ok(final_text.clone())});self.turn = None;+ self.reply_hops = None;if self.routine_completion.is_none() {self.set_inflight(false);}@@ -355,7 +356,7 @@ impl Actor {r.message = None;r.session = None;});- self.hub.team.cancel_from(&self.cfg.id);+ self.hub.team.end_turn(&self.cfg.id);// A room turn's news comes from the group once the room is done (see `group`).let more = self.queue.iter().any(|q| matches!(q, Queued::User { .. }));// It held back its only answer, a reaction: it said nothing, so there is nothing to tell either.@@ -363,7 +364,7 @@ impl Actor {if !self.stop_requested&& !delegated&& !grouped- && let Some(kind) = turn_alert(failed || message_failed, &stop_reason, more || held_back)+ && let Some(kind) = turn_alert(failed, &stop_reason, more || held_back){let body = final_text.unwrap_or_else(|| match (kind, reacted) {(AlertKind::Done, Reacted::With(emoji)) => format!("Reacted {emoji} to your message"),@@ -410,18 +411,22 @@ impl Actor {} else {TurnOutcome::Incomplete};- let source = if self.active_routine.is_some() {+ let started = self.hub.runtime(&self.id()).started_at.unwrap_or_else(now_ms);+ let ms = now_ms() - started;+ analytics::turn_finished(&self.hub, &self.cfg.backend, outcome, stop_reason, failure, self.source(), ms);+ }++ /// What started the turn that is starting or running.+ fn source(&self) -> TurnSource {+ if self.active_routine.is_some() {TurnSource::Routine} else if self.active_group.is_some() {TurnSource::Group- } else if self.active_request.is_some() {+ } else if self.active_request.is_some() || self.reply_hops.is_some() {TurnSource::Bot} else {TurnSource::User- };- let started = self.hub.runtime(&self.id()).started_at.unwrap_or_else(now_ms);- let ms = now_ms() - started;- analytics::turn_finished(&self.hub, &self.cfg.backend, outcome, stop_reason, failure, source, ms);+ }}}diff --git a/host/src/agent/bot/updates.rs b/host/src/agent/bot/updates.rsindex 31a367d2..1774d1a7 100644--- a/host/src/agent/bot/updates.rs+++ b/host/src/agent/bot/updates.rs@@ -278,13 +278,12 @@ impl Actor {}/// A `send_message`: the user's next bubble, in the turn's lane, right away. Only in the- /// bot's own chat, including independent messages; a room, an ask or a routine reads- /// the turn's reply.+ /// bot's own chat; a room, a bot request or a routine reads the turn's reply.pub(super) fn send_to_user(&mut self, text: String) -> anyhow::Result<()> {let Some(turn) = self.turn else { anyhow::bail!("no turn is running") };- if self.active_request.as_ref().is_some_and(crate::chat::team::BotRequest::expects_reply) {+ if self.active_request.is_some() {anyhow::bail!(- "send_message isn't available in an ask: return your answer to the requesting bot as your final reply"+ "send_message isn't available in a bot request: your final reply goes to the requesting bot, so put your answer there");}if self.active_group.is_some() || self.active_routine.is_some() {diff --git a/host/src/api/bots.rs b/host/src/api/bots.rsindex 07ed8031..0bcae38f 100644--- a/host/src/api/bots.rs+++ b/host/src/api/bots.rs@@ -52,9 +52,7 @@ pub(super) async fn call(hub: &Arc<Hub>, method: &str, b: Value) -> Result<Contrcrate::chat::outbox::call(hub, bot, name, &b["arguments"]).await?}}- "teamCall" => {- crate::chat::team::call(hub, str_arg(&b, "botId")?, str_arg(&b, "name")?, &b["arguments"]).await?- }+ "teamCall" => crate::chat::team::call(hub, str_arg(&b, "botId")?, str_arg(&b, "name")?, &b["arguments"])?,"manageCall" => {crate::chat::manage::call(hub, str_arg(&b, "botId")?, str_arg(&b, "name")?, &b["arguments"]).await?}diff --git a/host/src/chat/context.rs b/host/src/chat/context.rsindex 08c96e4e..5e695b73 100644--- a/host/src/chat/context.rs+++ b/host/src/chat/context.rs@@ -194,7 +194,7 @@ pub fn render(store: &Store, cfg: &BotConfig) -> String {lines.push(format!("Messages: {}", crate::chat::outbox::INSTRUCTIONS));lines.push(String::new());lines.push(- "Other conversations: your history is shared across them. A group chat turn starts with [Group chat: ...]; a request from another bot or a routine run says so in its first line. In group chats, routines and ask_bot requests, send_message isn't available: your final reply is what gets delivered, so write it for its reader. An independent message_bot request reports to the user in your own chat: send_message is available for updates and the report; if you send none, your final text becomes the report. These rules apply to the current turn, not later turns in this session. Only @-mention in group chats, and don't assume a group sees your private chat."+ "Other conversations: your history is shared across them. A group chat turn starts with [Group chat: ...]; a request from another bot or a routine run says so in its first line. In group chats, routines and requests from other bots, send_message isn't available: your final reply is what gets delivered (to the room, the run's result or the bot that asked), so write it for its reader; group chats and requests from other bots can't use message_bot either. Replies to your own message_bot requests arrive as a turn of their own in this chat, starting with [Codync: ...]: carry on with the user's task from there, and your final reply goes to the user. These rules apply to the current turn, not later turns in this session. Only @-mention in group chats, and don't assume a group sees your private chat.".to_owned(),);lines.push(String::new());@@ -269,12 +269,11 @@ mod tests {}#[test]- fn instructions_distinguish_ask_replies_from_independent_user_reports() {+ fn instructions_say_where_bot_requests_and_their_replies_go() {let store = store();let system = render(&store, &cfg("Reporter", "Report outcomes"));- assert!(system.contains("ask_bot"));- assert!(system.contains("message_bot"));- assert!(system.contains("send_message is available"));+ assert!(system.contains("requests from other bots, send_message isn't available"));+ assert!(system.contains("Replies to your own message_bot requests arrive as a turn of their own"));assert!(system.contains("These rules apply to the current turn"));}diff --git a/host/src/chat/group.rs b/host/src/chat/group.rsindex ee809c54..5c671b4f 100644--- a/host/src/chat/group.rs+++ b/host/src/chat/group.rs@@ -4,10 +4,12 @@//! transcript, but no agent. When the user writes, the group runs a *room turn*://! up to [`MAX_ROUNDS`] rounds in which the members answer one at a time, each in//! its **own** session (a member's history is unified across its chats), told-//! what was said since it last spoke. Everyone answers unless the new messages-//! @-mention someone; a member with nothing to add says `(pass)`, and a round-//! where nobody speaks ends the turn. A newer message in the same lane (or Stop)-//! moves the lane's epoch, which ends a running room turn before its next speaker.+//! what was said since it last spoke. In the first round everyone answers unless+//! the user @-mentions someone; later rounds only ask the members another member+//! @-mentioned and who haven't spoken or been asked since. A member with nothing+//! to add says `(pass)`, and a round where nobody speaks ends the turn. A newer+//! message in the same lane (or Stop) moves the lane's epoch, which ends a running+//! room turn before its next speaker.use crate::LockExt;use crate::agent::bot::{Cmd, NoticeStyle};@@ -17,9 +19,12 @@ use crate::store::{BotConfig, BotKind, Entry, EntryKind, Lane, Store};use anyhow::{Result, anyhow, bail};use std::collections::HashMap;use std::sync::{Arc, Mutex};+use std::time::Duration;use tokio::sync::oneshot;const MAX_ROUNDS: usize = 3;+/// A member's turn that runs longer counts as a pass.+const MEMBER_TIMEOUT: Duration = Duration::from_secs(600);/// Replies per room turn, across all rounds.const MAX_REPLIES: usize = 10;/// Room lines a member is shown per turn.@@ -119,11 +124,14 @@ async fn run(hub: &Arc<Hub>, group_id: &str, lane: &Lane, epoch: u64) -> Result<let mut last_reply: Option<(String, String, String)> = None;// Members busy elsewhere: their turn waits in their queue, and they answer on their own once free.let mut later: Vec<String> = vec![];+ // The newest message each member was shown when last asked: what it passed on, it has seen.+ let mut asked: HashMap<String, i64> = HashMap::new();'rounds: for round in 0..MAX_ROUNDS {let group = group(hub, group_id)?;let members = members(hub, &group);let since_user = since_last_user_message(hub, lane)?;- let mut speakers = responders(&members, &since_user);+ let mut speakers =+ if round == 0 { responders(&members, &since_user) } else { cited(&members, &since_user, &asked) };// Each round starts one member later, so the same bot doesn't always speak first.if !speakers.is_empty() {let offset = round % speakers.len();@@ -142,6 +150,7 @@ async fn run(hub: &Arc<Hub>, group_id: &str, lane: &Lane, epoch: u64) -> Result<continue;}let (prompt, shown) = ask(hub, &group, &members, member, lane)?;+ asked.insert(member.id.clone(), shown);let (reply, answer) = oneshot::channel();let busy = busy_elsewhere(hub, &member.id, lane);let turn = GroupTurn { lane: lane.clone(), prompt, shown, epoch, late: busy, reply };@@ -159,7 +168,7 @@ async fn run(hub: &Arc<Hub>, group_id: &str, lane: &Lane, epoch: u64) -> Result<continue;}// A failed, cancelled or overdue member turn counts as a pass; its error shows in the room.- if let Ok(Ok(Ok(Some(text)))) = tokio::time::timeout(crate::chat::team::ASK_TIMEOUT, answer).await {+ if let Ok(Ok(Ok(Some(text)))) = tokio::time::timeout(MEMBER_TIMEOUT, answer).await {spoke += 1;replies += 1;last_reply = Some((member.id.clone(), member.name.clone(), text));@@ -241,19 +250,51 @@ fn since_last_user_message(hub: &Hub, lane: &Lane) -> Result<Vec<Entry>> {Ok(recent[start..].to_vec())}-/// Who answers: the members @-mentioned or replied to since the user's last message, or+/// Who answers the user: the members @-mentioned or replied to since the user's last message, or/// everyone when nobody (or `@all` / `@everyone`) is.fn responders<'a>(members: &'a [BotConfig], messages: &[Entry]) -> Vec<&'a BotConfig> {let texts: Vec<&str> = messages.iter().filter_map(|e| e.data["text"].as_str()).collect();- let everyone = texts.iter().any(|t| mentions(t, "all") || mentions(t, "everyone"));+ let everyone = texts.iter().any(|t| names_everyone(t));let replied = |m: &BotConfig| messages.iter().any(|e| e.data["replyTo"]["author"] == m.id.as_str());- let named: Vec<&BotConfig> = members- .iter()- .filter(|m| replied(m) || texts.iter().any(|t| handles(&m.name).iter().any(|h| mentions(t, h))))- .collect();+ let named: Vec<&BotConfig> = members.iter().filter(|m| replied(m) || texts.iter().any(|t| names(t, m))).collect();if everyone || named.is_empty() { members.iter().collect() } else { named }}+/// Who answers in a later round: the members another member @-mentioned since the user's last+/// message (`@all` / `@everyone`: all the others) and who haven't spoken or been `asked` since.+/// Nobody, and the room turn ends: a member pulls a teammate in by naming it.+fn cited<'a>(members: &'a [BotConfig], messages: &[Entry], asked: &HashMap<String, i64>) -> Vec<&'a BotConfig> {+ let mut cited_at: HashMap<&str, i64> = HashMap::new();+ // The newest message each member answered or passed on.+ let mut seen: HashMap<&str, i64> = asked.iter().map(|(id, seq)| (id.as_str(), *seq)).collect();+ for e in messages.iter().filter(|e| e.kind == EntryKind::Agent.as_str()) {+ let Some(author) = e.data["author"].as_str() else { continue };+ let at = seen.entry(author).or_default();+ *at = (*at).max(e.seq);+ let text = e.data["text"].as_str().unwrap_or_default();+ let everyone = names_everyone(text);+ for member in members.iter().filter(|m| m.id != author) {+ if everyone || names(text, member) {+ cited_at.insert(&member.id, e.seq);+ }+ }+ }+ let pending = |m: &&BotConfig| {+ cited_at.get(m.id.as_str()).is_some_and(|cited| seen.get(m.id.as_str()).is_none_or(|seen| seen < cited))+ };+ members.iter().filter(pending).collect()+}++/// `@all` or `@everyone` in `text`.+fn names_everyone(text: &str) -> bool {+ mentions(text, "all") || mentions(text, "everyone")+}++/// `member` @-mentioned in `text`.+fn names(text: &str, member: &BotConfig) -> bool {+ handles(&member.name).iter().any(|h| mentions(text, h))+}+/// Ways to @-mention a bot: its full name, without spaces, or its first word (lowercased).fn handles(name: &str) -> Vec<String> {let lower = name.trim().to_lowercase();@@ -297,8 +338,9 @@ fn member_prompt(hub: &Hub, group: &BotConfig, members: &[BotConfig], me: &BotCo}out.push(format!("You have your full toolkit here. Do the work first, then answer: your final reply of this turn is \- the one message the room sees. Keep it short and conversational. @-mention another participant only \- when you need them to act. If you have nothing new worth adding, reply exactly \"{PASS}\". Never \+ the one message the room sees. Keep it short and conversational. After this round, only the \+ participants someone @-mentions answer again: @-mention another participant when you need their \+ answer or action, and only then. If you have nothing new worth adding, reply exactly \"{PASS}\". Never \reveal private one-on-one context. Reactions are rare: react(emoji, to) only where a person would, \never to a question or a request, `to` naming whose newest message (\"user\" or a participant). With \nothing to add, a reaction and \"{PASS}\" agrees without a message."diff --git a/host/src/chat/group/tests.rs b/host/src/chat/group/tests.rsindex 80808edb..cdd2c0b3 100644--- a/host/src/chat/group/tests.rs+++ b/host/src/chat/group/tests.rs@@ -37,6 +37,31 @@ fn mentions_pick_responders_and_no_mention_means_everyone() {assert_eq!(replied, ["b"], "a reply asks the bot it quotes");}+#[test]+fn later_rounds_ask_only_the_members_another_member_mentioned() {+ let members = [bot("a", "Alice"), bot("b", "Bob"), bot("c", "Cara")];+ let by = |author: &str, text: &str, seq: i64| Entry {+ seq,+ kind: "agent".into(),+ data: json!({"text": text, "author": author}),+ ..said(text)+ };+ let asked_ids = |messages: &[Entry], asked: &[(&str, i64)]| -> Vec<String> {+ let asked = asked.iter().map(|(id, seq)| ((*id).to_owned(), *seq)).collect();+ cited(&members, messages, &asked).into_iter().map(|b| b.id.clone()).collect()+ };+ let ids = |messages: &[Entry]| asked_ids(messages, &[]);+ assert!(ids(&[said("hi all"), by("a", "done", 2)]).is_empty(), "nobody named: the room turn ends");+ let named = [said("hi"), by("a", "@bob check", 2)];+ assert!(asked_ids(&named, &[("b", 2)]).is_empty(), "Bob saw it and passed");+ assert_eq!(asked_ids(&named, &[("b", 1)]), ["b"], "Bob was asked before he was named");+ assert_eq!(ids(&[said("hi"), by("a", "@bob can you check?", 2)]), ["b"]);+ assert!(ids(&[said("hi"), by("a", "@bob check", 2), by("b", "checked", 3)]).is_empty(), "Bob already answered");+ assert_eq!(ids(&[said("hi"), by("a", "@bob check", 2), by("b", "ok", 3), by("c", "@bob again", 4)]), ["b"]);+ assert_eq!(ids(&[said("hi"), by("a", "@alice @all over to you", 2)]), ["b", "c"], "not yourself");+ assert!(ids(&[said("@cara look"), by("a", "ok", 2)]).is_empty(), "the user's mentions pick the first round");+}+use crate::api::devices::Caller;use crate::hub::BotStatus;use std::path::PathBuf;@@ -147,8 +172,10 @@ async fn room_turns_follow_mentions_and_end_when_everyone_passes() {let main = Lane::main(&room.group);room.send("hello everyone", None).await;room.settle().await;- // `a` answers the user; `b` then sees a bot spoke last and passes; round two is all passes.+ // `a` answers the user; `b` then sees a bot spoke last and passes. Nobody named anyone: no second round.assert_eq!(room.replies(&main), [("a".to_owned(), "reply: group".to_owned())]);+ let prompts = |bot: &str| std::fs::read_to_string(room.dir.join(bot).join("prompts.jsonl")).unwrap_or_default();+ assert_eq!((prompts("a").lines().count(), prompts("b").lines().count()), (1, 1));room.send("@b your turn", None).await;room.settle().await;@@ -156,7 +183,14 @@ async fn room_turns_follow_mentions_and_end_when_everyone_passes() {assert_eq!(room.replies(&main).len(), 2);let listed = room.hub.bot_value_for_test(&room.group);assert_eq!(listed["lastMessage"], "b: reply: group");- let prompts = std::fs::read_to_string(room.dir.join("a/prompts.jsonl")).unwrap();++ // A member brings a teammate into the next round by naming it.+ room.send("@a PING", None).await;+ room.settle().await;+ assert_eq!(room.replies(&main).last().unwrap(), &("a".to_owned(), "@b over to you".to_owned()));+ assert!(prompts("b").lines().last().unwrap().contains(r"a: @b over to you"), "b is asked in round two");+ assert_eq!(prompts("b").lines().count(), 3);+ let prompts = prompts("a");assert!(prompts.contains("Ship the release) with the user"), "members are told what the room is for: {prompts}");// The members' own chats stay private: the room's entries live in the group.assert!(room.hub.store.messages_after(&Lane::main("a"), 0, 100).unwrap().is_empty());diff --git a/host/src/chat/team.rs b/host/src/chat/team.rsindex bc3ae2f0..4ed76da4 100644--- a/host/src/chat/team.rs+++ b/host/src/chat/team.rs@@ -1,33 +1,35 @@-//! Small, host-local bot delegation. The recipient uses its own ACP session;-//! native subagents remain the harness's responsibility.+//! Small, host-local bot messages. The recipient uses its own ACP session and its reply comes back+//! to the sender as a turn of its own, so no bot ever waits on another; native subagents remain+//! the harness's responsibility.-use crate::LockExt;use crate::agent::bot::Cmd;-use crate::hub::{BotStatus, Hub};+use crate::hub::Hub;use crate::store::{BotConfig, EntryKind};use anyhow::{Result, anyhow, bail};use serde::Serialize;use serde_json::{Value, json};use std::sync::Arc;-use std::time::Duration;-use tokio::sync::oneshot;mod requests;-pub use requests::Requests;+pub use requests::{Requests, Turn};-pub const ASK_TIMEOUT: Duration = Duration::from_secs(600);const MAX_MESSAGE_BYTES: usize = 32_000;const MAX_PENDING_MESSAGES: usize = 64;+/// What an exchange notice keeps of a reply.+const NOTICE_REPLY_BYTES: usize = 4000;+/// What the sender's reply turn quotes of its request: the session taking the reply may not have sent it.+const REQUEST_QUOTE_BYTES: usize = 1000;pub const INSTRUCTIONS: &str = "Use list_bots to find the user's other Codync bots. \-Use ask_bot when the user requests another bot's help or its specialty is useful. \-Use message_bot for a handoff that should continue independently: it returns when queued, \-and the recipient reports the outcome to the user in its own chat. Stopping you does not cancel it. \-Provide a self-contained request: the recipient has its own conversation, working directory, \-tools and permissions, not your context. ask_bot returns its final reply to you. \-Coordinate file ownership before asking for edits in a shared project. \-Do not ask a bot that is waiting for you. Native subagents are managed by your own harness; \-these tools are for collaborating with the user's existing bots.";+Use message_bot when the user requests another bot's help or its specialty is useful. It returns as soon as \+the request is queued, and the recipient's reply comes back to you later as a new turn in your own chat: don't \+wait or poll for it. Finish your turn (tell the user what you asked for) or go on with other work. Message \+several bots to have them work in parallel. It works only in your own chat: in a group chat, @-mention the \+room's members instead, and while answering another bot's request, say in your reply what you need from \+others. Provide a self-contained request: the recipient has its own \+conversation, working directory, tools and permissions, not your context. Coordinate file ownership before \+asking for edits in a shared project. Native subagents are managed by your own harness; these tools are for \+collaborating with the user's existing bots.";pub fn tools() -> Value {json!([@@ -37,27 +39,14 @@ pub fn tools() -> Value {"inputSchema": {"type": "object", "properties": {}},"annotations": {"readOnlyHint": true},},- {- "name": "ask_bot",- "description": "Ask an existing Codync bot to do a bounded task and wait for its final reply (up to 10 minutes, including queue time). It may use tools and modify files under its own permissions. Does not share your conversation or change its working directory. Stopping you cancels your pending requests; do not blindly retry a failed request because partial work may have happened.",- "inputSchema": {- "type": "object",- "properties": {- "botId": {"type": "string", "description": "Recipient ID from list_bots."},- "message": {"type": "string", "description": "Task, relevant context, file paths and expected result."},- },- "required": ["botId", "message"],- },- "annotations": {"readOnlyHint": false, "idempotentHint": false},- },{"name": "message_bot",- "description": "Queue a self-contained request for another Codync bot and return immediately. The recipient reports the outcome to the user in its own chat; no reply is returned to you. It uses its own tools, folder and permissions. Stopping you does not cancel accepted work. Stopping the recipient cancels its queued requests and stops its running turn. No automatic retry or replay after host restart; check the chats before retrying an uncertain result.",+ "description": "Send a self-contained request to another Codync bot and return as soon as it is queued. The recipient works with its own tools, folder and permissions; its final reply (or why it couldn't finish) comes back to you later as a new turn in your own chat, with replies that arrive while you are busy taken together. Don't wait or poll for it. Stopping you does not cancel accepted requests; stopping the recipient does. No automatic retry or replay after a host restart; check the chats before retrying an uncertain result.","inputSchema": {"type": "object","properties": {"botId": {"type": "string", "description": "Recipient ID from list_bots."},- "message": {"type": "string", "description": "Task, relevant context, file paths and expected outcome for the user."},+ "message": {"type": "string", "description": "Task, relevant context, file paths and expected result."},},"required": ["botId", "message"],},@@ -66,65 +55,87 @@ pub fn tools() -> Value {])}-/// Sent through the recipient's normal actor queue, but never merged with user-/// messages or another request. Its completion mode owns reply delivery or the-/// independent message's notice lifetime.+/// Sent through the recipient's normal actor queue, but never merged with user messages or+/// another request. It owns the exchange notices and the reply that goes back to the sender.pub struct BotRequest {- pub id: String,pub entry_id: String,pub prompt: String,- /// Bound the whole chain, including independent handoffs after their sender finishes.+ /// The chain's handoffs so far; the reply carries them into the sender's turn, so the chain stays bounded.hops: u8,- completion: Completion,-}--enum Completion {- ReplyToSender(oneshot::Sender<Result<String>>),- ReportInRecipientChat(MessageLifetime),+ lifetime: MessageLifetime,}impl BotRequest {- pub fn expects_reply(&self) -> bool {- matches!(self.completion, Completion::ReplyToSender(_))+ pub fn mark_started(&mut self) {+ self.lifetime.start();}- pub fn reply_closed(&self) -> bool {- matches!(&self.completion, Completion::ReplyToSender(reply) if reply.is_closed())+ /// Finishes both notices and, unless the user stopped the recipient, wakes the sender with the outcome.+ pub fn complete(mut self, result: Result<String>, cancelled: bool) {+ let message = &mut self.lifetime;+ if cancelled {+ message.finish(RequestStatus::Cancelled, "Recipient stopped. Partial work may have happened.", None);+ return;+ }+ let outcome = match result {+ Ok(text) => {+ let reply = crate::agent::acp::truncate(&text, NOTICE_REPLY_BYTES);+ let detail = format!("Reply from {}:\n{reply}", message.target_name);+ message.finish(RequestStatus::Completed, &detail, Some(&reply));+ Ok(crate::agent::acp::truncate(&text, MAX_MESSAGE_BYTES))+ }+ Err(error) => {+ let detail = format!("{error:#}");+ message.finish(RequestStatus::Failed, &detail, None);+ Err(detail)+ }+ };+ let reply = BotReply {+ request_id: message.request_id.clone(),+ quote: message.quote.clone(),+ from_name: message.target_name.clone(),+ outcome,+ hops: self.hops,+ };+ // A deleted sender has no chat to take the reply; its notice already shows it.+ let _ = message.hub.send_cmd(&message.sender, Cmd::BotReply(reply));}+}- pub fn mark_started(&mut self) {- if let Completion::ReportInRecipientChat(message) = &mut self.completion {- message.started = true;- for id in &message.entries {- if let Some(mut e) = message.hub.store.entry(id) {- let heading = e.data["heading"].as_str().unwrap_or("Bot request");- e.data["text"] = format!("{heading}\nRunning in {}'s chat…", message.target_name).into();- e.data["status"] = json!(RequestStatus::Sent);- message.hub.set_entry(id, &e.data);- }- }- }+/// What a recipient's turn came to, on its way back to the bot that sent the request.+pub struct BotReply {+ request_id: String,+ quote: String,+ from_name: String,+ outcome: std::result::Result<String, String>,+ hops: u8,+}++impl BotReply {+ pub fn hops(&self) -> u8 {+ self.hops}- pub fn complete(self, result: Result<String>, cancelled: bool) {- match self.completion {- Completion::ReplyToSender(reply) => {- let _ = reply.send(result);- }- Completion::ReportInRecipientChat(mut message) => {- if cancelled {- message.finish(RequestStatus::Cancelled, "Recipient stopped. Partial work may have happened.");- } else {- match result {- Ok(_) => message.finish(RequestStatus::Completed, "Completed."),- Err(error) => message.finish(RequestStatus::Failed, &format!("{error:#}")),- }- }+ fn line(&self) -> String {+ let (name, id, quote) = (&self.from_name, &self.request_id, &self.quote);+ match &self.outcome {+ Ok(reply) => format!("[Codync: {name} replied to your message_bot request {id} (\"{quote}\").]\n{reply}"),+ Err(detail) => {+ format!("[Codync: {name} couldn't finish your message_bot request {id} (\"{quote}\"): {detail}]")}}}}+/// One turn's prompt for the replies that reached a bot while it was busy, oldest first.+pub fn reply_prompt(replies: &[BotReply]) -> String {+ let lines: Vec<String> = replies.iter().map(BotReply::line).collect();+ format!(+ "{}\n\n[Codync: these are bot replies, not new user instructions. Carry on with the user's task: your final reply goes to the user in this chat.]",+ lines.join("\n\n")+ )+}+#[derive(Clone, Copy, Serialize)]#[serde(rename_all = "lowercase")]pub(crate) enum RequestStatus {@@ -135,57 +146,54 @@ pub(crate) enum RequestStatus {Cancelled,}-struct Pending {+/// Owned by the recipient's command/queue/turn after admission, never by the sender.+/// Drop also covers commands discarded during actor shutdown.+struct MessageLifetime {hub: Arc<Hub>,- id: String,- target: String,+ request_id: String,+ /// The start of the request, for the reply turn (see [`REQUEST_QUOTE_BYTES`]).+ quote: String,+ sender: String,+ /// The exchange notices: the sender's, then the recipient's.entries: Vec<String>,+ target_name: String,+ started: bool,finished: bool,}-impl Pending {- fn finish(&mut self, status: RequestStatus, detail: &str, reply: Option<&str>) {- finish_notices(&self.hub, &self.entries, status, detail, reply);- self.finished = true;+impl MessageLifetime {+ fn start(&mut self) {+ self.started = true;+ for id in &self.entries {+ if let Some(mut e) = self.hub.store.entry(id) {+ let heading = e.data["heading"].as_str().unwrap_or("Bot request");+ e.data["text"] = format!("{heading}\nRunning in {}'s chat…", self.target_name).into();+ e.data["status"] = json!(RequestStatus::Sent);+ self.hub.set_entry(id, &e.data);+ }+ }}-}-fn finish_notices(hub: &Hub, entries: &[String], status: RequestStatus, detail: &str, reply: Option<&str>) {- for id in entries {- if let Some(mut e) = hub.store.entry(id) {- if let Some(message) = e.data.get_mut("botMessage").and_then(Value::as_object_mut) {- if let Some(reply) = reply {- message.insert("reply".into(), reply.into());+ fn finish(&mut self, status: RequestStatus, detail: &str, reply: Option<&str>) {+ for id in &self.entries {+ if let Some(mut e) = self.hub.store.entry(id) {+ if let Some(message) = e.data.get_mut("botMessage").and_then(Value::as_object_mut) {+ if let Some(reply) = reply {+ message.insert("reply".into(), reply.into());+ }+ if matches!(status, RequestStatus::Failed | RequestStatus::Cancelled) {+ message.insert("detail".into(), detail.into());+ }}- if matches!(status, RequestStatus::Failed | RequestStatus::Cancelled) {- message.insert("detail".into(), detail.into());+ e.data["status"] = json!(status);+ let heading = e.data["heading"].as_str().unwrap_or("Bot request");+ e.data["text"] = format!("{heading}\n{detail}").into();+ if !matches!(status, RequestStatus::Completed) {+ e.data["style"] = "error".into();}+ self.hub.set_entry(id, &e.data);}- e.data["status"] = json!(status);- let heading = e.data["heading"].as_str().unwrap_or("Bot request");- e.data["text"] = format!("{heading}\n{detail}").into();- if !matches!(status, RequestStatus::Completed) {- e.data["style"] = "error".into();- }- hub.set_entry(id, &e.data);}- }-}--/// Owned by the recipient's command/queue/turn after admission, never by a-/// waiting sender. Drop also covers commands discarded during actor shutdown.-struct MessageLifetime {- hub: Arc<Hub>,- sender: String,- entries: Vec<String>,- target_name: String,- started: bool,- finished: bool,-}--impl MessageLifetime {- fn finish(&mut self, status: RequestStatus, detail: &str) {- finish_notices(&self.hub, &self.entries, status, detail, None);self.finished = true;}}@@ -198,23 +206,12 @@ impl Drop for MessageLifetime {} else {"Cancelled before execution."};- self.finish(RequestStatus::Cancelled, detail);+ self.finish(RequestStatus::Cancelled, detail, None);}self.hub.team.release_message(&self.sender);}}-impl Drop for Pending {- fn drop(&mut self) {- if !self.finished {- self.finish(RequestStatus::Cancelled, "Request cancelled. Partial work may have happened.", None);- }- self.hub.team.0.locked().pending.remove(&self.id);- // Targeted cancellation never clears unrelated user messages or turns.- let _ = self.hub.send_cmd(&self.target, Cmd::CancelAsk { id: self.id.clone() });- }-}-fn visible_bot(hub: &Hub, id: &str) -> Result<BotConfig> {hub.store.bot(id)?@@ -223,7 +220,7 @@ fn visible_bot(hub: &Hub, id: &str) -> Result<BotConfig> {.ok_or_else(|| anyhow!("unknown or hidden bot"))}-pub async fn call(hub: &Arc<Hub>, from: &str, name: &str, args: &Value) -> Result<Value> {+pub fn call(hub: &Arc<Hub>, from: &str, name: &str, args: &Value) -> Result<Value> {let source = visible_bot(hub, from)?;match name {"list_bots" => {@@ -242,11 +239,6 @@ pub async fn call(hub: &Arc<Hub>, from: &str, name: &str, args: &Value) -> Resul.collect();Ok(json!({"bots": bots}))}- "ask_bot" => {- let to = args["botId"].as_str().ok_or_else(|| anyhow!("botId is required"))?;- let message = args["message"].as_str().unwrap_or_default().trim();- ask(hub, &source, to, message, ASK_TIMEOUT).await- }"message_bot" => {let to = args["botId"].as_str().ok_or_else(|| anyhow!("botId is required"))?;let message = args["message"].as_str().unwrap_or_default().trim();@@ -263,17 +255,23 @@ fn message_bot(hub: &Arc<Hub>, source: &BotConfig, to: &str, message: &str) -> Rif source.id == to {bail!("a bot cannot message itself");}+ // The reply would come back to the sender's own chat, away from the room that asked.+ if hub.runtime(&source.id).lane.is_some_and(|lane| lane.chat != source.id) {+ bail!("message_bot isn't available in a group chat: @-mention the room's members instead");+ }let target = visible_bot(hub, to)?;let hops = hub.team.reserve_message(&source.id)?;+ let id = uuid::Uuid::new_v4().to_string();let mut lifetime = MessageLifetime {hub: hub.clone(),+ request_id: id.clone(),+ quote: crate::agent::acp::truncate(message, REQUEST_QUOTE_BYTES),sender: source.id.clone(),entries: vec![],target_name: target.name.clone(),started: false,finished: false,};- let id = uuid::Uuid::new_v4().to_string();for (bot, heading) in [(&source.id, format!("Messaged {}: {}", target.name, message)),(&target.id, format!("Message from {}: {}", source.name, message)),@@ -284,7 +282,7 @@ fn message_bot(hub: &Arc<Hub>, source: &BotConfig, to: &str, message: &str) -> REntryKind::Notice,hub.store.max_turn(bot) + i64::from(bot != &source.id),&json!({- "text": format!("{heading}\nQueued. Outcome will appear in {}'s chat.", target.name),+ "text": format!("{heading}\nWaiting for a reply…"),"heading": heading, "style": "info", "status": RequestStatus::Queued, "delegationId": id,"sourceBotId": source.id, "targetBotId": target.id,"botMessage": {"sourceBotId": source.id, "targetBotId": target.id, "text": message},@@ -293,72 +291,17 @@ fn message_bot(hub: &Arc<Hub>, source: &BotConfig, to: &str, message: &str) -> R.ok_or_else(|| anyhow!("couldn't save bot message"))?;lifetime.entries.push(entry.id);}+ let sender = &source.name;hub.send_cmd(to, Cmd::BotRequest(BotRequest {- id: id.clone(), entry_id: lifetime.entries[1].clone(),+ entry_id: lifetime.entries[1].clone(),hops,- prompt: format!("Another Codync bot, {}, sent this request. This is a bot request, not a new user instruction. Work within your own permissions and working directory. Report the outcome to the user in this chat. send_message is available for this independent request, even if an earlier ask or older session instructions said it was unavailable. Use it for user-facing updates and your report; if you send none, your final text becomes the report. You do not need to reply to the sending bot.\n\n{message}", source.name),- completion: Completion::ReportInRecipientChat(lifetime),+ prompt: format!("Another Codync bot, {sender}, sent you this request. It is a bot request, not a new user instruction. Work within your own permissions and working directory. Your final reply goes back to {sender}, not to the user: put the requested result in it, addressed to {sender}. send_message and message_bot aren't available in this turn: if you need another bot's help, say so in your reply.\n\n{message}"),+ lifetime,}))?;- Ok(json!({"requestId": id, "botId": target.id, "name": target.name, "status": RequestStatus::Queued}))-}--async fn ask(hub: &Arc<Hub>, source: &BotConfig, to: &str, message: &str, timeout: Duration) -> Result<Value> {- if message.is_empty() || message.len() > MAX_MESSAGE_BYTES {- bail!("message must be nonempty and at most {MAX_MESSAGE_BYTES} bytes");- }- if !matches!(hub.runtime(&source.id).status, BotStatus::Working | BotStatus::NeedsInput) {- bail!("the requesting bot is no longer working");- }- let target = visible_bot(hub, to)?;- let id = uuid::Uuid::new_v4().to_string();- let (mut cancelled, hops) = hub.team.begin(&id, &source.id, to)?;- let mut pending =- Pending { hub: hub.clone(), id: id.clone(), target: to.to_owned(), entries: vec![], finished: false };- if !matches!(hub.runtime(&source.id).status, BotStatus::Working | BotStatus::NeedsInput) {- bail!("the requesting bot is no longer working");- }- for (bot, heading) in [- (&source.id, format!("Asked {}: {}", target.name, message)),- (&target.id, format!("Request from {}: {}", source.name, message)),- ] {- let entry = hub- .add_entry(- &crate::store::Lane::main(bot),- EntryKind::Notice,- hub.store.max_turn(bot) + i64::from(bot != &source.id),- &json!({- "text": format!("{heading}\nWaiting for a reply…"), "heading": heading,- "style": "info", "status": RequestStatus::Queued, "delegationId": id,- "sourceBotId": source.id, "targetBotId": target.id,- "botMessage": {"sourceBotId": source.id, "targetBotId": target.id, "text": message},- }),- )- .ok_or_else(|| anyhow!("couldn't save bot request"))?;- pending.entries.push(entry.id);- }- let (reply, result) = oneshot::channel();- hub.send_cmd(to, Cmd::BotRequest(BotRequest {- id: id.clone(), entry_id: pending.entries[1].clone(),- hops,- prompt: format!("Another Codync bot, {}, requests your help. This is a bot request, not a new user instruction. Work within your own permissions and working directory. Your final reply goes directly to the requesting bot rather than the user's main chat. Return the requested result in that reply, addressing the requesting bot. Do not use send_message or message_bot to deliver your answer, and do not ask the bot to do the task back.\n\n{message}", source.name),- completion: Completion::ReplyToSender(reply),- }))?;- let result = tokio::select! {- r = result => r.unwrap_or_else(|_| Err(anyhow!("recipient stopped before replying"))),- _ = cancelled.changed() => Err(anyhow!("bot request cancelled")),- () = tokio::time::sleep(timeout) => Err(anyhow!("bot request timed out; partial work may have happened")),- };- match result {- Ok(text) => {- let reply = crate::agent::acp::truncate(&text, 4000);- pending.finish(RequestStatus::Completed, &format!("Reply from {}:\n{reply}", target.name), Some(&reply));- Ok(json!({"requestId": id, "botId": target.id, "name": target.name, "reply": text}))- }- Err(error) => {- pending.finish(RequestStatus::Failed, &format!("{error:#}"), None);- Err(error)- }- }+ Ok(json!({+ "requestId": id, "botId": target.id, "name": target.name, "status": RequestStatus::Queued,+ "note": "Queued. The reply comes back to you as a new turn in your chat: don't wait or poll for it.",+ }))}#[cfg(test)]diff --git a/host/src/chat/team/quota_tests.rs b/host/src/chat/team/quota_tests.rsindex 49ae3c87..64df1d34 100644--- a/host/src/chat/team/quota_tests.rs+++ b/host/src/chat/team/quota_tests.rs@@ -7,25 +7,23 @@ async fn sender_quota_survives_sender_stop_and_frees_on_recipient_stop() {f.send_user("BLOCK user work").await;f.until(|| f.prompts().len() == 1).await;for _ in 0..MAX_PENDING_MESSAGES_PER_SENDER {- let result = f.message("queued message").await;+ let result = f.message("queued message");assert!(result.is_ok());}- let result = f.message("overflow").await;+ let result = f.message("overflow");assert!(result.unwrap_err().to_string().contains("from this bot"));- assert!(f.hub.team.0.locked().pending.is_empty());f.hub.send_cmd("a", Cmd::Stop).unwrap();f.until(|| !f.hub.team.0.locked().active.contains_key("a")).await;- f.hub.team.start_turn("a", None);- let result = f.message("a new sender turn cannot bypass its quota").await;+ f.hub.team.start_turn("a", Turn::Chat(0));+ let result = f.message("a new sender turn cannot bypass its quota");assert!(result.unwrap_err().to_string().contains("from this bot"));- f.hub.set_runtime("c", |r| r.status = BotStatus::Working);- f.hub.team.start_turn("c", None);- let result = call(&f.hub, "c", "message_bot", &json!({"botId": "b", "message": "another sender"})).await;+ f.sending("c");+ let result = call(&f.hub, "c", "message_bot", &json!({"botId": "b", "message": "another sender"}));assert!(result.is_ok());f.hub.send_cmd("b", Cmd::Stop).unwrap();f.until(|| f.hub.team.0.locked().messages == 0 && f.hub.runtime("b").status == BotStatus::Idle).await;assert!(f.hub.team.0.locked().messages_by_sender.is_empty());- let result = f.message("after capacity released").await;+ let result = f.message("after capacity released");assert!(result.is_ok());f.until(|| f.hub.team.0.locked().messages == 0).await;assert_eq!(f.prompts().len(), 2);@@ -35,14 +33,14 @@ async fn sender_quota_survives_sender_stop_and_frees_on_recipient_stop() {#[tokio::test]async fn running_messages_hold_sender_slots_until_recipient_completion() {let f = Fixture::new();- let result = f.message("BLOCK active message").await;+ let result = f.message("BLOCK active message");assert!(result.is_ok());f.until(|| f.prompts().len() == 1).await;for _ in 1..MAX_PENDING_MESSAGES_PER_SENDER {- let result = f.message("queued message").await;+ let result = f.message("queued message");assert!(result.is_ok());}- let result = f.message("running plus queued reaches the quota").await;+ let result = f.message("running plus queued reaches the quota");assert!(result.unwrap_err().to_string().contains("from this bot"));f.hub.delete_bot("a").unwrap();assert_eq!(f.hub.team.0.locked().messages_by_sender["a"], MAX_PENDING_MESSAGES_PER_SENDER);@@ -63,12 +61,12 @@ async fn failed_admission_and_recipient_failure_return_sender_slots() {BEGIN SELECT RAISE(ABORT, 'fixture save failure'); END;",).unwrap();- let result = f.message("cannot persist recipient notice").await;+ let result = f.message("cannot persist recipient notice");assert!(result.is_err());assert!(f.hub.team.0.locked().messages_by_sender.is_empty());assert_eq!(f.hub.team.0.locked().messages, 0);db.execute_batch("DROP TRIGGER reject_message;").unwrap();- let result = f.message("FAIL recipient prompt").await;+ let result = f.message("FAIL recipient prompt");let receipt = result.unwrap();f.until(|| f.hub.team.0.locked().messages == 0).await;assert!(f.notices(&receipt).iter().all(|e| e.data["status"] == "failed"));diff --git a/host/src/chat/team/requests.rs b/host/src/chat/team/requests.rsindex 01f46ba6..945a49d4 100644--- a/host/src/chat/team/requests.rs+++ b/host/src/chat/team/requests.rs@@ -1,31 +1,33 @@-//! Admission, capacity and the wait graph for bot requests.+//! Admission, capacity and the hop limit for bot messages.use crate::LockExt;use anyhow::{Result, bail};-use std::collections::{HashMap, HashSet};+use std::collections::HashMap;use std::sync::Mutex;-use tokio::sync::watch;-use super::{BotRequest, MAX_PENDING_MESSAGES};+use super::MAX_PENDING_MESSAGES;const MAX_REQUEST_HOPS: u8 = 8;pub(super) const MAX_PENDING_MESSAGES_PER_SENDER: usize = 16;-pub(super) struct Request {- from: String,- to: String,- cancel: watch::Sender<bool>,-}--/// The wait graph includes queued requests, not only running recipients.-/// Reserving an edge and checking for cycles happen under the same lock.+/// Nothing waits on a message, so there is no wait graph: capacity and the chain's hop count+/// bound what bots can start.#[derive(Default)]pub struct Requests(pub(super) Mutex<RequestState>);+/// A running turn, as bot messages see it.+#[derive(Clone, Copy)]+pub enum Turn {+ /// A turn in the bot's own chat, `hops` handoffs into a chain (0 for the user's own turn).+ Chat(u8),+ /// Answering another bot's request: the answer goes back in its reply, so it messages no one.+ Request,+}+#[derive(Default)]pub(super) struct RequestState {- pub(super) pending: HashMap<String, Request>,- pub(super) active: HashMap<String, u8>,+ /// Bots in a turn.+ pub(super) active: HashMap<String, Turn>,pub(super) messages: usize,pub(super) messages_by_sender: HashMap<String, usize>,}@@ -57,62 +59,30 @@ impl Requests {}}- pub(super) fn begin(&self, id: &str, from: &str, to: &str) -> Result<(watch::Receiver<bool>, u8)> {- let mut state = self.0.locked();- let hops = state.next_hop(from)?;- let requests = &mut state.pending;- if from == to {- bail!("a bot cannot ask itself");- }- if requests.len() >= 64 {- bail!("too many pending bot requests");- }- if requests.values().any(|r| r.from == from && r.to == to) {- bail!("already waiting for this bot");- }- let mut pending = vec![to];- let mut seen = HashSet::new();- while let Some(bot) = pending.pop() {- if bot == from {- bail!("this request would make bots wait for each other; finish the current request first");- }- if seen.insert(bot) {- pending.extend(requests.values().filter(|r| r.from == bot).map(|r| r.to.as_str()));- }- }- let (cancel, rx) = watch::channel(false);- requests.insert(id.to_owned(), Request { from: from.to_owned(), to: to.to_owned(), cancel });- Ok((rx, hops))- }-- pub fn cancel_from(&self, bot: &str) {- let mut state = self.0.locked();- state.active.remove(bot);- for request in state.pending.values().filter(|r| r.from == bot) {- request.cancel.send_replace(true);- }- }-- pub fn start_turn(&self, bot: &str, request: Option<&BotRequest>) {- self.0.locked().active.insert(bot.to_owned(), request.map_or(0, |r| r.hops));+ pub fn start_turn(&self, bot: &str, turn: Turn) {+ self.0.locked().active.insert(bot.to_owned(), turn);}- pub fn cancel_bot(&self, bot: &str) {- let mut state = self.0.locked();- state.active.remove(bot);- for request in state.pending.values().filter(|r| r.from == bot || r.to == bot) {- request.cancel.send_replace(true);- }+ /// `bot`'s turn ended (or it was deleted): it can't send more until its next turn.+ pub fn end_turn(&self, bot: &str) {+ self.0.locked().active.remove(bot);}}impl RequestState {fn next_hop(&self, from: &str) -> Result<u8> {- let hops = *self.active.get(from).ok_or_else(|| anyhow::anyhow!("the requesting bot is no longer working"))?;- if hops >= MAX_REQUEST_HOPS {- bail!("bot request hop limit ({MAX_REQUEST_HOPS}) reached; ask the user before starting another chain");+ match self.active.get(from) {+ None => bail!("the requesting bot is no longer working"),+ Some(Turn::Request) => {+ bail!(+ "message_bot isn't available while answering another bot's request: say what you need in your reply"+ )+ }+ Some(&Turn::Chat(hops)) if hops >= MAX_REQUEST_HOPS => {+ bail!("bot request hop limit ({MAX_REQUEST_HOPS}) reached; ask the user before starting another chain")+ }+ Some(&Turn::Chat(hops)) => Ok(hops + 1),}- Ok(hops + 1)}}@@ -121,35 +91,45 @@ mod tests {use super::*;#[test]- fn exhausted_chain_rejects_messages_and_asks_without_reserving_capacity() {+ fn exhausted_chain_rejects_messages_without_reserving_capacity() {let requests = Requests::default();- requests.0.locked().active.insert("a".into(), MAX_REQUEST_HOPS);+ requests.start_turn("a", Turn::Chat(MAX_REQUEST_HOPS));let message = requests.reserve_message("a");assert!(message.unwrap_err().to_string().contains("hop limit"));- let ask = requests.begin("ask", "a", "b");- assert!(ask.unwrap_err().to_string().contains("hop limit"));- let state = requests.0.locked();- assert_eq!(state.messages, 0);- assert!(state.pending.is_empty());- drop(state);- requests.start_turn("a", None);+ assert_eq!(requests.0.locked().messages, 0);+ requests.start_turn("a", Turn::Chat(0));assert_eq!(requests.reserve_message("a").unwrap(), 1);}#[test]fn last_allowed_handoff_is_admitted() {let requests = Requests::default();- requests.0.locked().active.insert("a".into(), MAX_REQUEST_HOPS - 1);+ requests.start_turn("a", Turn::Chat(MAX_REQUEST_HOPS - 1));assert_eq!(requests.reserve_message("a").unwrap(), MAX_REQUEST_HOPS);- let (_, hops) = requests.begin("ask", "a", "b").unwrap();- assert_eq!(hops, MAX_REQUEST_HOPS);+ }++ #[test]+ fn a_bot_answering_a_request_cannot_send() {+ let requests = Requests::default();+ requests.start_turn("a", Turn::Request);+ assert!(requests.reserve_message("a").unwrap_err().to_string().contains("answering another bot's request"));+ assert_eq!(requests.0.locked().messages, 0);+ }++ #[test]+ fn a_bot_outside_a_turn_cannot_send() {+ let requests = Requests::default();+ assert!(requests.reserve_message("a").unwrap_err().to_string().contains("no longer working"));+ requests.start_turn("a", Turn::Chat(0));+ requests.end_turn("a");+ assert!(requests.reserve_message("a").is_err());}#[test]fn sender_quota_leaves_capacity_for_other_bots() {let requests = Requests::default();for bot in ["a", "b"] {- requests.start_turn(bot, None);+ requests.start_turn(bot, Turn::Chat(0));}for _ in 0..MAX_PENDING_MESSAGES_PER_SENDER {requests.reserve_message("a").unwrap();@@ -158,8 +138,6 @@ mod tests {assert!(result.unwrap_err().to_string().contains("from this bot (limit 16)"));assert_eq!(requests.0.locked().messages, MAX_PENDING_MESSAGES_PER_SENDER);requests.reserve_message("b").unwrap();- // Ask capacity is independent of message quotas.- requests.begin("ask", "a", "b").unwrap();requests.release_message("a");requests.reserve_message("a").unwrap();for _ in 0..MAX_PENDING_MESSAGES_PER_SENDER {@@ -175,13 +153,13 @@ mod tests {fn global_capacity_still_bounds_messages_from_multiple_senders() {let requests = Requests::default();for bot in ["a", "b", "c", "d"] {- requests.start_turn(bot, None);+ requests.start_turn(bot, Turn::Chat(0));for _ in 0..MAX_PENDING_MESSAGES_PER_SENDER {requests.reserve_message(bot).unwrap();}}assert_eq!(requests.0.locked().messages, MAX_PENDING_MESSAGES);- requests.start_turn("e", None);+ requests.start_turn("e", Turn::Chat(0));let result = requests.reserve_message("e");assert_eq!(result.unwrap_err().to_string(), "too many pending bot messages");assert!(!requests.0.locked().messages_by_sender.contains_key("e"));@@ -193,7 +171,7 @@ mod tests {#[test]fn concurrent_reservations_cannot_exceed_the_sender_quota() {let requests = Requests::default();- requests.start_turn("a", None);+ requests.start_turn("a", Turn::Chat(0));let barrier = std::sync::Barrier::new(MAX_PENDING_MESSAGES);let admitted = std::thread::scope(|scope| {let handles: Vec<_> = (0..MAX_PENDING_MESSAGES)diff --git a/host/src/chat/team/tests.rs b/host/src/chat/team/tests.rsindex 7ca1955f..c903a0eb 100644--- a/host/src/chat/team/tests.rs+++ b/host/src/chat/team/tests.rs@@ -1,25 +1,9 @@use super::*;+use crate::LockExt;+use crate::hub::BotStatus;use crate::store::Store;use std::path::PathBuf;--#[test]-fn wait_graph_rejects_self_duplicates_and_indirect_cycles() {- let requests = Requests::default();- for bot in ["a", "b", "c", "d"] {- requests.start_turn(bot, None);- }- assert!(requests.begin("self", "a", "a").is_err());- let (ab, _) = requests.begin("ab", "a", "b").unwrap();- assert!(requests.begin("duplicate", "a", "b").is_err());- let _bc = requests.begin("bc", "b", "c").unwrap();- assert!(requests.begin("ca", "c", "a").is_err());- let _dc = requests.begin("dc", "d", "c").unwrap();- requests.cancel_from("a");- assert!(*ab.borrow());- assert!(requests.begin("late", "a", "d").is_err());- requests.0.locked().pending.remove("ab");- assert!(requests.begin("ca", "c", "a").is_ok());-}+use std::time::Duration;struct Fixture {hub: Arc<Hub>,@@ -51,29 +35,19 @@ impl Fixture {19222,);hub.start().unwrap();- hub.set_runtime("a", |r| r.status = BotStatus::Working);- hub.team.start_turn("a", None);- Self { hub, dir }+ let f = Self { hub, dir };+ f.sending("a");+ f}- fn request(&self, message: &str) -> tokio::task::JoinHandle<Result<Value>> {- let hub = self.hub.clone();- let message = message.to_owned();- tokio::spawn(async move {- crate::api::dispatch(- &hub,- &crate::api::devices::Caller::Local,- "teamCall",- json!({- "botId": "a", "name": "ask_bot", "arguments": {"botId": "b", "message": message},- }),- )- .await- })+ /// `bot` is in a turn of its own, so it may send; its replies start real turns that end this.+ fn sending(&self, bot: &str) {+ self.hub.set_runtime(bot, |r| r.status = BotStatus::Working);+ self.hub.team.start_turn(bot, Turn::Chat(0));}- async fn message(&self, message: &str) -> Result<Value> {- call(&self.hub, "a", "message_bot", &json!({"botId": "b", "message": message})).await+ fn message(&self, message: &str) -> Result<Value> {+ call(&self.hub, "a", "message_bot", &json!({"botId": "b", "message": message}))}fn notices(&self, request: &Value) -> Vec<crate::store::Entry> {@@ -84,15 +58,20 @@ impl Fixture {.collect()}- async fn send_user(&self, text: &str) {- let result = crate::api::dispatch(+ async fn send_user(&self, text: &str) -> Value {+ self.send_to("b", text).await+ }++ /// The user's message in `bot`'s chat.+ async fn send_to(&self, bot: &str, text: &str) -> Value {+ let sent = crate::api::dispatch(&self.hub,&crate::api::devices::Caller::Local,"send",- json!({"botId": "b", "text": text}),+ json!({"botId": bot, "text": text}),).await;- result.unwrap();+ sent.unwrap()}async fn until(&self, condition: impl Fn() -> bool) {@@ -106,14 +85,39 @@ impl Fixture {.expect("fixture condition timed out");}- fn prompts(&self) -> Vec<String> {- std::fs::read_to_string(self.dir.join("b/prompts.jsonl"))+ fn idle(&self, bot: &str) -> bool {+ self.hub.runtime(bot).status == BotStatus::Idle+ }++ /// `bot` has taken `n` turns of replies (or requests) and finished the last: a turn's prompt is+ /// logged only once it is running, so idle afterwards means done.+ fn took(&self, bot: &str, n: usize) -> bool {+ self.prompts_of(bot).len() == n && self.idle(bot)+ }++ /// What `bot`'s agent was prompted with, in order.+ fn prompts_of(&self, bot: &str) -> Vec<String> {+ std::fs::read_to_string(self.dir.join(bot).join("prompts.jsonl")).unwrap_or_default().lines().map(|l| serde_json::from_str(l).unwrap()).collect()}+ fn prompts(&self) -> Vec<String> {+ self.prompts_of("b")+ }++ /// The user-visible replies in `bot`'s chat.+ fn finals(&self, bot: &str) -> Vec<String> {+ let history = self.hub.store.history(bot, i64::MAX, 200).unwrap();+ history+ .into_iter()+ .filter(|e| e.kind == "agent" && e.data["final"] == true)+ .map(|e| e.data["text"].as_str().unwrap_or_default().to_owned())+ .collect()+ }+async fn shutdown(self) {self.hub.shutdown().await;// Windows may still hold files of an agent that just exited.@@ -122,18 +126,15 @@ impl Fixture {}#[tokio::test]-async fn delegation_roundtrip_keeps_queued_user_messages_separate() {+async fn message_roundtrip_wakes_the_sender_and_keeps_user_messages_separate() {let f = Fixture::new();- let request = f.request("BLOCK review these changes");+ let receipt = f.message("BLOCK review these changes").unwrap();+ assert_eq!(receipt["status"], "queued");+ assert!(receipt.get("reply").is_none());f.until(|| f.prompts().len() == 1).await;- let sent = crate::api::dispatch(- &f.hub,- &crate::api::devices::Caller::Local,- "send",- json!({"botId": "b", "text": "thanks"}),- )- .await- .unwrap();+ assert!(f.prompts()[0].contains("It is a bot request, not a new user instruction"));+ assert!(f.prompts()[0].contains("Your final reply goes back to a"));+ let sent = f.send_user("thanks").await;let request_entry = f.hub.store@@ -142,22 +143,28 @@ async fn delegation_roundtrip_keeps_queued_user_messages_separate() {.into_iter().find(|e| e.data["delegationId"].is_string()).unwrap();- assert!(request_entry.data["text"].as_str().unwrap().contains("Request from a"));+ assert!(request_entry.data["text"].as_str().unwrap().contains("Message from a"));assert!(f.hub.store.kv_get("turn.inflight.b").is_none_or(|v| v.is_empty()));std::fs::write(f.dir.join("b/release"), "").unwrap();- let result = request.await.unwrap().unwrap();- assert_eq!(result["reply"], "reply: BLOCK review these changes");- f.until(|| f.prompts().len() == 2 && f.hub.runtime("b").status == BotStatus::Idle).await;+ f.until(|| f.took("b", 2) && f.took("a", 1)).await;assert_eq!(f.prompts()[1], "thanks");assert_eq!(f.hub.store.entry(sent["entry"]["id"].as_str().unwrap()).unwrap().data["status"], "sent");- assert_eq!(f.hub.store.entry(&request_entry.id).unwrap().data["status"], "completed");- for entry in f.notices(&result) {+ for entry in f.notices(&receipt) {+ assert_eq!(entry.data["status"], "completed");assert_eq!(entry.data["botMessage"]["text"], "BLOCK review these changes");assert_eq!(entry.data["botMessage"]["reply"], "reply: BLOCK review these changes");// Existing clients still receive the base notice display fields.let heading = entry.data["heading"].as_str().unwrap();assert_eq!(entry.data["text"], format!("{heading}\nReply from b:\nreply: BLOCK review these changes"));}+ // The answer is a's: b's chat keeps it in the trace, a takes it up in a turn of its own.+ assert_eq!(f.finals("b"), ["reply: thanks"]);+ let woke = f.prompts_of("a");+ assert_eq!(woke.len(), 1);+ let id = receipt["requestId"].as_str().unwrap();+ let header = format!("[Codync: b replied to your message_bot request {id} (\"BLOCK review these changes\").]");+ assert!(woke[0].contains(&format!("{header}\nreply: BLOCK")), "the reply quotes what was asked");+ assert_eq!(f.finals("a"), ["Relayed: reply: BLOCK review these changes"]);let conversation = |peer: &str| {let hub = f.hub.clone();let peer = peer.to_owned();@@ -174,20 +181,20 @@ async fn delegation_roundtrip_keeps_queued_user_messages_separate() {};assert_eq!(conversation("b").await["entries"].as_array().unwrap().len(), 1);assert_eq!(conversation("c").await["entries"].as_array().unwrap().len(), 0);- assert!(f.hub.team.0.locked().pending.is_empty());let servers: Value = serde_json::from_slice(&std::fs::read(f.dir.join("b/servers.json")).unwrap()).unwrap();assert!(servers.as_array().unwrap().iter().any(|s| s["name"] == "team"));f.shutdown().await;}#[tokio::test]-async fn permission_cards_still_require_the_recipients_approval() {+async fn permission_cards_still_require_the_recipients_approval_and_a_request_messages_no_one() {let f = Fixture::new();- let request = f.request("PERMISSION inspect the project");+ let receipt = f.message("PERMISSION inspect the project").unwrap();f.until(|| f.hub.runtime("b").status == BotStatus::NeedsInput).await;- assert!(!request.is_finished());- let cycle = call(&f.hub, "b", "ask_bot", &json!({"botId": "a", "message": "help me back"})).await;- assert!(cycle.unwrap_err().to_string().contains("wait for each other"));+ // Its reply goes back to a: a message from this turn would be answered in b's own chat instead.+ let back = call(&f.hub, "b", "message_bot", &json!({"botId": "c", "message": "pass it on"}));+ assert!(back.unwrap_err().to_string().contains("answering another bot's request"));+ assert_eq!(f.hub.team.0.locked().messages, 1);let card = f.hub.store.history("b", i64::MAX, 100).unwrap().into_iter().find(|e| e.kind == "permission").unwrap();crate::api::dispatch(&f.hub,@@ -197,122 +204,20 @@ async fn permission_cards_still_require_the_recipients_approval() {).await.unwrap();- assert!(request.await.unwrap().is_ok());- f.shutdown().await;-}--#[tokio::test]-async fn stopping_requester_cancels_only_its_delegation() {- let f = Fixture::new();- let request = f.request("BLOCK waiting for cancellation");- f.until(|| f.prompts().len() == 1).await;- crate::api::dispatch(&f.hub, &crate::api::devices::Caller::Local, "send", json!({"botId": "b", "text": "thanks"}))- .await- .unwrap();- f.hub.send_cmd("a", Cmd::Stop).unwrap();- assert!(request.await.unwrap().unwrap_err().to_string().contains("cancelled"));- f.until(|| f.prompts().len() == 2 && f.hub.runtime("b").status == BotStatus::Idle).await;- assert_eq!(f.prompts()[1], "thanks");- assert!(f.hub.team.0.locked().pending.is_empty());- f.shutdown().await;-}--#[tokio::test]-async fn timeout_and_recipient_errors_release_waiters() {- let f = Fixture::new();- for message in ["FAIL requested failure", "EMPTY no text"] {- assert!(f.request(message).await.unwrap().is_err());- assert!(f.hub.team.0.locked().pending.is_empty());- }- let source = visible_bot(&f.hub, "a").unwrap();- let error = ask(&f.hub, &source, "b", "BLOCK timed request", Duration::from_millis(100)).await.unwrap_err();- assert!(error.to_string().contains("timed out"));- f.until(|| f.hub.runtime("b").status == BotStatus::Idle).await;- assert!(f.hub.team.0.locked().pending.is_empty());- assert!(f.request("after timeout").await.unwrap().is_ok());- f.shutdown().await;-}--#[tokio::test]-async fn invalid_hidden_and_deleted_targets_never_start() {- let f = Fixture::new();- let mut hidden = visible_bot(&f.hub, "c").unwrap();- hidden.hidden = true;- f.hub.store.save_bot(&hidden).unwrap();- let list = call(&f.hub, "a", "list_bots", &json!({})).await.unwrap();- assert_eq!(list["bots"].as_array().unwrap().len(), 1);- assert_eq!(list["bots"][0]["id"], "b");- for target in ["a", "c", "missing"] {- assert!(call(&f.hub, "a", "ask_bot", &json!({"botId": target, "message": "do work"})).await.is_err());- }- assert!(f.request(" ").await.unwrap().is_err());- f.hub.delete_bot("b").unwrap();- assert!(f.request("deleted").await.unwrap().is_err());- assert_eq!(f.prompts().len(), 0);- f.shutdown().await;-}--#[tokio::test]-async fn queued_requests_are_not_merged_and_cancelled_requests_never_execute() {- let f = Fixture::new();- f.hub.set_runtime("c", |r| r.status = BotStatus::Working);- f.hub.team.start_turn("c", None);- let first = f.request("BLOCK first request");- f.until(|| f.prompts().len() == 1).await;- let hub = f.hub.clone();- let second =- tokio::spawn(- async move { call(&hub, "c", "ask_bot", &json!({"botId": "b", "message": "second request"})).await },- );- f.until(|| f.hub.team.0.locked().pending.len() == 2).await;- assert_eq!(f.prompts().len(), 1);- std::fs::write(f.dir.join("b/release"), "").unwrap();- assert_eq!(first.await.unwrap().unwrap()["reply"], "reply: BLOCK first request");- assert_eq!(second.await.unwrap().unwrap()["reply"], "reply: second request");- assert_eq!(f.prompts().len(), 2);-- std::fs::remove_file(f.dir.join("b/release")).unwrap();- let third = f.request("BLOCK third request");- f.until(|| f.prompts().len() == 3).await;- let source = visible_bot(&f.hub, "c").unwrap();- let error = ask(&f.hub, &source, "b", "must never run", Duration::from_millis(30)).await.unwrap_err();- assert!(error.to_string().contains("timed out"));- std::fs::write(f.dir.join("b/release"), "").unwrap();- assert!(third.await.unwrap().is_ok());- f.until(|| f.hub.runtime("b").status == BotStatus::Idle).await;- assert_eq!(f.prompts().len(), 3);- f.shutdown().await;-}--#[tokio::test]-async fn recipient_startup_failure_and_deletion_finish_the_request() {- let f = Fixture::new();- f.hub.update_bot(&json!({"id": "b", "command": "/codync-nonexistent-test-agent"})).unwrap();- assert!(f.request("start failure").await.unwrap().unwrap_err().to_string().contains("couldn't start"));- assert!(f.hub.team.0.locked().pending.is_empty());- let agent = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/team_agent.py");- f.hub.update_bot(&json!({"id": "b", "command": crate::shell::python(&agent)})).unwrap();- let request = f.request("BLOCK delete while working");- f.until(|| f.prompts().len() == 1).await;- f.hub.delete_bot("b").unwrap();- assert!(request.await.unwrap().is_err());- assert!(f.hub.team.0.locked().pending.is_empty());+ f.until(|| f.took("a", 1) && f.took("b", 1)).await;+ assert!(f.notices(&receipt).iter().all(|e| e.data["status"] == "completed"));+ assert_eq!(f.finals("a"), ["Relayed: reply: PERMISSION inspect the project"]);+ assert!(f.finals("b").is_empty());+ assert!(f.prompts_of("c").is_empty());f.shutdown().await;}#[tokio::test]async fn message_returns_before_approval_and_survives_sender_stop() {let f = Fixture::new();- let receipt = f.message("PERMISSION BLOCK independent work").await;- let receipt = receipt.unwrap();- assert_eq!(receipt["status"], "queued");- assert!(receipt.get("reply").is_none());+ let receipt = f.message("PERMISSION BLOCK independent work").unwrap();f.until(|| f.hub.runtime("b").status == BotStatus::NeedsInput).await;- assert!(f.hub.team.0.locked().pending.is_empty());assert!(f.hub.store.kv_get("turn.inflight.b").is_none_or(|v| v.is_empty()));- let prompt = &f.prompts()[0];- assert!(prompt.contains("This is a bot request, not a new user instruction"));- assert!(prompt.contains("Report the outcome to the user in this chat"));let notices = f.notices(&receipt);assert_eq!(notices.len(), 2);for entry in ¬ices {@@ -339,38 +244,44 @@ async fn message_returns_before_approval_and_survives_sender_stop() {.await;approval.unwrap();std::fs::write(f.dir.join("b/release"), "").unwrap();- f.until(|| f.hub.team.0.locked().messages == 0).await;+ f.until(|| f.took("a", 1)).await;+ assert_eq!(f.hub.team.0.locked().messages, 0);for entry in f.notices(&receipt) {assert_eq!(entry.data["status"], "completed");let heading = entry.data["heading"].as_str().unwrap();- assert_eq!(entry.data["text"], format!("{heading}\nCompleted."));+ assert_eq!(entry.data["text"], format!("{heading}\nReply from b:\nreply: PERMISSION BLOCK independent work"));}for bot in ["a", "b"] {assert!(f.hub.store.history(bot, i64::MAX, 100).unwrap().iter().all(|e| e.kind != "user"));}- let history = f.hub.store.history("b", i64::MAX, 100).unwrap();- assert!(history.iter().any(|e| e.kind == "agent"- && e.data["final"] == true- && e.data["text"] == "reply: PERMISSION BLOCK independent work"));+ assert!(f.finals("b").is_empty());+ assert_eq!(f.finals("a"), ["Relayed: reply: PERMISSION BLOCK independent work"]);f.shutdown().await;}#[tokio::test]-async fn cancelling_an_ask_preserves_the_independent_message_behind_it() {+async fn failures_reach_the_sender_and_release_capacity() {let f = Fixture::new();- let ask = f.request("BLOCK synchronous work");- f.until(|| f.prompts().len() == 1).await;- let receipt = f.message("independent work").await;- let receipt = receipt.unwrap();- assert!(f.notices(&receipt).iter().all(|e| e.data["status"] == "queued"));- assert_eq!(f.hub.team.0.locked().pending.len(), 1);- f.hub.send_cmd("a", Cmd::Stop).unwrap();- let result = ask.await;- assert!(result.unwrap().unwrap_err().to_string().contains("cancelled"));- f.until(|| f.hub.team.0.locked().messages == 0).await;- assert_eq!(f.prompts().len(), 2);- assert!(f.prompts()[1].ends_with("\n\nindependent work"));- assert!(f.notices(&receipt).iter().all(|e| e.data["status"] == "completed"));+ for (n, message) in ["FAIL agent error", "REFUSE requested refusal", "EMPTY no report"].into_iter().enumerate() {+ let receipt = f.message(message).unwrap();+ f.until(|| f.took("a", n + 1)).await;+ assert_eq!(f.hub.team.0.locked().messages, 0);+ assert!(f.notices(&receipt).iter().all(|e| e.data["status"] == "failed"));+ f.sending("a");+ }+ f.hub.update_bot(&json!({"id": "b", "command": "/codync-nonexistent-test-agent"})).unwrap();+ let receipt = f.message("startup failure").unwrap();+ f.until(|| f.took("a", 4)).await;+ assert!(+ f.notices(&receipt)+ .iter()+ .all(|e| e.data["status"] == "failed"+ && e.data["text"].as_str().unwrap().contains("couldn't start recipient"))+ );+ let woke = f.prompts_of("a");+ assert_eq!(woke.len(), 4);+ assert!(woke.iter().all(|p| p.contains("[Codync: b couldn't finish your message_bot request")));+ assert!(woke[3].contains("couldn't start recipient"));f.shutdown().await;}@@ -379,90 +290,105 @@ async fn recipient_stop_cancels_queued_messages_before_execution() {let f = Fixture::new();f.send_user("BLOCK user work").await;f.until(|| f.prompts().len() == 1).await;- let first = f.message("must never run").await;- let first = first.unwrap();- let second = f.message("also must never run").await;- let second = second.unwrap();+ let first = f.message("must never run").unwrap();+ let second = f.message("also must never run").unwrap();f.hub.send_cmd("b", Cmd::Stop).unwrap();- f.until(|| f.hub.team.0.locked().messages == 0 && f.hub.runtime("b").status == BotStatus::Idle).await;+ f.until(|| f.hub.team.0.locked().messages == 0 && f.idle("b")).await;for receipt in [&first, &second] {let notices = f.notices(receipt);assert_eq!(notices.len(), 2);assert!(notices.iter().all(|e| e.data["status"] == "cancelled"&& e.data["text"].as_str().unwrap().ends_with("Cancelled before execution.")));}- let later = f.message("new work after Stop").await;- let later = later.unwrap();- f.until(|| f.hub.team.0.locked().messages == 0).await;+ let later = f.message("new work after Stop").unwrap();+ f.until(|| f.took("a", 1)).await;assert_eq!(f.prompts().len(), 2);assert!(f.prompts()[1].ends_with("\n\nnew work after Stop"));assert!(f.notices(&later).iter().all(|e| e.data["status"] == "completed"));+ // What the user stopped doesn't wake the sender: only the later message's reply did.+ assert_eq!(f.prompts_of("a").len(), 1);f.shutdown().await;}#[tokio::test]async fn recipient_stop_cancels_running_message_and_releases_capacity() {let f = Fixture::new();- let receipt = f.message("BLOCK running work").await;- let receipt = receipt.unwrap();+ let receipt = f.message("BLOCK running work").unwrap();f.until(|| f.prompts().len() == 1).await;f.hub.send_cmd("b", Cmd::Stop).unwrap();f.until(|| f.hub.team.0.locked().messages == 0).await;assert!(f.notices(&receipt).iter().all(|e| e.data["status"] == "cancelled"&& e.data["text"].as_str().unwrap().contains("Partial work may have happened")));+ // What the user stopped doesn't wake the sender: its only turn is the later message's reply.+ let later = f.message("later work").unwrap();+ f.until(|| f.took("a", 1)).await;+ assert!(f.prompts_of("a")[0].contains(later["requestId"].as_str().unwrap()));+ f.shutdown().await;+}++#[tokio::test]+async fn replies_that_arrive_while_the_sender_works_are_one_turn() {+ let f = Fixture::new();+ f.send_to("a", "BLOCK user work").await;+ f.until(|| f.prompts_of("a").len() == 1).await;+ f.message("first").unwrap();+ call(&f.hub, "a", "message_bot", &json!({"botId": "c", "message": "second"})).unwrap();+ f.until(|| f.took("b", 1) && f.took("c", 1)).await;+ std::fs::write(f.dir.join("a/release"), "").unwrap();+ f.until(|| f.took("a", 2)).await;+ let woke = &f.prompts_of("a")[1];+ assert!(woke.contains("[Codync: b replied") && woke.contains("[Codync: c replied"), "{woke}");+ f.shutdown().await;+}++#[tokio::test]+async fn stopping_the_sender_drops_the_replies_queued_for_it() {+ let f = Fixture::new();+ f.send_to("a", "BLOCK user work").await;+ f.until(|| f.prompts_of("a").len() == 1).await;+ let receipt = f.message("work").unwrap();+ f.until(|| f.took("b", 1)).await;+ f.hub.send_cmd("a", Cmd::Stop).unwrap();+ f.until(|| f.idle("a")).await;+ // Both notices still show the outcome.+ assert!(f.notices(&receipt).iter().all(|e| e.data["status"] == "completed"));+ f.send_to("a", "next").await;+ f.until(|| f.took("a", 2)).await;+ assert_eq!(f.prompts_of("a")[1], "next");f.shutdown().await;}#[tokio::test]-async fn mixed_requests_preserve_fifo_and_user_batch_boundaries() {+async fn requests_from_several_senders_keep_fifo_and_user_batch_boundaries() {let f = Fixture::new();+ f.sending("c");f.send_user("BLOCK current turn").await;f.until(|| f.prompts().len() == 1).await;f.send_user("first user").await;f.send_user("second user").await;- let first = f.message("first message").await;- let first = first.unwrap();- let ask = f.request("synchronous request");- f.until(|| f.hub.team.0.locked().pending.len() == 1).await;- let second = f.message("second message").await;- let second = second.unwrap();+ let first = f.message("first message").unwrap();+ let from_c = call(&f.hub, "c", "message_bot", &json!({"botId": "b", "message": "message from c"}));+ let second = f.message("second message").unwrap();f.send_user("third user").await;f.send_user("fourth user").await;std::fs::write(f.dir.join("b/release"), "").unwrap();- let result = ask.await;- assert_eq!(result.unwrap().unwrap()["reply"], "reply: synchronous request");- f.until(|| f.prompts().len() == 6 && f.hub.runtime("b").status == BotStatus::Idle).await;+ let both = || {+ let a = f.finals("a").join(" | ");+ a.contains("reply: first message") && a.contains("reply: second message")+ };+ f.until(|| f.took("b", 6) && f.took("c", 1) && both() && f.idle("a")).await;let prompts = f.prompts();assert_eq!(prompts[1], "first user\n\nsecond user");assert!(prompts[2].ends_with("\n\nfirst message"));- assert!(prompts[3].ends_with("\n\nsynchronous request"));+ assert!(prompts[3].ends_with("\n\nmessage from c"));assert!(prompts[4].ends_with("\n\nsecond message"));assert_eq!(prompts[5], "third user\n\nfourth user");- for receipt in [&first, &second] {+ for receipt in [&first, &from_c.unwrap(), &second] {assert!(f.notices(receipt).iter().all(|e| e.data["status"] == "completed"));}- f.shutdown().await;-}--#[tokio::test]-async fn message_failures_finish_notices_and_release_capacity() {- let f = Fixture::new();- for message in ["FAIL agent error", "REFUSE requested refusal", "EMPTY no report"] {- let receipt = f.message(message).await;- let receipt = receipt.unwrap();- f.until(|| f.hub.team.0.locked().messages == 0).await;- assert!(f.notices(&receipt).iter().all(|e| e.data["status"] == "failed"));- }- f.hub.update_bot(&json!({"id": "b", "command": "/codync-nonexistent-test-agent"})).unwrap();- let receipt = f.message("startup failure").await;- let receipt = receipt.unwrap();- f.until(|| f.hub.team.0.locked().messages == 0).await;- assert!(- f.notices(&receipt)- .iter()- .all(|e| e.data["status"] == "failed"- && e.data["text"].as_str().unwrap().contains("couldn't start recipient"))- );+ // Each reply goes to the bot that asked; a's may come in one turn or two.+ assert!(!f.finals("a").join(" | ").contains("message from c"));+ assert_eq!(f.finals("c"), ["Relayed: reply: message from c"]);f.shutdown().await;}@@ -476,7 +402,7 @@ async fn failed_message_admission_never_executes_or_leaks_capacity() {BEGIN SELECT RAISE(ABORT, 'fixture save failure'); END;",).unwrap();- let result = f.message("cannot save recipient notice").await;+ let result = f.message("cannot save recipient notice");assert!(result.is_err());assert_eq!(f.hub.team.0.locked().messages, 0);let history = f.hub.store.history("a", i64::MAX, 100).unwrap();@@ -485,7 +411,7 @@ async fn failed_message_admission_never_executes_or_leaks_capacity() {db.execute_batch("DROP TRIGGER reject_message;").unwrap();f.hub.send_cmd("b", Cmd::Shutdown).unwrap();f.until(|| f.hub.send_cmd("b", Cmd::RefreshTools).is_err()).await;- let result = f.message("recipient actor has exited").await;+ let result = f.message("recipient actor has exited");assert!(result.is_err());assert_eq!(f.hub.team.0.locked().messages, 0);assert_eq!(f.prompts().len(), 0);@@ -503,8 +429,7 @@ async fn shutdown_discards_accepted_mailbox_messages_and_finishes_notices() {// Admission is synchronous: these commands enter the mailbox in order// before the actor runs, so shutdown disposes of the unread request.f.hub.send_cmd("b", Cmd::Shutdown).unwrap();- let receipt = f.message("must never start").await;- let receipt = receipt.unwrap();+ let receipt = f.message("must never start").unwrap();f.until(|| f.hub.team.0.locked().messages == 0).await;assert!(f.notices(&receipt).iter().all(|e| e.data["status"] == "cancelled"));assert_eq!(f.prompts().len(), 0);@@ -517,34 +442,45 @@ async fn invalid_messages_never_start_and_stopped_senders_cannot_admit_more() {let mut hidden = visible_bot(&f.hub, "c").unwrap();hidden.hidden = true;f.hub.store.save_bot(&hidden).unwrap();+ let list = call(&f.hub, "a", "list_bots", &json!({})).unwrap();+ assert_eq!(list["bots"].as_array().unwrap().len(), 1);+ assert_eq!(list["bots"][0]["id"], "b");for target in ["a", "c", "missing"] {- let result = call(&f.hub, "a", "message_bot", &json!({"botId": target, "message": "work"})).await;+ let result = call(&f.hub, "a", "message_bot", &json!({"botId": target, "message": "work"}));assert!(result.is_err());}for message in [" ".to_owned(), "x".repeat(MAX_MESSAGE_BYTES + 1)] {- let result = f.message(&message).await;+ let result = f.message(&message);assert!(result.is_err());}- f.hub.team.cancel_from("a");- let result = f.message("late request").await;+ f.hub.team.end_turn("a");+ let result = f.message("late request");assert!(result.unwrap_err().to_string().contains("no longer working"));- f.hub.team.start_turn("a", None);+ f.hub.team.start_turn("a", Turn::Chat(0));f.hub.delete_bot("b").unwrap();- let result = f.message("deleted recipient").await;+ let result = f.message("deleted recipient");assert!(result.is_err());assert_eq!(f.hub.team.0.locked().messages, 0);assert_eq!(f.prompts().len(), 0);f.shutdown().await;}+#[tokio::test]+async fn a_member_in_a_room_turn_mentions_instead_of_messaging() {+ let f = Fixture::new();+ f.hub.set_runtime("a", |r| r.lane = Some(crate::store::Lane::main("crew")));+ let result = f.message("work");+ assert!(result.unwrap_err().to_string().contains("@-mention the room's members"));+ assert_eq!(f.hub.team.0.locked().messages, 0);+ f.shutdown().await;+}+#[tokio::test]async fn sender_deletion_preserves_messages_and_recipient_deletion_closes_them() {let f = Fixture::new();- let running = f.message("BLOCK active message").await;- let running = running.unwrap();+ let running = f.message("BLOCK active message").unwrap();f.until(|| f.prompts().len() == 1).await;- let queued = f.message("queued message").await;- let queued = queued.unwrap();+ let queued = f.message("queued message").unwrap();f.hub.delete_bot("a").unwrap();assert_eq!(f.hub.team.0.locked().messages, 2);assert_eq!(f.hub.runtime("b").status, BotStatus::Working);@@ -556,28 +492,28 @@ async fn sender_deletion_preserves_messages_and_recipient_deletion_closes_them()f.shutdown().await;let f = Fixture::new();- let running = f.message("BLOCK active message").await;- let running = running.unwrap();+ let running = f.message("BLOCK active message").unwrap();f.until(|| f.prompts().len() == 1).await;- let queued = f.message("queued message").await;- let queued = queued.unwrap();+ let queued = f.message("queued message").unwrap();f.hub.delete_bot("b").unwrap();f.until(|| f.hub.team.0.locked().messages == 0).await;for receipt in [&running, &queued] {assert!(f.notices(receipt).iter().all(|e| e.data["status"] == "cancelled"));}assert_eq!(f.prompts().len(), 1);+ // Deleting the recipient doesn't wake the sender: its only turn is a later message's reply.+ let later = call(&f.hub, "a", "message_bot", &json!({"botId": "c", "message": "later work"})).unwrap();+ f.until(|| f.took("a", 1)).await;+ assert!(f.prompts_of("a")[0].contains(later["requestId"].as_str().unwrap()));f.shutdown().await;}#[tokio::test]async fn message_turns_have_no_resume_marker_and_restart_expires_both_notices() {let f = Fixture::new();- let running = f.message("BLOCK active message").await;- let running = running.unwrap();+ let running = f.message("BLOCK active message").unwrap();f.until(|| f.prompts().len() == 1).await;- let queued = f.message("queued message").await;- let queued = queued.unwrap();+ let queued = f.message("queued message").unwrap();assert!(f.hub.store.kv_get("turn.inflight.b").is_none_or(|v| v.is_empty()));// A new store connection applies the same startup cleanup to the// persisted queued and running notices, without replaying a prompt.@@ -601,7 +537,7 @@ fn restart_marks_requests_interrupted_without_replaying_them() {EntryKind::Notice,1,&json!({- "delegationId": "d", "status": "sent", "heading": "Request from a",+ "delegationId": "d", "status": "sent", "heading": "Message from a","botMessage": {"sourceBotId": "a", "targetBotId": "b", "text": "Work"},}),)diff --git a/host/src/hub.rs b/host/src/hub.rsindex 40a37b85..485c8f0b 100644--- a/host/src/hub.rs+++ b/host/src/hub.rs@@ -286,7 +286,7 @@ impl Hub {pub fn delete_bot(&self, id: &str) -> Result<()> {self.routines.disable_bot(&self.store, id)?;- self.team.cancel_bot(id);+ self.team.end_turn(id);self.groups.stop(self, id);let _ = self.send_cmd(id, Cmd::Shutdown);self.bots.locked().remove(id);diff --git a/host/src/mcp.rs b/host/src/mcp.rsindex 7aace2b2..93ee14c5 100644--- a/host/src/mcp.rs+++ b/host/src/mcp.rs@@ -37,7 +37,7 @@ pub async fn serve(bot: String, port: u16, server: Server) -> Result<()> {let token: Arc<str> = token.trim().into();let bot: Arc<str> = bot.into();let mut lines = BufReader::new(tokio::io::stdin()).lines();- // Requests run side by side (an ask_bot can take minutes); their replies share stdout.+ // Requests run side by side (a manage approval can take minutes); their replies share stdout.let (replies, mut outbox) = mpsc::unbounded_channel::<Value>();tokio::spawn(async move {let mut out = tokio::io::stdout();@@ -144,7 +144,7 @@ async fn call(port: u16, token: &str, bot: &str, params: &Value, server: Server)Server::Routines => ("routineCall", Duration::from_secs(30)),Server::Computer => ("computerCall", Duration::from_secs(60)),Server::Chat => ("chatCall", Duration::from_secs(if params["name"] == "send_file" { 70 } else { 30 })),- Server::Team => ("teamCall", crate::chat::team::ASK_TIMEOUT + Duration::from_secs(30)),+ Server::Team => ("teamCall", Duration::from_secs(30)),Server::Manage => ("manageCall", crate::chat::manage::APPROVAL_TIMEOUT + Duration::from_secs(30)),Server::Memory => ("memoryCall", Duration::from_secs(120)),Server::Composio => ("composioCall", Duration::from_secs(120)),diff --git a/host/tests/fixtures/team_agent.py b/host/tests/fixtures/team_agent.pyindex ecd4ba6e..7371f5fd 100644--- a/host/tests/fixtures/team_agent.py+++ b/host/tests/fixtures/team_agent.py@@ -37,7 +37,7 @@ def mcp_call(server_name, tool, arguments):tools = rpc(2, "tools/list", {})assert any(t["name"] == tool for t in tools["result"]["tools"])if server_name == "team":- assert {t["name"] for t in tools["result"]["tools"]} == {"list_bots", "ask_bot", "message_bot"}+ assert {t["name"] for t in tools["result"]["tools"]} == {"list_bots", "message_bot"}roster = rpc(3, "tools/call", {"name": "list_bots", "arguments": {}})assert any(b["id"] == arguments["botId"] for b in json.loads(roster["result"]["content"][0]["text"])["bots"])response = rpc(4, "tools/call", {"name": tool, "arguments": arguments})@@ -45,37 +45,53 @@ def mcp_call(server_name, tool, arguments):return response["result"]-def team_call(target, tool, message):- return mcp_call("team", tool, {"botId": target, "message": message})+def team_call(target, message):+ return mcp_call("team", "message_bot", {"botId": target, "message": message})+++def chain():+ """Hands the chain on to the bot in handoff.json; what the turn replies."""+ response = team_call(json.loads(pathlib.Path("handoff.json").read_text())["target"], "CHAIN")+ return "Chain stopped: " + response["content"][0]["text"] if response.get("isError") else "Chain forwarded"+++REPLIES_END = "\n\n[Codync: these are bot replies"def prompt(request):text = request["params"]["prompt"][0]["text"]with open("prompts.jsonl", "a") as log:log.write(json.dumps(text) + "\n")- if text.startswith(("DELEGATE ", "MESSAGE ", "ASK_REPORT ", "MESSAGE_REPORT ")):- independent = text.startswith(("MESSAGE ", "MESSAGE_REPORT "))+ if REPLIES_END in text:+ # Replies to requests this bot sent: relay what they said (whatever words they carry),+ # or pass on a chain the peer handed back.+ parts = text.split(REPLIES_END, 1)[0].split("\n\n")+ relayed = [p.split(".]\n", 1)[1] if ".]\n" in p else "failed" for p in parts]+ reply = chain() if any("CHAIN" in r for r in relayed) else "Relayed: " + " | ".join(relayed)+ update({"sessionUpdate": "agent_message_chunk", "content": {"type": "text", "text": reply}})+ # A text update can reach sync before the host handles turn completion.+ # Keep that interval deterministic when the bounded chain stops.+ if reply.startswith("Chain stopped"):+ time.sleep(0.3)+ send({"id": request["id"], "result": {"stopReason": "end_turn"}})+ return+ if text.startswith(("DELEGATE ", "DELEGATE_REPORT ")):target = text.split()[1]- update({"sessionUpdate": "tool_call", "toolCallId": "delegate", "title": "Ask reviewer", "status": "in_progress"})- message = "REPORT" if "_REPORT " in text else "PERMISSION review the changes"- response = team_call(target, "message_bot" if independent else "ask_bot", message)+ update({"sessionUpdate": "tool_call", "toolCallId": "delegate", "title": "Message reviewer", "status": "in_progress"})+ message = "REPORT" if text.startswith("DELEGATE_REPORT ") else "PERMISSION review the changes"+ response = team_call(target, message)assert not response.get("isError"), responseresult = json.loads(response["content"][0]["text"])- if independent:- assert result["status"] == "queued" and "reply" not in result- text = "Message queued"- else:- text = "Team reply: " + result["reply"]+ assert result["status"] == "queued" and "reply" not in resultupdate({"sessionUpdate": "tool_call_update", "toolCallId": "delegate", "status": "completed"})- update({"sessionUpdate": "agent_message_chunk", "content": {"type": "text", "text": text}})+ update({"sessionUpdate": "agent_message_chunk", "content": {"type": "text", "text": "Message queued"}})send({"id": request["id"], "result": {"stopReason": "end_turn"}})returnif text.split("\n\n")[-1] == "REPORT":response = mcp_call("chat", "send_message", {"text": "Report for the user"})- if "requests your help" in text:+ if "Your final reply goes back to" in text:assert response.get("isError"), responseassert "requesting bot" in response["content"][0]["text"]- assert "Do not use send_message or message_bot" in textreply = "Answer for the requesting bot"else:assert not response.get("isError"), response@@ -86,18 +102,12 @@ def prompt(request):send({"id": request["id"], "result": {"stopReason": "end_turn"}})returnif text.split("\n\n")[-1] == "CHAIN":- route = json.loads(pathlib.Path("handoff.json").read_text())- response = team_call(route["target"], route["tool"], "CHAIN")- if response.get("isError"):- reply = "Chain stopped: " + response["content"][0]["text"]- else:- result = json.loads(response["content"][0]["text"])- reply = result.get("reply", "Chain forwarded")+ reply = chain()+ if "Your final reply goes back to" in text:+ # A request turn messages no one: it hands the chain back in its reply.+ assert "answering another bot's request" in reply, reply+ reply = "CHAIN back"update({"sessionUpdate": "agent_message_chunk", "content": {"type": "text", "text": reply}})- # A text update can reach sync before the host handles turn completion.- # Keep that interval deterministic when the bounded chain stops.- if response.get("isError"):- time.sleep(0.3)send({"id": request["id"], "result": {"stopReason": "end_turn"}})returnif text.split("\n\n")[-1].startswith("MANAGE "):@@ -136,6 +146,8 @@ def prompt(request):room = text.split("New messages in the room (oldest first):\n", 1)[-1].split("\n\n", 1)[0]last = room.strip().splitlines()[-1] if "New messages" in text else ""reply = "reply: group" if last.startswith("User:") else "(pass)"+ if last.startswith("User:") and "PING" in last:+ reply = "@b over to you"if "REACT" in last:response = mcp_call("chat", "react", {"emoji": "👍", "to": "user"})assert not response.get("isError"), responsediff --git a/host/tests/team_e2e.rs b/host/tests/team_e2e.rsindex 1a23ff57..dbcaabe5 100644--- a/host/tests/team_e2e.rs+++ b/host/tests/team_e2e.rs@@ -1,5 +1,5 @@//! A real host and built-in MCP process, with deterministic ACP agents instead-//! of paid providers. Exercises discovery, delegation, approval and reply sync.+//! of paid providers. Exercises discovery, messages, approval and the reply's way back.#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]@@ -107,83 +107,76 @@ impl Host {}}+fn finals(history: &Value) -> Vec<&str> {+ history["entries"]+ .as_array()+ .unwrap()+ .iter()+ .filter(|e| e["kind"] == "agent" && e["data"]["final"] == true)+ .map(|e| e["data"]["text"].as_str().unwrap())+ .collect()+}+#[tokio::test]-async fn agent_uses_team_mcp_and_returns_the_reviewers_answer() {+async fn a_bot_messages_another_and_relays_its_reply_to_the_user() {let host = Host::start().await;let lead = host.bot("lead").await;let reviewer = host.bot("reviewer").await;host.call("send", json!({"botId": lead, "text": format!("DELEGATE {reviewer}")})).await;let permission = host.wait_for(&reviewer, |e| e["kind"] == "permission" && e["data"]["status"] == "pending").await;- let lead_history = host.call("history", json!({"botId": lead})).await;- assert!(!lead_history["entries"].as_array().unwrap().iter().any(|e| e["data"]["final"] == true));+ // The lead didn't wait: its turn ended as soon as the request was queued.+ let queued = host.wait_for(&lead, |e| e["kind"] == "agent" && e["data"]["final"] == true).await;+ assert_eq!(queued["data"]["text"], "Message queued");+ // Stopping the sender leaves the recipient's approval and the accepted request alone.+ host.call("stop", json!({"botId": lead})).await;host.call("respondPermission", json!({"entryId": permission["id"], "optionId": "allow"})).await;- let final_reply = host.wait_for(&lead, |e| e["kind"] == "agent" && e["data"]["final"] == true).await;- assert_eq!(final_reply["data"]["text"], "Team reply: reply: PERMISSION review the changes");- let sync = common::snapshot(&host.base, &host.token).await;+ let relayed = host+ .wait_for(&lead, |e| {+ e["kind"] == "agent" && e["data"]["final"] == true && e["data"]["text"] != "Message queued"+ })+ .await;+ assert_eq!(relayed["data"]["text"], "Relayed: reply: PERMISSION review the changes");+ let sync = host.wait_finished().await;let requests: Vec<_> =sync["entries"].as_array().unwrap().iter().filter(|e| e["data"]["delegationId"].is_string()).collect();assert_eq!(requests.len(), 2);- assert!(requests.iter().all(|e| e["data"]["status"] == "completed"));assert_eq!(requests[0]["data"]["delegationId"], requests[1]["data"]["delegationId"]);- assert!(requests.iter().all(|e| e["data"]["botMessage"]["reply"] == "reply: PERMISSION review the changes"));+ for entry in &requests {+ assert_eq!(entry["kind"], "notice");+ assert_eq!(entry["data"]["sourceBotId"], lead);+ assert_eq!(entry["data"]["targetBotId"], reviewer);+ assert_eq!(entry["data"]["status"], "completed");+ assert_eq!(entry["data"]["botMessage"]["reply"], "reply: PERMISSION review the changes");+ }let conversation = host.call("botConversation", json!({"botId": lead, "peerId": reviewer})).await;assert_eq!(conversation["entries"].as_array().unwrap().len(), 1);let recipient_history = host.call("history", json!({"botId": reviewer})).await;- assert!(!recipient_history["entries"].as_array().unwrap().iter().any(|e| e["data"]["final"] == true));+ assert!(finals(&recipient_history).is_empty(), "the answer is the lead's, not the reviewer's chat's");+ assert!(recipient_history["entries"].as_array().unwrap().iter().all(|e| e["kind"] != "user"));assert!(recipient_history["entries"].as_array().unwrap().iter()- .any(|e| { e["kind"] == "agent" && e["data"]["text"] == "reply: PERMISSION review the changes" }),+ .any(|e| e["kind"] == "agent" && e["data"]["text"] == "reply: PERMISSION review the changes"),"the reply remains available in the trace");- assert!(sync["bots"].as_array().unwrap().iter().all(|b| b["status"] == "idle"));-}--#[tokio::test]-async fn agent_messages_another_bot_then_finishes_before_recipient_approval() {- let host = Host::start().await;- let lead = host.bot("lead").await;- let reviewer = host.bot("reviewer").await;- host.call("send", json!({"botId": lead, "text": format!("MESSAGE {reviewer}")})).await;- let permission = host.wait_for(&reviewer, |e| e["kind"] == "permission" && e["data"]["status"] == "pending").await;- let final_reply = host.wait_for(&lead, |e| e["kind"] == "agent" && e["data"]["final"] == true).await;- assert_eq!(final_reply["data"]["text"], "Message queued");- let history = host.call("history", json!({"botId": reviewer})).await;- assert!(!history["entries"].as_array().unwrap().iter().any(|e| e["data"]["final"] == true));- assert!(history["entries"].as_array().unwrap().iter().all(|e| e["kind"] != "user"));- // The sender's turn and MCP subprocess have finished; Stop must still leave- // the recipient's approval and admitted message intact.- host.call("stop", json!({"botId": lead})).await;- host.call("respondPermission", json!({"entryId": permission["id"], "optionId": "allow"})).await;- let report = host.wait_for(&reviewer, |e| e["kind"] == "agent" && e["data"]["final"] == true).await;- assert_eq!(report["data"]["text"], "reply: PERMISSION review the changes");- host.wait_for(&reviewer, |e| e["kind"] == "notice" && e["data"]["status"] == "completed").await;- let sync = common::snapshot(&host.base, &host.token).await;- let notices: Vec<_> =- sync["entries"].as_array().unwrap().iter().filter(|e| e["data"]["delegationId"].is_string()).collect();- assert_eq!(notices.len(), 2);- for entry in ¬ices {- assert_eq!(entry["kind"], "notice");- assert_eq!(entry["data"]["sourceBotId"], lead);- assert_eq!(entry["data"]["targetBotId"], reviewer);- assert_eq!(entry["data"]["status"], "completed");- assert!(!entry["data"]["text"].as_str().unwrap().contains("reply: PERMISSION"));- }- assert_eq!(notices[0]["data"]["delegationId"], notices[1]["data"]["delegationId"]);- let history = host.call("history", json!({"botId": lead})).await;- assert_eq!(history["entries"].as_array().unwrap().iter().filter(|e| e["data"]["final"] == true).count(), 1);+ let lead_history = host.call("history", json!({"botId": lead})).await;+ assert_eq!(finals(&lead_history), ["Message queued", "Relayed: reply: PERMISSION review the changes"]);+ let prompts = host.fixture_log("lead", "prompts.jsonl");+ assert_eq!(prompts.len(), 2);+ assert!(prompts[1].as_str().unwrap().contains("[Codync: reviewer replied to your message_bot request"));}#[tokio::test]-async fn ask_returns_only_the_bot_answer_and_does_not_publish_a_user_report() {+async fn a_bot_request_answers_the_sender_and_never_the_user() {let host = Host::start().await;let lead = host.bot("lead").await;let reviewer = host.bot("reviewer").await;- host.call("send", json!({"botId": lead, "text": format!("ASK_REPORT {reviewer}")})).await;- let answer = host.wait_for(&lead, |e| e["kind"] == "agent" && e["data"]["final"] == true).await;- assert_eq!(answer["data"]["text"], "Team reply: Answer for the requesting bot");+ host.call("send", json!({"botId": lead, "text": format!("DELEGATE_REPORT {reviewer}")})).await;+ host.wait_for(&lead, |e| e["kind"] == "agent" && e["data"]["text"] == "Relayed: Answer for the requesting bot")+ .await;+ host.wait_finished().await;for bot in [&lead, &reviewer] {let history = host.call("history", json!({"botId": bot})).await;let notices: Vec<_> = history["entries"].as_array().unwrap().iter().filter(|e| e["kind"] == "notice").collect();@@ -192,66 +185,13 @@ async fn ask_returns_only_the_bot_answer_and_does_not_publish_a_user_report() {assert!(notices[0]["data"]["text"].as_str().unwrap().contains("Answer for the requesting bot"));assert!(!history["entries"].as_array().unwrap().iter().any(|e| e["data"]["text"] == "Report for the user"));if bot == &reviewer {- assert!(- history["entries"]- .as_array()- .unwrap()- .iter()- .filter(|e| e["kind"] == "agent")- .all(|e| e["data"]["final"] != true)- );+ assert!(finals(&history).is_empty());}}}#[tokio::test]-async fn independent_message_reports_to_the_user_without_a_bot_reply_or_duplicate_fallback() {- let host = Host::start().await;- let lead = host.bot("lead").await;- let reviewer = host.bot("reviewer").await;- host.call("send", json!({"botId": lead, "text": format!("MESSAGE_REPORT {reviewer}")})).await;- host.wait_for(&reviewer, |e| e["kind"] == "notice" && e["data"]["status"] == "completed").await;- let history = host.call("history", json!({"botId": reviewer})).await;- let reports: Vec<_> = history["entries"]- .as_array()- .unwrap()- .iter()- .filter(|e| e["kind"] == "agent" && e["data"]["final"] == true)- .map(|e| e["data"]["text"].as_str().unwrap())- .collect();- assert_eq!(reports, ["Report for the user", "Second report for the user"]);- assert!(history["entries"].as_array().unwrap().iter().any(|e| {- e["kind"] == "agent" && e["data"]["final"] != true && e["data"]["text"] == "Private completion trace"- }));- for bot in [&lead, &reviewer] {- let history = host.call("history", json!({"botId": bot})).await;- let notices: Vec<_> = history["entries"].as_array().unwrap().iter().filter(|e| e["kind"] == "notice").collect();- assert_eq!(notices.len(), 1);- assert_eq!(notices[0]["data"]["status"], "completed");- let text = notices[0]["data"]["text"].as_str().unwrap();- assert!(!text.contains("Report for the user"));- assert!(!text.contains("Private completion trace"));- }-}--fn assert_recipient_reports(sync: &Value, recipient: &str) {- let entries: Vec<_> = sync["entries"].as_array().unwrap().iter().filter(|e| e["botId"] == recipient).collect();- let reports: Vec<_> = entries- .iter()- .filter(|e| e["kind"] == "agent" && e["data"]["final"] == true)- .map(|e| e["data"]["text"].as_str().unwrap())- .collect();- assert_eq!(reports, ["Report for the user", "Second report for the user"]);- assert!(entries.iter().any(|e| e["kind"] == "agent"- && e["data"]["final"] != true- && e["data"]["text"] == "reply: PERMISSION review the changes"));- assert!(entries.iter().any(|e| {- e["kind"] == "agent" && e["data"]["final"] != true && e["data"]["text"] == "Private completion trace"- }));-}--#[tokio::test]-async fn user_report_queued_behind_an_ask_is_delivered_in_the_recipient_chat() {+async fn user_report_queued_behind_a_request_is_delivered_in_the_recipient_chat() {let host = Host::start().await;let lead = host.bot("lead").await;let reviewer = host.bot("reviewer").await;@@ -263,57 +203,37 @@ async fn user_report_queued_behind_an_ask_is_delivered_in_the_recipient_chat() {e["kind"] == "agent" && e["data"]["final"] == true && e["data"]["text"] == "Second report for the user"}).await;+ host.wait_for(&lead, |e| e["data"]["text"] == "Relayed: reply: PERMISSION review the changes").await;let sync = host.wait_finished().await;- assert_recipient_reports(&sync, &reviewer);- assert!(sync["entries"].as_array().unwrap().iter().any(|e| {- e["botId"] == lead- && e["data"]["final"] == true- && e["data"]["text"] == "Team reply: reply: PERMISSION review the changes"+ // The request's limits were its turn's: the user's own turn after it reports as usual.+ let entries: Vec<_> = sync["entries"].as_array().unwrap().iter().filter(|e| e["botId"] == reviewer).collect();+ let reports: Vec<_> = entries+ .iter()+ .filter(|e| e["kind"] == "agent" && e["data"]["final"] == true)+ .map(|e| e["data"]["text"].as_str().unwrap())+ .collect();+ assert_eq!(reports, ["Report for the user", "Second report for the user"]);+ assert!(entries.iter().any(|e| {+ e["kind"] == "agent" && e["data"]["final"] != true && e["data"]["text"] == "Private completion trace"}));let prompts = host.fixture_log("reviewer", "prompts.jsonl");assert_eq!(prompts.len(), 2);+ assert!(prompts[0].as_str().unwrap().contains("Your final reply goes back to lead"));assert_eq!(prompts[1], "REPORT");-}--#[tokio::test]-async fn independent_report_queued_behind_an_ask_gets_guidance_in_the_reused_session() {- let host = Host::start().await;- let lead = host.bot("lead").await;- let reviewer = host.bot("reviewer").await;- let messenger = host.bot("messenger").await;- host.call("send", json!({"botId": lead, "text": format!("DELEGATE {reviewer}")})).await;- let permission = host.wait_for(&reviewer, |e| e["kind"] == "permission" && e["data"]["status"] == "pending").await;- host.call("send", json!({"botId": messenger, "text": format!("MESSAGE_REPORT {reviewer}")})).await;- host.wait_for(&reviewer, |e| {- e["kind"] == "notice" && e["data"]["sourceBotId"] == messenger && e["data"]["status"] == "queued"- })- .await;- host.wait_for(&messenger, |e| e["kind"] == "agent" && e["data"]["final"] == true).await;- host.call("respondPermission", json!({"entryId": permission["id"], "optionId": "allow"})).await;- host.wait_for(&reviewer, |e| {- e["kind"] == "agent" && e["data"]["final"] == true && e["data"]["text"] == "Second report for the user"- })- .await;- let sync = host.wait_finished().await;- assert_recipient_reports(&sync, &reviewer);- let prompts = host.fixture_log("reviewer", "prompts.jsonl");- assert_eq!(prompts.len(), 2);- assert!(prompts[0].as_str().unwrap().contains("Do not use send_message or message_bot"));- assert!(prompts[1].as_str().unwrap().contains("send_message is available for this independent request"));- assert!(prompts[1].as_str().unwrap().contains("even if an earlier ask or older session instructions"));assert_eq!(host.fixture_log("reviewer", "sessions.jsonl").len(), 1, "the existing session must be reused");}-async fn exercise_bounded_chain(second_tool: &str) {+#[tokio::test]+async fn message_ping_pong_stops_at_the_hop_limit_and_a_new_user_turn_can_delegate() {let host = Host::start().await;let first = host.bot("first").await;let second = host.bot("second").await;- for (name, target, tool) in [("first", &second, "message_bot"), ("second", &first, second_tool)] {- std::fs::write(host.home.join(name).join("handoff.json"), json!({"target": target, "tool": tool}).to_string())- .unwrap();+ for (name, target) in [("first", &second), ("second", &first)] {+ std::fs::write(host.home.join(name).join("handoff.json"), json!({"target": target}).to_string()).unwrap();}let mut previous_rev = 0;- // The second user turn must start a fresh budget after the first chain ends.+ // `first` passes the chain on from each reply turn and `second` hands it back, so only the hops each reply+ // carries stop it. The second user turn must start a fresh budget after the first chain ends.for chain in 1..=2 {host.call("send", json!({"botId": first, "text": "CHAIN"})).await;let stopped = host@@ -329,19 +249,9 @@ async fn exercise_bounded_chain(second_tool: &str) {// after both bots and all request notices have completed.let entries = sync["entries"].as_array().unwrap();let completed = entries.iter().find(|e| e["id"] == stopped["id"]).expect("completed stop entry");- assert_eq!(completed["data"]["final"] == true, second_tool == "message_bot");+ assert_eq!(completed["data"]["final"], true, "a reply turn answers the user");let notices = entries.iter().filter(|e| e["data"]["delegationId"].is_string()).count();assert_eq!(notices, chain * 8 * 2, "the ninth handoff must never be queued");previous_rev = sync["rev"].as_i64().unwrap();}}--#[tokio::test]-async fn independent_message_ping_pong_stops_and_a_new_user_turn_can_delegate() {- exercise_bounded_chain("message_bot").await;-}--#[tokio::test]-async fn asking_between_independent_handoffs_cannot_reset_the_hop_limit() {- exercise_bounded_chain("ask_bot").await;-}