//! The `message` tool: the agent's only way into the room. use async_trait::async_trait; use rhema_core::request::ToolSpec; use rhema_core::tool::{ReplaySafety, ToolCall, ToolContext, ToolResolver, ToolResult}; use serde_json::json; use crate::error::AppResult; use crate::models::Message; use crate::state::Shared; use crate::util::{mentions_agent, now_ms, random_id}; /// Posts an agent message into the room log. pub fn post_agent_message(state: &Shared, room: &str, text: &str) -> AppResult { let text = text.trim(); let seq = state.hub.next_seq(&state.db, room); let message = Message { seq, id: random_id(16), author_id: None, author_name: "rhema".into(), author_kind: "agent".into(), text: text.to_owned(), mentions: mentions_agent(text), created_at: now_ms(), }; let data = serde_json::to_value(&message)?; state.hub.insert(&state.db, room, seq, "message", &data)?; state.hub.broadcast( room, crate::models::Envelope { seq, kind: "message".into(), data, }, ); Ok(message) } /// The resolver handed to the agent as an extra tool. pub struct MessageTool { state: Shared, room: String, } impl MessageTool { /// A tool posting into `room`. pub fn new(state: Shared, room: String) -> Self { Self { state, room } } } #[async_trait] impl ToolResolver for MessageTool { fn specs(&self) -> Vec { vec![ToolSpec::new( "message", "Send a message to the people in the room. This is the only way you \ speak: text outside this tool is not shown. One short message per \ update. Always send one before the turn ends.", json!({ "type": "object", "properties": { "text": { "type": "string", "description": "The message, in plain language. Address people by name." } }, "required": ["text"] }), )] } fn replay_safety(&self, _name: &str) -> ReplaySafety { // Posting twice would duplicate a line in the room. A resume // reports the call interrupted instead of re-running it. ReplaySafety::Unsafe } async fn resolve(&self, call: ToolCall, _ctx: &ToolContext) -> ToolResult { let Some(text) = call.args.get("text").and_then(|value| value.as_str()) else { return ToolResult::failure(call.id, "`text` must be a string"); }; if text.trim().is_empty() { return ToolResult::failure(call.id, "the message is empty"); } match post_agent_message(&self.state, &self.room, text) { Ok(_) => ToolResult::success(call.id, "sent"), Err(err) => ToolResult::failure(call.id, format!("could not post: {}", err.message)), } } }