From 66528cca00db77aee4d11f1be749746950456155 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 23 Nov 2026 03:16:28 -0600 Subject: [PATCH] feat(id-caps): MCP bridge translator and end-to-end world session for #7914 BridgeSession now translates the seven v1 tool calls into F13.1 client frames, local answers rendered from the server frames observed so far, or a session close, and tracks the screen state (latest full view, pending semantic-diff changes, observed objects) that screen.read and object.inspect are answered from. presence.set is refused with a typed NoFrameMapping: the F13.1 contract carries presence only as the join itself, so there is no presence frame. pkgs/id/tests/mcp_bridge_e2e.rs proves criterion 1 of #7914 over iroh on loopback against a live world host: the agent joins, subscribes to chat_posted, reads the other participant's chat from the pushed semantic diff through screen.read (drained by the read), posts chat that lands durably in the host journal, and leaves. The facade gains an iroh-blobs dev-dependency for the test host's blob store. --- pkgs/id/Cargo.toml | 4 + pkgs/id/crates/id-caps/src/mcp_bridge.rs | 605 +++++++++++++++++- .../id-caps/tests/mcp_bridge_surface.rs | 49 +- pkgs/id/tests/mcp_bridge_e2e.rs | 273 ++++++++ 4 files changed, 925 insertions(+), 6 deletions(-) create mode 100644 pkgs/id/tests/mcp_bridge_e2e.rs diff --git a/pkgs/id/Cargo.toml b/pkgs/id/Cargo.toml index c4f241e539..cd85d5a79b 100644 --- a/pkgs/id/Cargo.toml +++ b/pkgs/id/Cargo.toml @@ -239,6 +239,10 @@ proptest = "1.12" dcbor = "=0.25.2" # Local relay server for the startup-wait tests (iroh's test-utils feature). Dev only. iroh = { version = "1", features = ["test-utils"] } +# In-memory blob store for the MCP bridge end-to-end test's world host +# (tests/mcp_bridge_e2e.rs, #7914). Dev only; already in the lock via the +# root package's own iroh-blobs dependency. +iroh-blobs = "0.103" # Parses the relay kit's configs in tests/relay_ops.rs. Dev only. toml = "1" # Local mainline DHT testnet for tests/dht_testnet.rs (P7.3). Dev only; already in the lock via the `dht` feature. diff --git a/pkgs/id/crates/id-caps/src/mcp_bridge.rs b/pkgs/id/crates/id-caps/src/mcp_bridge.rs index 889f796449..d727577f33 100644 --- a/pkgs/id/crates/id-caps/src/mcp_bridge.rs +++ b/pkgs/id/crates/id-caps/src/mcp_bridge.rs @@ -1,8 +1,16 @@ //! The authority-free MCP bridge surface for the agent-in-worlds spike. //! //! The bridge is a translator: the world host remains responsible for -//! credentials, authority, quota, and audit. This module only defines the -//! narrow v1 tool surface and the session-start definition pin. +//! credentials, authority, quota, and audit. This module defines the +//! narrow v1 tool surface, the session-start definition pin, and the +//! translation itself (design #6300 sections 3 and 4.4): a tool call +//! becomes an F13.1 client frame, a local answer rendered from the +//! server frames observed so far, or a session close. The bridge holds +//! no credentials of its own; the one secret-shaped value it ever +//! handles is the agent's own join capability, passed through into the +//! join frame exactly as any shell presents it. + +use std::collections::BTreeMap; use serde::{Deserialize, Serialize}; use sha2::{Digest as _, Sha256}; @@ -52,7 +60,8 @@ pub fn v1_tool_definitions() -> Vec { } /// Errors that terminate a bridge session before a changed tool definition -/// can be used as a poisoning or shadowing vector. +/// can be used as a poisoning or shadowing vector, and errors that refuse +/// a single tool call without ending the session. #[derive(Clone, Debug, Eq, PartialEq)] pub enum BridgeError { /// The definition set changed after the session was pinned. @@ -64,13 +73,67 @@ pub enum BridgeError { }, /// The definition set could not be serialized for hashing. InvalidDefinitions, + /// A definition mismatch already terminated this session; no tool + /// call may be translated afterwards. + Terminated, + /// The tool name is not on the pinned v1 surface. + UnknownTool { + /// The refused tool name. + name: String, + }, + /// The tool's arguments do not match its pinned shape. + InvalidArguments { + /// The tool whose arguments were refused. + tool: &'static str, + /// What was wrong with the arguments. + problem: &'static str, + }, + /// The tool is on the surface but has no F13.1 frame mapping in v1. + NoFrameMapping { + /// The tool without a mapping. + tool: &'static str, + }, + /// The tool needs a joined session and none is open. + NotJoined { + /// The tool that required a session. + tool: &'static str, + }, + /// `world.join` was called on an already joined session. + AlreadyJoined, } -/// A bridge session with its tool-definition hash pinned at start. -#[derive(Clone, Debug, Eq, PartialEq)] +/// What the bridge driver must do with one translated tool call. +/// +/// The `Eq` derive is out of reach — frames are `serde_json::Value`, +/// which is not `Eq` — so the nursery suggestion to add it is refused. +#[allow(clippy::derive_partial_eq_without_eq)] +#[derive(Clone, Debug, PartialEq)] +pub enum ToolAction { + /// Send this F13.1 client frame (JSON) to the world host. + SendFrame(serde_json::Value), + /// Answer the call locally, from the server frames observed so far; + /// the string is the tool result text. + Local(String), + /// End the session. `world.leave` maps here: presence in the F13.1 + /// contract is connection-scoped, so leaving is closing the + /// connection — there is no leave frame. + Close, +} + +/// A bridge session: the pinned definition hash plus the screen state +/// the local tools are answered from. (Not `Eq`: the observed frames +/// are `serde_json::Value`.) +#[allow(clippy::derive_partial_eq_without_eq)] +#[derive(Clone, Debug, PartialEq)] pub struct BridgeSession { pinned_definition_hash: [u8; 32], terminated: bool, + joined: bool, + subscribed: bool, + screen_text: Option, + view_revision: u64, + pending_changes: Vec, + objects: BTreeMap, } impl BridgeSession { @@ -79,6 +142,12 @@ impl BridgeSession { Ok(Self { pinned_definition_hash: definition_hash(definitions)?, terminated: false, + joined: false, + subscribed: false, + screen_text: None, + view_revision: 0, + pending_changes: Vec::new(), + objects: BTreeMap::new(), }) } @@ -118,9 +187,535 @@ impl BridgeSession { pub const fn pinned_definition_hash(&self) -> [u8; 32] { self.pinned_definition_hash } + + /// Whether `world.join` has opened the world session. + #[must_use] + pub const fn is_joined(&self) -> bool { + self.joined + } + + /// Whether the host has acknowledged a `screen.subscribe`. + #[must_use] + pub const fn is_subscribed(&self) -> bool { + self.subscribed + } + + /// The latest full screen text observed, if any view has arrived. + #[must_use] + pub fn screen_text(&self) -> Option<&str> { + self.screen_text.as_deref() + } + + /// The newest screen revision observed on any frame that carries one. + #[must_use] + pub const fn view_revision(&self) -> u64 { + self.view_revision + } + + /// The semantic-diff changes observed since the last `screen.read`. + #[must_use] + pub fn pending_changes(&self) -> &[serde_json::Value] { + &self.pending_changes + } + + /// Translate one MCP tool call into the bridge driver's next step. + /// + /// Frame-backed tools produce [`ToolAction::SendFrame`] with the + /// exact F13.1 client frame; `screen.read` and `object.inspect` are + /// answered from the frames observed so far; `world.leave` produces + /// [`ToolAction::Close`]. `presence.set` is refused with + /// [`BridgeError::NoFrameMapping`]: presence in the F13.1 contract + /// is the join itself, so there is no presence frame to send. + pub fn tool_action( + &mut self, + name: &str, + arguments: &serde_json::Value, + ) -> Result { + if self.terminated { + return Err(BridgeError::Terminated); + } + match name { + "world.join" => self.join_action(arguments), + "world.leave" => { + self.require_joined("world.leave")?; + self.joined = false; + self.subscribed = false; + Ok(ToolAction::Close) + } + "screen.subscribe" => { + self.require_joined("screen.subscribe")?; + Ok(ToolAction::SendFrame(subscribe_frame(arguments)?)) + } + "screen.read" => { + self.require_joined("screen.read")?; + Ok(ToolAction::Local(self.screen_read())) + } + "chat.post" => { + self.require_joined("chat.post")?; + Ok(ToolAction::SendFrame(chat_frame(arguments)?)) + } + "object.inspect" => { + self.require_joined("object.inspect")?; + Ok(ToolAction::Local(self.object_inspect(arguments)?)) + } + "presence.set" => Err(BridgeError::NoFrameMapping { + tool: "presence.set", + }), + _ => Err(BridgeError::UnknownTool { + name: name.to_owned(), + }), + } + } + + /// Observe one server frame, updating the screen state the local + /// tools are answered from. Frames the bridge does not render — + /// snapshots, events, errors — are ignored by design: the agent + /// profile reads screens through views and semantic diffs. + pub fn observe_frame(&mut self, frame: &serde_json::Value) { + match frame.get("type").and_then(serde_json::Value::as_str) { + Some("view") => { + self.observe_revision(frame); + // A patch view carries an empty `data` and a `patch` + // instead; only a full view replaces the screen text. + if frame.get("patch").is_none() + && let Some(data) = frame.get("data").and_then(serde_json::Value::as_str) + { + self.screen_text = Some(data.to_owned()); + } + } + Some("semantic_diff") => { + self.observe_revision(frame); + if let Some(changes) = frame.get("changes").and_then(serde_json::Value::as_array) { + for change in changes { + if change.get("kind").and_then(serde_json::Value::as_str) + == Some("object_changed") + && let Some(entity_ref) = change.get("entity_ref") + { + self.objects.insert(entity_ref.to_string(), change.clone()); + } + self.pending_changes.push(change.clone()); + } + } + } + Some("screen_subscription") => { + self.subscribed = true; + self.observe_revision(frame); + } + _ => {} + } + } + + /// Render the current screen for `screen.read`: the latest full + /// view's text, then every semantic-diff change observed since the + /// previous read. Reading drains the pending changes. + pub fn screen_read(&mut self) -> String { + let mut out = self + .screen_text + .clone() + .unwrap_or_else(|| "(no screen received yet)".to_owned()); + if !self.pending_changes.is_empty() { + out.push_str("\nchanges since last read:"); + for change in self.pending_changes.drain(..) { + out.push('\n'); + if change.get("kind").and_then(serde_json::Value::as_str) == Some("chat_posted") { + out.push_str("chat_posted: "); + out.push_str( + change + .get("text") + .and_then(serde_json::Value::as_str) + .unwrap_or(""), + ); + } else { + out.push_str(&change.to_string()); + } + } + } + out + } + + fn join_action(&mut self, arguments: &serde_json::Value) -> Result { + if self.joined { + return Err(BridgeError::AlreadyJoined); + } + let capability = arguments + .get("capability") + .and_then(serde_json::Value::as_str) + .ok_or(BridgeError::InvalidArguments { + tool: "world.join", + problem: "capability must be a string", + })?; + let after = arguments.get("after").and_then(serde_json::Value::as_u64); + self.joined = true; + Ok(ToolAction::SendFrame(serde_json::json!({ + "type": "join", + "capability": capability, + "after": after, + "agent_profile": true, + }))) + } + + fn object_inspect(&self, arguments: &serde_json::Value) -> Result { + let entity_ref = arguments + .get("entity_ref") + .ok_or(BridgeError::InvalidArguments { + tool: "object.inspect", + problem: "entity_ref is required", + })?; + Ok(match self.objects.get(&entity_ref.to_string()) { + Some(change) => change.to_string(), + None => "object not in the observed screen state".to_owned(), + }) + } + + const fn require_joined(&self, tool: &'static str) -> Result<(), BridgeError> { + if self.joined { + Ok(()) + } else { + Err(BridgeError::NotJoined { tool }) + } + } + + fn observe_revision(&mut self, frame: &serde_json::Value) { + if let Some(revision) = frame + .get("view_revision") + .and_then(serde_json::Value::as_u64) + { + self.view_revision = revision; + } + } +} + +/// Build the `screen_subscribe` frame for `screen.subscribe`: a region +/// and/or event classes, at least one of the two (the contract requires +/// a subscription to name something). +fn subscribe_frame(arguments: &serde_json::Value) -> Result { + let mut frame = serde_json::json!({ "type": "screen_subscribe" }); + if let Some(region) = arguments.get("region") { + for key in ["x", "y", "width", "height"] { + if region + .get(key) + .and_then(serde_json::Value::as_u64) + .is_none() + { + return Err(BridgeError::InvalidArguments { + tool: "screen.subscribe", + problem: "region needs numeric x, y, width, height", + }); + } + } + frame["region"] = region.clone(); + } + if let Some(classes) = arguments.get("event_classes") { + let valid = classes + .as_array() + .is_some_and(|classes| classes.iter().all(|class| class.as_str().is_some())); + if !valid { + return Err(BridgeError::InvalidArguments { + tool: "screen.subscribe", + problem: "event_classes must be an array of strings", + }); + } + frame["event_classes"] = classes.clone(); + } + if frame.get("region").is_none() && frame.get("event_classes").is_none() { + return Err(BridgeError::InvalidArguments { + tool: "screen.subscribe", + problem: "a region and/or event_classes is required", + }); + } + Ok(frame) +} + +/// Build the `chat` frame for `chat.post`, carrying the caller's +/// stale-decision token when one is supplied (design section 4.3). +fn chat_frame(arguments: &serde_json::Value) -> Result { + let text = arguments + .get("text") + .and_then(serde_json::Value::as_str) + .ok_or(BridgeError::InvalidArguments { + tool: "chat.post", + problem: "text must be a string", + })?; + let mut frame = serde_json::json!({ "type": "chat", "text": text }); + if let Some(revision) = arguments + .get("screen_revision") + .and_then(serde_json::Value::as_u64) + { + frame["screen_revision"] = serde_json::json!(revision); + } + Ok(frame) } fn definition_hash(definitions: &[ToolDefinition]) -> Result<[u8; 32], BridgeError> { let bytes = serde_json::to_vec(definitions).map_err(|_| BridgeError::InvalidDefinitions)?; Ok(Sha256::digest(bytes).into()) } + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used)] +mod tests { + use super::*; + use serde_json::json; + + fn started() -> BridgeSession { + BridgeSession::start(&v1_tool_definitions()).unwrap() + } + + fn joined() -> BridgeSession { + let mut session = started(); + let action = session + .tool_action("world.join", &json!({ "capability": "cap-1" })) + .unwrap(); + assert_eq!( + action, + ToolAction::SendFrame(json!({ + "type": "join", + "capability": "cap-1", + "after": null, + "agent_profile": true, + })) + ); + session + } + + #[test] + fn join_rejects_a_second_join_and_a_missing_capability() { + let mut session = joined(); + assert_eq!( + session.tool_action("world.join", &json!({ "capability": "cap-2" })), + Err(BridgeError::AlreadyJoined) + ); + let mut fresh = started(); + assert!(matches!( + fresh.tool_action("world.join", &json!({})), + Err(BridgeError::InvalidArguments { + tool: "world.join", + .. + }) + )); + assert!(!fresh.is_joined()); + } + + #[test] + fn session_tools_require_a_join() { + let mut session = started(); + for (name, args) in [ + ("world.leave", json!({})), + ( + "screen.subscribe", + json!({ "event_classes": ["chat_posted"] }), + ), + ("screen.read", json!({})), + ("chat.post", json!({ "text": "hi" })), + ("object.inspect", json!({ "entity_ref": 1 })), + ] { + assert!( + matches!( + session.tool_action(name, &args), + Err(BridgeError::NotJoined { .. }) + ), + "{name} must require a join" + ); + } + } + + #[test] + fn subscribe_frame_names_region_or_classes() { + let mut session = joined(); + assert_eq!( + session + .tool_action( + "screen.subscribe", + &json!({ "event_classes": ["chat_posted"] }) + ) + .unwrap(), + ToolAction::SendFrame(json!({ + "type": "screen_subscribe", + "event_classes": ["chat_posted"], + })) + ); + assert_eq!( + session + .tool_action( + "screen.subscribe", + &json!({ "region": { "x": 0, "y": 1, "width": 5, "height": 2 } }) + ) + .unwrap(), + ToolAction::SendFrame(json!({ + "type": "screen_subscribe", + "region": { "x": 0, "y": 1, "width": 5, "height": 2 }, + })) + ); + assert!(matches!( + session.tool_action("screen.subscribe", &json!({})), + Err(BridgeError::InvalidArguments { + tool: "screen.subscribe", + .. + }) + )); + assert!(matches!( + session.tool_action( + "screen.subscribe", + &json!({ "region": { "x": 0, "y": 1, "width": 5 } }) + ), + Err(BridgeError::InvalidArguments { + tool: "screen.subscribe", + .. + }) + )); + } + + #[test] + fn chat_frame_carries_text_and_the_stale_decision_token() { + let mut session = joined(); + assert_eq!( + session + .tool_action("chat.post", &json!({ "text": "hello" })) + .unwrap(), + ToolAction::SendFrame(json!({ "type": "chat", "text": "hello" })) + ); + assert_eq!( + session + .tool_action( + "chat.post", + &json!({ "text": "hello", "screen_revision": 7 }) + ) + .unwrap(), + ToolAction::SendFrame(json!({ + "type": "chat", + "text": "hello", + "screen_revision": 7, + })) + ); + } + + #[test] + fn read_renders_the_view_then_drains_semantic_diffs() { + let mut session = joined(); + session.observe_frame(&json!({ + "type": "view", + "sequence": 1, + "data": "board", + "view_revision": 3, + })); + assert_eq!(session.screen_text(), Some("board")); + assert_eq!(session.view_revision(), 3); + session.observe_frame(&json!({ + "type": "semantic_diff", + "sequence": 2, + "view_revision": 3, + "changes": [ + { "kind": "chat_posted", "participant_id": 2, "text": "hello agent" }, + { "kind": "object_changed", "participant_id": 2, "entity_ref": "cell-4" }, + ], + })); + assert_eq!(session.pending_changes().len(), 2); + let read = session.screen_read(); + assert!( + read.starts_with("board\nchanges since last read:"), + "{read}" + ); + assert!(read.contains("chat_posted: hello agent"), "{read}"); + assert!(read.contains("object_changed"), "{read}"); + // The read drained the diffs; a second read is the bare screen. + assert_eq!(session.screen_read(), "board"); + } + + #[test] + fn patch_views_do_not_blank_the_screen() { + let mut session = joined(); + session.observe_frame(&json!({ + "type": "view", + "sequence": 1, + "data": "board", + "view_revision": 1, + })); + session.observe_frame(&json!({ + "type": "view", + "sequence": 2, + "data": "", + "view_revision": 2, + "base_view_revision": 1, + "patch": { "ops": [] }, + })); + assert_eq!(session.screen_text(), Some("board")); + assert_eq!(session.view_revision(), 2); + } + + #[test] + fn inspect_reads_the_observed_object_state() { + let mut session = joined(); + session.observe_frame(&json!({ + "type": "semantic_diff", + "sequence": 2, + "view_revision": 1, + "changes": [ + { "kind": "object_changed", "participant_id": 2, "entity_ref": "cell-4" }, + ], + })); + let found = session + .tool_action("object.inspect", &json!({ "entity_ref": "cell-4" })) + .unwrap(); + assert!( + matches!(&found, ToolAction::Local(text) if text.contains("object_changed")), + "{found:?}" + ); + assert_eq!( + session + .tool_action("object.inspect", &json!({ "entity_ref": "cell-9" })) + .unwrap(), + ToolAction::Local("object not in the observed screen state".to_owned()) + ); + } + + #[test] + fn leave_closes_and_presence_set_has_no_frame_mapping() { + let mut session = joined(); + assert_eq!( + session.tool_action("presence.set", &json!({ "state": "away" })), + Err(BridgeError::NoFrameMapping { + tool: "presence.set" + }) + ); + assert_eq!( + session.tool_action("world.leave", &json!({})).unwrap(), + ToolAction::Close + ); + assert!(!session.is_joined()); + assert!(matches!( + session.tool_action("chat.post", &json!({ "text": "hi" })), + Err(BridgeError::NotJoined { .. }) + )); + } + + #[test] + fn unknown_tools_and_terminated_sessions_are_refused() { + let mut session = joined(); + assert_eq!( + session.tool_action("host.exec", &json!({})), + Err(BridgeError::UnknownTool { + name: "host.exec".to_owned() + }) + ); + let mut tampered = v1_tool_definitions(); + tampered[0].ceiling = "credential.read".to_owned(); + assert!(session.verify_definitions(&tampered).is_err()); + assert_eq!( + session.tool_action("chat.post", &json!({ "text": "hi" })), + Err(BridgeError::Terminated) + ); + } + + #[test] + fn subscription_ack_marks_the_session_subscribed() { + let mut session = joined(); + assert!(!session.is_subscribed()); + session.observe_frame(&json!({ + "type": "screen_subscription", + "event_classes": ["chat_posted"], + "view_revision": 4, + })); + assert!(session.is_subscribed()); + assert_eq!(session.view_revision(), 4); + } +} diff --git a/pkgs/id/crates/id-caps/tests/mcp_bridge_surface.rs b/pkgs/id/crates/id-caps/tests/mcp_bridge_surface.rs index 30d9d982dd..59b013555d 100644 --- a/pkgs/id/crates/id-caps/tests/mcp_bridge_surface.rs +++ b/pkgs/id/crates/id-caps/tests/mcp_bridge_surface.rs @@ -1,7 +1,12 @@ //! Surface oracle for #7914: only the seven approved tools are exposed, and //! a mid-session definition change terminates the bridge. -use id_caps::mcp_bridge::{BridgeError, BridgeSession, FORBIDDEN_TOOL_NAMES, v1_tool_definitions}; +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use id_caps::mcp_bridge::{ + BridgeError, BridgeSession, FORBIDDEN_TOOL_NAMES, ToolAction, v1_tool_definitions, +}; +use serde_json::json; #[test] fn v1_surface_excludes_forbidden_non_tools() { @@ -38,3 +43,45 @@ fn tampered_definition_terminates_session() { assert!(session.is_terminated()); assert!(session.verify_definitions(&definitions).is_err()); } + +#[test] +fn every_surface_tool_translates_or_names_its_missing_mapping() { + // Minimal valid arguments per tool, in an order that keeps the + // session joined for the session-scoped tools. + let calls: [(&str, serde_json::Value); 7] = [ + ("world.join", json!({ "capability": "cap" })), + ( + "screen.subscribe", + json!({ "event_classes": ["chat_posted"] }), + ), + ("screen.read", json!({})), + ("chat.post", json!({ "text": "hi" })), + ("object.inspect", json!({ "entity_ref": "cell-0" })), + ("presence.set", json!({ "state": "away" })), + ("world.leave", json!({})), + ]; + let mut session = + BridgeSession::start(&v1_tool_definitions()).expect("the static surface serializes"); + for (name, arguments) in calls { + match session.tool_action(name, &arguments) { + Ok(ToolAction::SendFrame(_) | ToolAction::Local(_) | ToolAction::Close) => {} + Err(BridgeError::NoFrameMapping { tool }) => { + assert_eq!(tool, "presence.set", "only presence.set lacks a mapping"); + assert_eq!(name, "presence.set"); + } + other => panic!("{name} must translate, got {other:?}"), + } + } + // The forbidden non-tools never translate. + let mut session = + BridgeSession::start(&v1_tool_definitions()).expect("the static surface serializes"); + for forbidden in FORBIDDEN_TOOL_NAMES { + assert!( + matches!( + session.tool_action(forbidden, &json!({})), + Err(BridgeError::UnknownTool { .. }) + ), + "{forbidden} must stay off the bridge" + ); + } +} diff --git a/pkgs/id/tests/mcp_bridge_e2e.rs b/pkgs/id/tests/mcp_bridge_e2e.rs new file mode 100644 index 0000000000..8698503104 --- /dev/null +++ b/pkgs/id/tests/mcp_bridge_e2e.rs @@ -0,0 +1,273 @@ +//! End-to-end oracle for #7914 criterion 1: an agent joins a local +//! world over iroh, reads a screen via semantic diffs, posts chat, and +//! leaves — end to end. +//! +//! Every frame the agent sends is produced by the MCP bridge translator +//! ([`id_caps::mcp_bridge`]) from a tool call, and every frame it +//! receives is fed back into the bridge; the agent never touches a raw +//! frame. A second participant joins raw, exactly as a human shell +//! does, and posts the chat the agent then reads. Oracles: the bridge's +//! own `screen.read` rendering (the diff must surface, once) and the +//! host journal exported through the admin fixture recorder (both +//! chats durable, in order) — not either client's local view alone. + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::time::Duration; + +use id::world::{WorldCore, WorldHandle, WorldLimits, WorldScopes}; +use id::world_fixture::{FixtureEvent, record}; +use id::world_net::{WORLD_ALPN, WorldClient, WorldProtocol}; +use id::world_session::{WorldService, module_hash}; +use id_caps::mcp_bridge::{BridgeSession, ToolAction, v1_tool_definitions}; +use iroh::endpoint::{RelayMode, presets}; +use iroh::protocol::Router; +use iroh::{Endpoint, EndpointAddr, TransportAddr}; +use iroh_blobs::store::mem::MemStore; +use serde_json::{Value, json}; + +const TIC_TAC_TOE: &[u8] = include_bytes!("../apps/tic-tac-toe/program/tic-tac-toe.wasm"); +const TIMEOUT: Duration = Duration::from_secs(30); + +/// A loopback endpoint that uses no relay or discovery. +async fn endpoint() -> Endpoint { + Endpoint::builder(presets::Minimal) + .relay_mode(RelayMode::Disabled) + .bind() + .await + .unwrap() +} + +/// Serve `service` over iroh on loopback (mirrors the world_fixture +/// test harness). +async fn serve(service: WorldService) -> (Router, EndpointAddr) { + let ep = endpoint().await; + let router = Router::builder(ep.clone()) + .accept(WORLD_ALPN, WorldProtocol::new(service)) + .spawn(); + let addr = EndpointAddr::from_parts( + ep.id(), + ep.bound_sockets().iter().map(|socket| { + let ip = if socket.ip().is_unspecified() { + std::net::Ipv4Addr::LOCALHOST.into() + } else { + socket.ip() + }; + TransportAddr::Ip(std::net::SocketAddr::new(ip, socket.port())) + }), + ); + (router, addr) +} + +/// The agent side of the bridge: one world connection driven purely by +/// tool calls. `Local` results are returned to the caller; frames are +/// sent verbatim; `Close` drops the connection. +struct AgentDriver { + client: Option, + bridge: BridgeSession, +} + +impl AgentDriver { + async fn call(&mut self, name: &str, arguments: Value) -> Option { + match self.bridge.tool_action(name, &arguments).unwrap() { + ToolAction::SendFrame(frame) => { + self.client + .as_mut() + .unwrap() + .send_json(&frame) + .await + .unwrap(); + None + } + ToolAction::Local(text) => Some(text), + ToolAction::Close => { + if let Some(client) = self.client.take() { + client.close(); + } + None + } + } + } + + /// Read host frames into the bridge until `ready` holds. + async fn pump_until(&mut self, what: &str, ready: impl Fn(&BridgeSession) -> bool) { + tokio::time::timeout(TIMEOUT, async { + loop { + if ready(&self.bridge) { + return; + } + let frame = self + .client + .as_mut() + .unwrap() + .recv_json() + .await + .unwrap() + .expect("host closed the agent session"); + self.bridge.observe_frame(&frame); + } + }) + .await + .unwrap_or_else(|_| panic!("timed out waiting for {what}")); + } +} + +/// Wait until the raw client receives the durable `event` frame for +/// `sequence`, skipping snapshots, views, and earlier events. +async fn wait_for_event(client: &mut WorldClient, sequence: u64) { + tokio::time::timeout(TIMEOUT, async { + loop { + let frame = client + .recv_json() + .await + .unwrap() + .expect("host closed the raw session"); + if frame["type"] == "event" && frame["event"]["sequence"] == sequence { + return; + } + } + }) + .await + .unwrap_or_else(|_| panic!("timed out waiting for event at sequence {sequence}")); +} + +#[tokio::test] +async fn agent_joins_reads_via_semantic_diffs_posts_chat_and_leaves() { + // A live host with the tic-tac-toe program installed (sequence 1 + // is the install event, as in the world_fixture games). + let world = WorldHandle::spawn(WorldCore::new("lobby", WorldLimits::default()).unwrap()); + let service = WorldService::new(world.clone(), Some("admin".to_owned())) + .with_blob_store(MemStore::new().into()); + service + .install_wasm( + Some("admin"), + TIC_TAC_TOE.to_vec(), + 7, + &module_hash(TIC_TAC_TOE), + ) + .await + .unwrap(); + let (_, agent_cap) = world.issue("agent", WorldScopes::GUEST).await.unwrap(); + let (_, bo_cap) = world.issue("bo", WorldScopes::GUEST).await.unwrap(); + let (router, addr) = serve(service).await; + let client_ep = endpoint().await; + + let client = WorldClient::connect(&client_ep, addr.clone()) + .await + .unwrap(); + let mut agent = AgentDriver { + client: Some(client), + bridge: BridgeSession::start(&v1_tool_definitions()).unwrap(), + }; + + // world.join: the bridge emits the agent-profile join frame; the + // host answers with a snapshot and the first view, which the + // bridge renders for screen.read. + agent + .call("world.join", json!({ "capability": agent_cap.expose() })) + .await; + agent + .pump_until("the join view", |bridge| bridge.screen_text().is_some()) + .await; + let first_read = agent.call("screen.read", json!({})).await.unwrap(); + assert!( + !first_read.contains("changes since last read"), + "no diffs before any world change: {first_read}" + ); + + // screen.subscribe: the host acknowledges the chat_posted + // subscription. + agent + .call( + "screen.subscribe", + json!({ "event_classes": ["chat_posted"] }), + ) + .await; + agent + .pump_until("the subscription ack", |bridge| bridge.is_subscribed()) + .await; + + // A human participant joins raw, exactly as a terminal shell does, + // and posts chat (durable sequence 2). + let mut bo = WorldClient::connect(&client_ep, addr.clone()) + .await + .unwrap(); + bo.send_json(&json!({ "type": "join", "capability": bo_cap.expose(), "after": null })) + .await + .unwrap(); + let snapshot = bo.recv_json().await.unwrap().unwrap(); + assert_eq!(snapshot["type"], "snapshot"); + bo.send_json(&json!({ "type": "chat", "text": "hello agent" })) + .await + .unwrap(); + + // The agent reads the screen via the semantic diff the host pushes + // for its subscription: the change in world terms, not a repaint. + agent + .pump_until("the chat_posted diff", |bridge| { + bridge + .pending_changes() + .iter() + .any(|change| change["kind"] == "chat_posted" && change["text"] == "hello agent") + }) + .await; + let read = agent.call("screen.read", json!({})).await.unwrap(); + assert!( + read.contains("chat_posted: hello agent"), + "screen.read must surface the diff: {read}" + ); + let reread = agent.call("screen.read", json!({})).await.unwrap(); + assert!( + !reread.contains("hello agent"), + "a second read must not replay the drained diff: {reread}" + ); + + // chat.post: the bridge emits the chat frame; bo's raw client sees + // the durable event at sequence 3. + agent + .call("chat.post", json!({ "text": "hello human" })) + .await; + wait_for_event(&mut bo, 3).await; + + // world.leave: no frame exists to send — the bridge closes the + // session, and the translator refuses further session tools. + match agent.bridge.tool_action("world.leave", &json!({})).unwrap() { + ToolAction::Close => { + if let Some(client) = agent.client.take() { + client.close(); + } + } + other => panic!("world.leave must close the session, got {other:?}"), + } + assert!( + agent + .bridge + .tool_action("chat.post", &json!({ "text": "gone" })) + .is_err(), + "no tool may translate after leaving" + ); + bo.close(); + + // The durable oracle: the host journal holds both chats, in order. + let mut admin = WorldClient::connect(&client_ep, addr.clone()) + .await + .unwrap(); + let fixture = record(&mut admin, "admin").await.unwrap(); + admin.close(); + let chats: Vec<(u64, String)> = fixture + .events + .iter() + .filter_map(|event| match event { + FixtureEvent::Chat { sequence, text, .. } => Some((*sequence, text.clone())), + _ => None, + }) + .collect(); + assert_eq!( + chats, + vec![(2, "hello agent".to_owned()), (3, "hello human".to_owned())] + ); + assert_eq!(fixture.header.current_sequence, 3); + + client_ep.close().await; + router.shutdown().await.unwrap(); +}