Skip to content

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.

feat(host): cloud assistants reach the bots on the user's other computers

leepokai2946936c5a5a
diff --git a/cloud/src/routes/assistant.ts b/cloud/src/routes/assistant.ts
index afba1c5f..e1b78f57 100644
--- a/cloud/src/routes/assistant.ts
+++ b/cloud/src/routes/assistant.ts
@@ -42,8 +42,9 @@ const TOOLS = [
name: "list_bots",
title: "List bots",
description:
- "The user's Codync bots you can message, with their IDs, specialties and status. Narrow it with query; it " +
- "returns at most limit at a time, with next for the rest. Without computer, every online computer answers.",
+ "The user's Codync bots you can message, with their IDs, specialties and status, also those on the user's " +
+ "other computers in that computer's network (IDs like reviewer@laptop). Narrow it with query; it returns at " +
+ "most limit at a time, with next for the rest. Without computer, every online computer answers.",
inputSchema: {
type: "object",
properties: {
@@ -65,7 +66,10 @@ const TOOLS = [
inputSchema: {
type: "object",
properties: {
- botId: { type: "string", description: "The bot's id from list_bots." },
+ botId: {
+ type: "string",
+ description: "The bot's id from list_bots; with computer set to the computer that listed it when several are online.",
+ },
message: { type: "string", description: "The task, relevant context, file paths and the expected result." },
computer: COMPUTER,
},
@@ -278,7 +282,7 @@ async function ask(c: Ctx, computer: Computer, user: string, tool: string, args:
if (a.code === "offline") throw new ToolError(`${computer.name} is offline: Codync isn't running there, or it can't reach the internet.`);
if (a.code === "timeout") {
throw new ToolError(
- `${computer.name} didn't answer. Its Codync may be too old for cloud assistants: update it, then turn them on there (codync-host cloud --assistants on).`,
+ `${computer.name} didn't answer. Its Codync may be too old for cloud assistants: update it, then turn them on there (Cloud assistants in its Codync settings, or codync-host cloud --assistants on).`,
);
}
throw new ToolError(a.error ?? "Refused");
diff --git a/docs/design/codync-network.md b/docs/design/codync-network.md
index f68145f5..07d7fea4 100644
--- a/docs/design/codync-network.md
+++ b/docs/design/codync-network.md
@@ -150,8 +150,7 @@ terminal UI manage the network, phones show it, and a `network` event keeps them
1. Per-bot offering and inbound rules (needed before networks shared with other people).
2. Codync-run iroh relays as the default connector.
-3. The cloud assistant reaching bots on the connected computer's network.
-4. A local MCP server for agents that aren't Codync bots.
-5. Hellos that carry only what changed, lifting the roster's per-computer cap.
-6. Account networks; several networks per computer.
-7. A control channel for the standalone daemon on Windows (named pipe).
+3. A local MCP server for agents that aren't Codync bots.
+4. Hellos that carry only what changed, lifting the roster's per-computer cap.
+5. Account networks; several networks per computer.
+6. A control channel for the standalone daemon on Windows (named pipe).
diff --git a/docs/features/cloud-assistants.md b/docs/features/cloud-assistants.md
index fea3a8d3..72192500 100644
--- a/docs/features/cloud-assistants.md
+++ b/docs/features/cloud-assistants.md
@@ -30,8 +30,12 @@ ChatGPT / Claude ──MCP over HTTPS──▶ mcp.codync.dev (cloud Worker)
nothing can wake a hosted assistant.
- **Host** (`host/src/chat/team/assistant.rs`): the assistant messages bots like a bot does
(`Back::Assistant`): the bot's chat shows "Message from Cloud assistant" and the reply is kept in memory (the
- newest 50 requests, at most 16 running) until read. Only this computer's bots: bots on the user's other
- computers in its network aren't reachable through the connector yet.
+ newest 50 requests, at most 16 running) until read. `list_bots` also lists the bots the user's other
+ computers in this one's network offer (`reviewer@laptop`), and `message_bot` sends those a letter from
+ `cloud-assistant@<this computer>` (`Node::set_senders`: it may send but isn't offered, so nothing elsewhere can
+ ask it). That computer's own rules decide whether it takes it, like any sender's; the outcome comes back into the
+ same replies, and a refusal ends the request as failed with that computer's reason. The receiving bot's chat
+ shows "Message from Cloud assistant on desk".
## Who can get in
@@ -79,7 +83,6 @@ What lifts them, and in what order: [what's left](../plans/codync-network-next.m
|---|---|
| Hosts before 2.28.0 don't answer (`assistant.call` is ignored, the call times out after 10 s) | the host side ships in 2.28.0 |
| Only computers in the account that use the Codync relay; a private relay has no accounts | by design: the account is how the cloud knows whose computer it is |
-| Only the connected computer's bots, not bots elsewhere in its codync-network | the assistant isn't a network agent yet ([design](../design/codync-network.md#next-in-order)) |
| No hidden bots or groups | the same visibility rule as `list_bots` for bots |
| No callback when a reply is ready | MCP can't wake a hosted assistant; it calls `read_replies` |
| Replies in host memory: newest 50, at most 16 running, gone on restart | kept small and unencrypted data off disk; persist if users need it |
diff --git a/docs/features/codync-network.md b/docs/features/codync-network.md
index 3190a31f..257697f3 100644
--- a/docs/features/codync-network.md
+++ b/docs/features/codync-network.md
@@ -110,8 +110,6 @@ Planned in order, with what each step touches: [what's left](../plans/codync-net
- One network per computer; the `.network` address suffix comes with several.
- Shared networks (other people's computers) need the per-network list of offered bots and inbound rules first.
- Bots can't reach Claude Code or Codex sessions on another computer through the host (the standalone daemon can).
-- The cloud assistant connector ([cloud assistants](cloud-assistants.md)) reaches only the bots of the computer it
- talks to, not that computer's network.
- Each computer's share of the roster is capped (256 entries) and keeps its oldest: an owner or admin that has
made 256 admissions, promotions and removals can't make more. Hellos sending changes since the last one, instead
of the whole roster, would lift the cap.
diff --git a/docs/plans/codync-network-next.md b/docs/plans/codync-network-next.md
index acbcc2a1..4d38b611 100644
--- a/docs/plans/codync-network-next.md
+++ b/docs/plans/codync-network-next.md
@@ -173,7 +173,13 @@ connector and no Tailscale, a laptop that changes networks can't be found until
endpoint's addresses (iroh exposes changes), re-sign `Locate` when they change, and hello everyone. The roster keeps
only each computer's newest location, so this doesn't grow the log. Test: change addresses in a two-node test.
-## 5. Cloud assistants beyond the connected computer
+## 5. Cloud assistants beyond the connected computer (built)
+
+Built with the second option: the host sends letters for the assistant as `cloud-assistant` (reserved: no bot gets
+that address name), which it may send as without offering it (`Node::set_senders`); answers come back into the
+assistant's replies (`remote::Asker::Assistant`). The Worker's tool descriptions mention `name@computer` ids.
+
+Before:
The connector reaches only the bots of the computer it talks to. To reach that computer's network: publish the
assistant as an agent of that computer (or let the host send letters for it under a reserved name), route
diff --git a/host/crates/network/src/node/mod.rs b/host/crates/network/src/node/mod.rs
index 5b09c409..99cc5df4 100644
--- a/host/crates/network/src/node/mod.rs
+++ b/host/crates/network/src/node/mod.rs
@@ -44,6 +44,8 @@ struct Inner {
dir: PathBuf,
roster: Mutex<Option<Roster>>,
agents: Mutex<Vec<(Agent, Reach)>>,
+ /// Names the app also sends as without offering them (`set_senders`).
+ senders: Mutex<Vec<String>>,
/// The app offered its agents since the node started: until then, letters wait at the sender.
ready: AtomicBool,
/// The handoff count of letters taken here, by id, so a reply carries the chain on.
@@ -85,6 +87,7 @@ impl Node {
dir: dir.to_path_buf(),
roster: Mutex::new(Roster::load(dir)?),
agents: Mutex::default(),
+ senders: Mutex::default(),
ready: AtomicBool::new(false),
heard: Mutex::default(),
seen: Mutex::default(),
@@ -226,6 +229,12 @@ impl Node {
}
}
+ /// Names the app sends letters as without offering them to the network: a hosted assistant that
+ /// asks agents elsewhere but can't be asked itself. Answers to its letters still come back.
+ pub fn set_senders(&self, senders: impl IntoIterator<Item = String>) {
+ *locked(&self.inner.senders) = senders.into_iter().collect();
+ }
+
/// Who on the other computers may write to this computer's agents, the first match deciding.
/// Answers to this computer's own letters always pass, so a rule added while a request runs
/// doesn't strand it.
@@ -277,7 +286,10 @@ impl Node {
/// Sends a letter from one of the agents this computer offers. An answer (`reply_to`) may also
/// come from one it no longer offers: renamed or gone while it worked, it still says how it ended.
pub async fn send(&self, letter: Letter) -> Result<Sent> {
- if letter.reply_to.is_none() && !self.inner.offered().iter().any(|a| a.id == letter.from) {
+ let sender = |from: &str| {
+ self.inner.offered().iter().any(|a| a.id == from) || locked(&self.inner.senders).iter().any(|s| s == from)
+ };
+ if letter.reply_to.is_none() && !sender(&letter.from) {
bail!("{} isn't one of this computer's agents", letter.from);
}
// A reply carries on the chain of the letter it answers (one more handoff).
diff --git a/host/crates/network/tests/two_computers.rs b/host/crates/network/tests/two_computers.rs
index a815b20c..478ff713 100644
--- a/host/crates/network/tests/two_computers.rs
+++ b/host/crates/network/tests/two_computers.rs
@@ -313,3 +313,29 @@ async fn the_receiving_computers_rules_decide_but_answers_always_pass() {
let _ = std::fs::remove_dir_all(dir);
}
}
+
+#[tokio::test]
+async fn an_unlisted_sender_asks_and_hears_back_but_isnt_offered() {
+ let (desk_dir, laptop_dir) = (temp_dir("desk8"), temp_dir("laptop8"));
+ let (desk, mut desk_inbox) = Node::start(&desk_dir, &Connector::Private).await.unwrap();
+ desk.create("desk").unwrap();
+ offer(&desk, "reviewer");
+ desk.set_senders(["assistant".to_owned()]);
+ let (laptop, mut laptop_inbox) = Node::start(&laptop_dir, &Connector::Private).await.unwrap();
+ offer(&laptop, "coder");
+ laptop.join(&desk.invite().unwrap(), "laptop").await.unwrap();
+
+ let ask = Letter::new("assistant", to("coder@laptop"), "status?");
+ let asked = ask.id.clone();
+ desk.send(ask).await.unwrap();
+ let got = next(&mut laptop_inbox).await;
+ assert_eq!(got.from, to("assistant@desk"));
+ laptop.send(Letter::new("coder", got.from, "all green").reply_to(asked)).await.unwrap();
+ assert_eq!(next(&mut desk_inbox).await.body, "all green");
+ let offered: Vec<String> = laptop.peers().await.unwrap()[1].agents.iter().map(|a| a.id.clone()).collect();
+ assert_eq!(offered, ["reviewer"], "the assistant isn't listed");
+ assert!(desk.send(Letter::new("nobody", to("coder@laptop"), "hi")).await.is_err());
+ for dir in [desk_dir, laptop_dir] {
+ let _ = std::fs::remove_dir_all(dir);
+ }
+}
diff --git a/host/src/chat/team/assistant.rs b/host/src/chat/team/assistant.rs
index 35e3e6ea..78e98983 100644
--- a/host/src/chat/team/assistant.rs
+++ b/host/src/chat/team/assistant.rs
@@ -6,11 +6,12 @@
//! until it reads them (in memory: a restart forgets them).
use super::{
- Back, Exchange, MessageLifetime, RequestStatus, STOPPED, check_message, directory, message_args, request_prompt,
- visible_bot,
+ Back, Exchange, MessageLifetime, RequestStatus, STOPPED, check_message, directory, message_args, remote,
+ request_prompt, visible_bot,
};
use crate::LockExt;
use crate::hub::Hub;
+use crate::network::Recipient;
use crate::remote::cloud::{self, CloudStatus};
use crate::store::{Store, now_ms};
use anyhow::{Result, bail};
@@ -18,8 +19,11 @@ use serde_json::{Value, json};
use std::sync::{Arc, Mutex};
/// How it shows in a bot's chat, and its id there (`sourceBotId`).
-const NAME: &str = "Cloud assistant";
+pub(super) const NAME: &str = "Cloud assistant";
const ID: &str = "assistant";
+/// What it signs letters to the user's other computers with (`cloud-assistant@desk` there). No
+/// bot ever gets this address name.
+pub(crate) const HANDLE: &str = "cloud-assistant";
/// kv: `on` lets the cloud assistant in.
const KV: &str = "cloud_assistants";
/// Requests still running at a time.
@@ -52,10 +56,10 @@ pub fn set_enabled(hub: &Hub, on: bool) -> Result<CloudStatus> {
}
/// Answers one `assistant.call` from the relay: `{"t":"assistant.result","id","ok","result"|"error"}`.
-pub fn answer(hub: &Arc<Hub>, call: &Value) -> Value {
+pub async fn answer(hub: &Arc<Hub>, call: &Value) -> Value {
let id = &call["id"];
let tool = call["tool"].as_str().unwrap_or_default();
- match run(hub, call["user"].as_str().unwrap_or_default(), tool, &call["args"]) {
+ match run(hub, call["user"].as_str().unwrap_or_default(), tool, &call["args"]).await {
Ok(result) => json!({"t": "assistant.result", "id": id, "ok": true, "result": result}),
Err(e) => {
tracing::info!(tool, error = format!("{e:#}"), "refused a cloud assistant call");
@@ -64,7 +68,7 @@ pub fn answer(hub: &Arc<Hub>, call: &Value) -> Value {
}
}
-fn run(hub: &Arc<Hub>, user: &str, tool: &str, args: &Value) -> Result<Value> {
+async fn run(hub: &Arc<Hub>, user: &str, tool: &str, args: &Value) -> Result<Value> {
if !enabled(&hub.store) {
bail!(OFF);
}
@@ -73,7 +77,10 @@ fn run(hub: &Arc<Hub>, user: &str, tool: &str, args: &Value) -> Result<Value> {
bail!("This computer isn't in your Codync account.");
}
match tool {
- "list_bots" => directory::list(hub, ID, args, &[], |bot| bot.reachable_by_assistants),
+ // Also the bots on the user's other computers in this one's network (what they offer).
+ "list_bots" => {
+ directory::list(hub, ID, args, &hub.network.directory().await, |bot| bot.reachable_by_assistants)
+ }
"message_bot" => message(hub, args),
"read_replies" => Ok(hub.assistant.read(args["requestId"].as_str())),
_ => bail!("unknown tool: {tool}"),
@@ -83,13 +90,17 @@ fn run(hub: &Arc<Hub>, user: &str, tool: &str, args: &Value) -> Result<Value> {
fn message(hub: &Arc<Hub>, args: &Value) -> Result<Value> {
let (to, message) = message_args(args)?;
check_message(message)?;
- let target = visible_bot(hub, to)?;
- if !target.reachable_by_assistants {
- bail!("{} isn't open to cloud assistants: Reachable by cloud assistants is off in its settings", target.name);
- }
if hub.assistant.running() >= MAX_RUNNING {
bail!("{MAX_RUNNING} requests are still running: read_replies first, then try again");
}
+ let to = match hub.network.recipient(to)? {
+ Recipient::Here(bot) => bot,
+ Recipient::There(address) => return message_elsewhere(hub, &address, message),
+ };
+ let target = visible_bot(hub, &to)?;
+ if !target.reachable_by_assistants {
+ bail!("{} isn't open to cloud assistants: Reachable by cloud assistants is off in its settings", target.name);
+ }
let request = uuid::Uuid::new_v4().to_string();
let back = Back::Assistant { request: request.clone() };
let mut lifetime = MessageLifetime::new(hub, &request, message, back, &target.name);
@@ -111,6 +122,24 @@ fn message(hub: &Arc<Hub>, args: &Value) -> Result<Value> {
}))
}
+/// A bot on another of the user's computers (`reviewer@laptop`): a letter from this computer,
+/// whose answer comes back here. That computer's own rules decide whether it takes it.
+fn message_elsewhere(hub: &Arc<Hub>, to: &codync_network::Address, message: &str) -> Result<Value> {
+ let (request, peer) = remote::ask_for_assistant(hub, to, message)?;
+ hub.assistant.add(Reply {
+ request: request.clone(),
+ bot: peer.clone(),
+ quote: crate::agent::acp::truncate(message, super::REQUEST_QUOTE_BYTES),
+ status: RequestStatus::Queued,
+ text: None,
+ at: now_ms(),
+ });
+ Ok(json!({
+ "requestId": request, "botId": to.to_string(), "name": peer, "status": RequestStatus::Queued,
+ "note": "Queued on that computer. Bots can take minutes: get the reply later with read_replies.",
+ }))
+}
+
/// The cloud assistant's requests and their replies, oldest first.
#[derive(Default)]
pub struct Replies(Mutex<Vec<Reply>>);
diff --git a/host/src/chat/team/assistant/tests.rs b/host/src/chat/team/assistant/tests.rs
index 7e60a850..8436ebcb 100644
--- a/host/src/chat/team/assistant/tests.rs
+++ b/host/src/chat/team/assistant/tests.rs
@@ -3,8 +3,8 @@ use super::*;
use crate::agent::bot::Cmd;
use crate::remote::cloud::Owner;
-fn call(hub: &Arc<Hub>, user: &str, tool: &str, args: &Value) -> Value {
- answer(hub, &json!({"t": "assistant.call", "id": "c1", "user": user, "tool": tool, "args": args}))
+async fn call(hub: &Arc<Hub>, user: &str, tool: &str, args: &Value) -> Value {
+ answer(hub, &json!({"t": "assistant.call", "id": "c1", "user": user, "tool": tool, "args": args})).await
}
fn refused(v: &Value, why: &str) {
@@ -15,16 +15,16 @@ fn refused(v: &Value, why: &str) {
async fn the_cloud_assistant_needs_the_switch_and_the_account_and_reads_replies_later() {
let f = Fixture::new();
let hub = &f.hub;
- refused(&call(hub, "user_1", "list_bots", &json!({})), "Cloud assistants are off");
+ refused(&call(hub, "user_1", "list_bots", &json!({})).await, "Cloud assistants are off");
set_enabled(hub, true).unwrap();
assert!(hub.cloud.status().assistants);
- refused(&call(hub, "user_1", "list_bots", &json!({})), "isn't in your Codync account");
+ refused(&call(hub, "user_1", "list_bots", &json!({})).await, "isn't in your Codync account");
cloud::update_status(hub, |s| s.owner = Some(Owner { user_id: "user_1".into(), email: None }));
- refused(&call(hub, "user_2", "list_bots", &json!({})), "isn't in your Codync account");
+ refused(&call(hub, "user_2", "list_bots", &json!({})).await, "isn't in your Codync account");
- let listed = call(hub, "user_1", "list_bots", &json!({"query": "b"}));
+ let listed = call(hub, "user_1", "list_bots", &json!({"query": "b"})).await;
assert_eq!((&listed["id"], &listed["result"]["bots"][0]["id"]), (&json!("c1"), &json!("b")));
- let sent = call(hub, "user_1", "message_bot", &json!({"botId": "b", "message": "review this"}));
+ let sent = call(hub, "user_1", "message_bot", &json!({"botId": "b", "message": "review this"})).await;
let request = sent["result"]["requestId"].as_str().unwrap().to_owned();
let read = || hub.assistant.read(Some(&request))["replies"][0].clone();
f.until(|| read()["status"] == "completed").await;
@@ -33,7 +33,10 @@ async fn the_cloud_assistant_needs_the_switch_and_the_account_and_reads_replies_
let history = hub.store.history("b", i64::MAX, 50).unwrap();
let notice = history.into_iter().find(|e| e.data["delegationId"] == *request).unwrap();
assert_eq!(notice.data["botMessage"]["peerName"], NAME);
- refused(&call(hub, "user_1", "message_bot", &json!({"botId": "nobody", "message": "hi"})), "unknown or hidden bot");
+ refused(
+ &call(hub, "user_1", "message_bot", &json!({"botId": "nobody", "message": "hi"})).await,
+ "unknown or hidden bot",
+ );
f.shutdown().await;
}
@@ -43,16 +46,16 @@ async fn read_replies_tells_a_failed_request_from_a_stopped_one() {
let hub = &f.hub;
set_enabled(hub, true).unwrap();
cloud::update_status(hub, |s| s.owner = Some(Owner { user_id: "user_1".into(), email: None }));
- let ask = |message: &str| {
- let sent = call(hub, "user_1", "message_bot", &json!({"botId": "b", "message": message}));
+ let ask = async |message: &str| {
+ let sent = call(hub, "user_1", "message_bot", &json!({"botId": "b", "message": message})).await;
sent["result"]["requestId"].as_str().unwrap().to_owned()
};
let read = |request: &str| hub.assistant.read(Some(request))["replies"][0].clone();
- let failed = ask("FAIL agent error");
+ let failed = ask("FAIL agent error").await;
f.until(|| read(&failed)["status"] == "failed").await;
assert!(read(&failed)["detail"].as_str().is_some_and(|d| !d.is_empty()), "{}", read(&failed));
- let stopped = ask("BLOCK long work");
+ let stopped = ask("BLOCK long work").await;
f.until(|| read(&stopped)["status"] == "sent").await;
hub.send_cmd("b", Cmd::Stop).unwrap();
f.until(|| read(&stopped)["status"] == "cancelled").await;
@@ -89,12 +92,49 @@ async fn a_bot_closed_to_cloud_assistants_is_neither_listed_nor_reached() {
set_enabled(hub, true).unwrap();
cloud::update_status(hub, |s| s.owner = Some(Owner { user_id: "user_1".into(), email: None }));
hub.update_bot(&json!({"id": "b", "reachableByAssistants": false})).unwrap();
- let listed = call(hub, "user_1", "list_bots", &json!({}));
+ let listed = call(hub, "user_1", "list_bots", &json!({})).await;
let ids: Vec<&Value> = listed["result"]["bots"].as_array().unwrap().iter().map(|b| &b["id"]).collect();
assert!(!ids.contains(&&json!("b")), "{listed}");
refused(
- &call(hub, "user_1", "message_bot", &json!({"botId": "b", "message": "hi"})),
+ &call(hub, "user_1", "message_bot", &json!({"botId": "b", "message": "hi"})).await,
"isn't open to cloud assistants",
);
f.shutdown().await;
}
+
+#[tokio::test]
+async fn an_answer_from_another_computer_waits_in_the_replies() {
+ let f = Fixture::new();
+ let hub = &f.hub;
+ let added = |request: &str| Reply {
+ request: request.into(),
+ bot: "Coder on laptop".into(),
+ quote: "status?".into(),
+ status: RequestStatus::Sent,
+ text: None,
+ at: now_ms(),
+ };
+ for request in ["l1", "l2"] {
+ hub.assistant.add(added(request));
+ remote::awaits_for_assistant(hub, request, "Coder on laptop", "status?");
+ }
+ let (tx, rx) = tokio::sync::mpsc::channel(4);
+ tokio::spawn(remote::listen(hub.clone(), rx));
+ let answer = |request: &str, body: &str, status: &str| codync_network::Message {
+ id: format!("re-{request}"),
+ from: "coder@laptop".parse().unwrap(),
+ to: HANDLE.into(),
+ body: body.into(),
+ wake: true,
+ reply_to: Some(request.into()),
+ hops: 1,
+ meta: Some(json!({"codync": status})),
+ };
+ tx.send(answer("l1", "all green", "completed")).await.unwrap();
+ tx.send(answer("l2", "Couldn't finish: tests fail", "failed")).await.unwrap();
+ let read = |request: &str| hub.assistant.read(Some(request))["replies"][0].clone();
+ f.until(|| read("l2")["status"] == "failed").await;
+ assert_eq!((&read("l1")["status"], &read("l1")["reply"]), (&json!("completed"), &json!("all green")));
+ assert_eq!(read("l2")["detail"], "Couldn't finish: tests fail");
+ f.shutdown().await;
+}
diff --git a/host/src/chat/team/remote.rs b/host/src/chat/team/remote.rs
index f249d36f..fb168307 100644
--- a/host/src/chat/team/remote.rs
+++ b/host/src/chat/team/remote.rs
@@ -25,14 +25,20 @@ use tokio::sync::mpsc;
pub struct Waiting(Mutex<HashMap<String, Waiter>>);
struct Waiter {
- sender: String,
- /// The sender's exchange notice.
- entry: String,
+ asker: Asker,
quote: String,
/// How the recipient is shown ("Reviewer on desk").
peer: String,
}
+/// Who waits for an answer from another computer.
+enum Asker {
+ /// One of this computer's bots, with its exchange notice.
+ Bot { id: String, entry: String },
+ /// The user's cloud assistant: the answer waits in its replies (by the letter's id).
+ Assistant,
+}
+
impl Waiting {
fn insert(&self, id: String, waiter: Waiter) {
self.0.locked().insert(id, waiter);
@@ -85,6 +91,9 @@ fn take(hub: &Arc<Hub>, m: &Message) -> Result<()> {
/// How a bot on another computer is shown: its name and computer, from the directory.
fn peer_name(hub: &Hub, address: &Address) -> String {
+ if address.agent == super::assistant::HANDLE {
+ return format!("{} on {}", super::assistant::NAME, address.computer);
+ }
let name = hub.network.node().and_then(|node| {
node.directory()
.into_iter()
@@ -115,7 +124,8 @@ async fn send(hub: &Arc<Hub>, node: &Node, source: &BotConfig, letter: Letter) -
Exchange { request: &id, source: &source.id, target: &address, text: &letter.body, peer_name: Some(&peer) };
let entry = exchange.notice(hub, &source.id, &heading, false)?;
let quote = truncate(&letter.body, REQUEST_QUOTE_BYTES);
- let waiter = Waiter { sender: source.id.clone(), entry: entry.clone(), quote, peer: peer.clone() };
+ let asker = Asker::Bot { id: source.id.clone(), entry: entry.clone() };
+ let waiter = Waiter { asker, quote, peer: peer.clone() };
hub.waiting.insert(id.clone(), waiter);
let said = match node.send(letter).await {
Ok(Sent::Delivered) => {
@@ -139,6 +149,34 @@ async fn send(hub: &Arc<Hub>, node: &Node, source: &BotConfig, letter: Letter) -
}))
}
+/// The user's cloud assistant asks a bot on another computer. Returns the request's id (the
+/// letter's) at once: the letter goes in the background, and its outcome waits in the
+/// assistant's replies.
+pub(super) fn ask_for_assistant(hub: &Arc<Hub>, to: &Address, message: &str) -> Result<(String, String)> {
+ let node = hub.network.node().ok_or_else(|| anyhow!("this computer isn't in a network"))?;
+ let letter = Letter::new(super::assistant::HANDLE, to.clone(), message);
+ let (id, peer) = (letter.id.clone(), peer_name(hub, to));
+ awaits_for_assistant(hub, &id, &peer, message);
+ let (hub, request) = (hub.clone(), id.clone());
+ tokio::spawn(async move {
+ match node.send(letter).await {
+ Ok(Sent::Delivered) => hub.assistant.started(&request),
+ Ok(Sent::Queued) => {}
+ Err(error) => {
+ hub.waiting.take(&request);
+ hub.assistant.answered(&request, Err(format!("{error:#}")));
+ }
+ }
+ });
+ Ok((id, peer))
+}
+
+/// The answer to letter `id` goes to the cloud assistant's replies.
+pub(super) fn awaits_for_assistant(hub: &Hub, id: &str, peer: &str, message: &str) {
+ let quote = truncate(message, REQUEST_QUOTE_BYTES);
+ hub.waiting.insert(id.to_owned(), Waiter { asker: Asker::Assistant, quote, peer: peer.to_owned() });
+}
+
/// Says where a request waits, unless its reply already came (a quick one can beat this).
fn waiting(hub: &Hub, id: &str, text: &str, status: RequestStatus) {
if let Some(mut e) = hub.store.entry(id)
@@ -207,25 +245,33 @@ fn send_back(hub: &Hub, to: &Return, mut body: String, status: RequestStatus, ho
fn replied(hub: &Hub, id: &str, waiter: Waiter, m: &Message) {
let peer = &waiter.peer;
let status = m.meta.as_ref().and_then(|meta| serde_json::from_value(meta["codync"].clone()).ok());
+ let Asker::Bot { id: sender, entry } = waiter.asker else {
+ match status {
+ Some(RequestStatus::Cancelled) => hub.assistant.cancelled(id),
+ Some(RequestStatus::Failed) => hub.assistant.answered(id, Err(m.body.clone())),
+ _ => hub.assistant.answered(id, Ok(truncate(&m.body, MAX_MESSAGE_BYTES))),
+ }
+ return;
+ };
let outcome = match status {
Some(RequestStatus::Cancelled) => {
let detail = format!("{peer} was stopped before finishing. Partial work may have happened.");
- finish_entry(hub, &waiter.entry, RequestStatus::Cancelled, &detail, None);
+ finish_entry(hub, &entry, RequestStatus::Cancelled, &detail, None);
return;
}
Some(RequestStatus::Failed) => {
- finish_entry(hub, &waiter.entry, RequestStatus::Failed, &m.body, None);
+ finish_entry(hub, &entry, RequestStatus::Failed, &m.body, None);
Err(m.body.clone())
}
// A reply, also from an agent that isn't a Codync bot (it sends no `meta`).
_ => {
let reply = truncate(&m.body, NOTICE_REPLY_BYTES);
let detail = format!("Reply from {peer}:\n{reply}");
- finish_entry(hub, &waiter.entry, RequestStatus::Completed, &detail, Some(&reply));
+ finish_entry(hub, &entry, RequestStatus::Completed, &detail, Some(&reply));
Ok(truncate(&m.body, MAX_MESSAGE_BYTES))
}
};
let reply =
BotReply { request_id: id.to_owned(), quote: waiter.quote, from_name: peer.clone(), outcome, hops: m.hops };
- let _ = hub.send_cmd(&waiter.sender, Cmd::BotReply(reply));
+ let _ = hub.send_cmd(&sender, Cmd::BotReply(reply));
}
diff --git a/host/src/network/mod.rs b/host/src/network/mod.rs
index 157605ca..bb931054 100644
--- a/host/src/network/mod.rs
+++ b/host/src/network/mod.rs
@@ -138,6 +138,7 @@ async fn boot(hub: &Arc<Hub>) -> Result<Arc<Node>> {
if let Err(error) = node.set_rules(rules) {
tracing::warn!(error = format!("{error:#}"), "couldn't apply the network's rules; none apply");
}
+ node.set_senders([crate::chat::team::assistant::HANDLE.to_owned()]);
let node = Arc::new(node);
hub.network.node.set(node.clone()).map_err(|_| anyhow!("the network is already starting; try again"))?;
tokio::spawn(watch(hub.clone(), node.changes()));
@@ -174,6 +175,8 @@ pub fn publish(hub: &Hub) {
let mut handles = hub.network.handles.locked();
let mut given: HashMap<String, String> =
hub.store.kv_get(KV_HANDLES).and_then(|v| serde_json::from_str(&v).ok()).unwrap_or_default();
+ // The cloud assistant's address name never goes to a bot (`chat::team::assistant::HANDLE`).
+ given.entry(crate::chat::team::assistant::HANDLE.into()).or_insert_with(|| "assistant".into());
let before = given.len();
*handles = handles::Handles::of(bots.iter().map(|b| (b.id.clone(), b.name.clone())), &mut given);
if given.len() != before
diff --git a/host/src/remote/relay.rs b/host/src/remote/relay.rs
index 1dd32316..c51a988b 100644
--- a/host/src/remote/relay.rs
+++ b/host/src/remote/relay.rs
@@ -410,7 +410,7 @@ impl Session {
}
// A private relay has no accounts, so no cloud assistant (§7.9).
"assistant.call" if self.address.kind == cloud::RelayKind::Codync => {
- let result = crate::chat::team::assistant::answer(&self.hub, &v);
+ let result = crate::chat::team::assistant::answer(&self.hub, &v).await;
self.send(&result).await?;
}
"cloud.changed" => self.pull(),
diff --git a/web/content/docs/cloud-assistants.mdx b/web/content/docs/cloud-assistants.mdx
index 912be8b5..a7dc8533 100644
--- a/web/content/docs/cloud-assistants.mdx
+++ b/web/content/docs/cloud-assistants.mdx
@@ -35,7 +35,7 @@ In the bot's chat, the request shows as a row saying **Message from Cloud assist
- **The computer needs Codync 2.28.0 or later.** An older one doesn't answer the assistant.
- **Turned on at the computer.** The desktop app, the terminal UI or `codync-host` changes it; phones only show it.
-- **Only computers in your Codync account that use the Codync relay.** A computer that uses your own relay can't be reached, and neither can a computer that is only in your [network of computers](/docs/teamwork#bots-on-your-other-computers) and not in your account: the assistant reaches the bots of the computer it talks to, not that computer's network.
+- **Only through computers in your Codync account that use the Codync relay.** A computer that uses your own relay can't be reached directly. Through one that can, the assistant also reaches the bots your other computers offer in your [network of computers](/docs/teamwork#bots-on-your-other-computers), as `name@computer`; each of those computers decides with its own rules whether it takes the message.
- **No hidden bots or group chats.** The assistant sees the same bots another bot can message.
- **It can't be told when a reply is ready.** A hosted assistant only acts when you write to it, so ask it to check on the task later.
- **Replies don't last.** The computer keeps the newest 50 requests, at most 16 of them running at once, and forgets them all when Codync restarts.