Skip to main content

rpi_cli/
message_agent.rs

1//! Built-in `message_agent` tool — agent-to-agent messaging for host-integrated
2//! bot sessions.
3//!
4//! ## Why this lives in the engine
5//!
6//! The tool has to be visible to the model in the session's tool list and it
7//! must run in the same turn loop as every other tool. Delivery itself is
8//! host-owned (a desktop app knows its roster and its bot sessions; a bare CLI
9//! does not), so the engine exposes a process-global [`MessageAgentHandler`]
10//! that an embedding host installs once. When no handler is installed the tool
11//! is not registered at all — a CLI session never advertises a tool it cannot
12//! service.
13//!
14//! ## Semantics (mirrors hermes `tools/bot_mode_dm.py`)
15//!
16//! FIRE-AND-FORGET: a successful send returns a dispatch ack
17//! (`{status:"queued", delivery_id}`). The reply arrives later through the
18//! host's own delivery path; the tool never blocks waiting for it.
19//!
20//! The schema models **two distinct inputs** instead of one shape with a mode
21//! flag:
22//!
23//! - *send*: `target` + `message` are required (optionally `constraints`,
24//!   `expecting`, `expects_reply`);
25//! - *cancel*: `cancel` (a `delivery_id` from your own ack) is given, and
26//!   `target`/`message` must be absent.
27//!
28//! Mixing both is an error — the tool never guesses which call the model
29//! meant. The host receives the caller's session id (resolved from the harness
30//! binding) so it can attribute the message without trusting model input.
31
32use std::sync::{Arc, OnceLock};
33
34use async_trait::async_trait;
35use rpi_agent::agent_tool::AgentTool;
36use rpi_agent::error::AgentError;
37use rpi_agent::types::{AgentToolResult, ToolExecutionMode, ToolResultPartial};
38use rpi_ai::types::Tool;
39use rpi_harness::agent_harness::WeakAgentHarness;
40use schemars::JsonSchema;
41use serde::Deserialize;
42use tokio_util::sync::CancellationToken;
43
44pub const MESSAGE_AGENT_TOOL_NAME: &str = "message_agent";
45pub const MESSAGE_MAX_CHARS: usize = 16_000;
46const TARGET_MAX_CHARS: usize = 128;
47const FREE_TEXT_MAX_CHARS: usize = 4_000;
48const DELIVERY_ID_MAX_CHARS: usize = 128;
49
50#[derive(Debug, Clone, Deserialize, JsonSchema)]
51pub struct MessageAgentInput {
52    /// Who to message: a roster name or handle. Required for a send; omit when
53    /// cancelling. The host validates it against its live roster.
54    #[serde(default)]
55    pub target: Option<String>,
56    /// The message YOU composed for that agent (max 16000 chars). Do not add a
57    /// "Message from …" prefix; the host adds it. Required for a send; omit
58    /// when cancelling.
59    #[serde(default)]
60    pub message: Option<String>,
61    /// Limits their answer must respect (scope, length, format).
62    #[serde(default)]
63    pub constraints: Option<String>,
64    /// What you need back from them; shown to them as the reply they owe you.
65    #[serde(default)]
66    pub expecting: Option<String>,
67    /// false: notify only — no reply comes back and nothing wakes you.
68    #[serde(default = "default_expects_reply")]
69    pub expects_reply: bool,
70    /// Cancel mode: a `delivery_id` from your own ack. Withdraws that queued
71    /// request or stops the turn it started. Cannot be combined with
72    /// `target`/`message`.
73    #[serde(default)]
74    pub cancel: Option<String>,
75}
76
77fn default_expects_reply() -> bool {
78    true
79}
80
81/// A validated dispatch request handed to the host (source id filled in).
82#[derive(Debug, Clone)]
83pub struct MessageAgentRequest {
84    /// Session that called the tool (resolved by the engine, not by the model).
85    pub source_session_id: String,
86    pub target: String,
87    pub message: String,
88    pub constraints: Option<String>,
89    pub expecting: Option<String>,
90    pub expects_reply: bool,
91}
92
93#[derive(Debug, Clone)]
94pub struct MessageAgentAck {
95    pub delivery_id: String,
96    pub status: String,
97}
98
99/// Host delivery door. Implementations enqueue the message and return at once.
100#[async_trait]
101pub trait MessageAgentHandler: Send + Sync {
102    async fn dispatch(&self, request: MessageAgentRequest) -> Result<MessageAgentAck, String>;
103
104    /// Optional cancellation door. Default = unsupported (the tool reports the
105    /// handler's refusal; it never pretends the request was withdrawn).
106    async fn cancel(&self, _source_session_id: &str, _delivery_id: &str) -> Result<(), String> {
107        Err("message_agent: this host does not support cancelling deliveries".into())
108    }
109}
110
111static HANDLER: OnceLock<Arc<dyn MessageAgentHandler>> = OnceLock::new();
112
113/// Install the host delivery door (once per process). Returns false when a
114/// handler was already installed.
115pub fn set_handler(handler: Arc<dyn MessageAgentHandler>) -> bool {
116    HANDLER.set(handler).is_ok()
117}
118
119pub fn handler_installed() -> bool {
120    HANDLER.get().is_some()
121}
122
123fn handler() -> Result<&'static Arc<dyn MessageAgentHandler>, String> {
124    HANDLER
125        .get()
126        .ok_or_else(|| "message_agent: no host handler installed".to_owned())
127}
128
129pub struct MessageAgentTool {
130    schema: Tool,
131    binding: Arc<OnceLock<WeakAgentHarness>>,
132}
133
134pub fn create_message_agent_tool(binding: Arc<OnceLock<WeakAgentHarness>>) -> Arc<dyn AgentTool> {
135    let params = schemars::schema_for!(MessageAgentInput);
136    Arc::new(MessageAgentTool {
137        binding,
138        schema: Tool {
139            name: MESSAGE_AGENT_TOOL_NAME.to_string(),
140            description: "Send a message to ANOTHER agent (teammate) on this install. FIRE-AND-FORGET: it validates the target against the live roster, delivers into that agent's Bot Chat with your attribution prefixed, and returns a dispatch ack at once (status queued + delivery_id: a hand-off, not a receipt). It never returns the reply: finish your turn and the reply arrives later through the host. COMPOSE the message yourself (lead with the point and the concrete ask); never paste the user's words verbatim or share private 1:1 content. To withdraw a message you already sent, call with `cancel` set to its delivery_id instead of target/message.".to_string(),
141            parameters: rpi_ai::types::Schema::new(
142                serde_json::to_value(params).unwrap_or_default(),
143            ),
144            constrained_sampling: None,
145        },
146    })
147}
148
149fn validate_target(target: &str) -> Result<String, String> {
150    let trimmed = target.trim();
151    if trimmed.is_empty() || trimmed.chars().count() > TARGET_MAX_CHARS {
152        return Err("message_agent: target must be a non-empty roster name (≤128 chars)".into());
153    }
154    if trimmed.chars().any(char::is_control) {
155        return Err("message_agent: target contains control characters".into());
156    }
157    Ok(trimmed.to_owned())
158}
159
160fn validate_delivery_id(raw: &str) -> Result<String, String> {
161    let trimmed = raw.trim();
162    if trimmed.is_empty() {
163        return Err("message_agent: cancel requires a delivery_id from your own ack".into());
164    }
165    if trimmed.chars().count() > DELIVERY_ID_MAX_CHARS {
166        return Err("message_agent: delivery_id is too long (≤128 chars)".into());
167    }
168    if !trimmed
169        .chars()
170        .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
171    {
172        return Err(
173            "message_agent: delivery_id may only contain letters, digits, '-' and '_'".into(),
174        );
175    }
176    Ok(trimmed.to_owned())
177}
178
179fn validate_free_text(field: &str, raw: Option<&str>) -> Result<Option<String>, String> {
180    let Some(text) = raw.map(str::trim).filter(|text| !text.is_empty()) else {
181        return Ok(None);
182    };
183    if text.chars().count() > FREE_TEXT_MAX_CHARS {
184        return Err(format!(
185            "message_agent: {field} is too long (≤{FREE_TEXT_MAX_CHARS} chars)"
186        ));
187    }
188    if text
189        .chars()
190        .any(|c| c.is_control() && c != '\n' && c != '\t')
191    {
192        return Err(format!(
193            "message_agent: {field} contains control characters"
194        ));
195    }
196    Ok(Some(text.to_owned()))
197}
198
199/// The two valid call shapes. Parsing is where "send vs cancel" is decided, so
200/// the executor never carries an ambient mode flag.
201enum MessageAgentCall {
202    Send {
203        target: String,
204        message: String,
205        constraints: Option<String>,
206        expecting: Option<String>,
207        expects_reply: bool,
208    },
209    Cancel {
210        delivery_id: String,
211    },
212}
213
214fn parse_call(input: &MessageAgentInput) -> Result<MessageAgentCall, String> {
215    if let Some(raw_cancel) = input.cancel.as_deref() {
216        let delivery_id = validate_delivery_id(raw_cancel)?;
217        let has_target = input
218            .target
219            .as_deref()
220            .map(str::trim)
221            .is_some_and(|text| !text.is_empty());
222        let has_message = input
223            .message
224            .as_deref()
225            .map(str::trim)
226            .is_some_and(|text| !text.is_empty());
227        if has_target || has_message {
228            return Err(
229                "message_agent: `cancel` cannot be combined with `target`/`message`".into(),
230            );
231        }
232        return Ok(MessageAgentCall::Cancel { delivery_id });
233    }
234
235    let target = validate_target(input.target.as_deref().unwrap_or(""))?;
236    let message = input.message.as_deref().map(str::trim).unwrap_or("");
237    if message.is_empty() {
238        return Err("message_agent: message must be non-empty".into());
239    }
240    if message.chars().count() > MESSAGE_MAX_CHARS {
241        return Err(format!(
242            "message_agent: message is too long (≤{MESSAGE_MAX_CHARS} chars)"
243        ));
244    }
245    Ok(MessageAgentCall::Send {
246        target,
247        message: message.to_owned(),
248        constraints: validate_free_text("constraints", input.constraints.as_deref())?,
249        expecting: validate_free_text("expecting", input.expecting.as_deref())?,
250        expects_reply: input.expects_reply,
251    })
252}
253
254#[async_trait]
255impl AgentTool for MessageAgentTool {
256    fn schema(&self) -> &Tool {
257        &self.schema
258    }
259
260    fn label(&self) -> &str {
261        MESSAGE_AGENT_TOOL_NAME
262    }
263
264    fn execution_mode(&self) -> ToolExecutionMode {
265        // Messaging is a cheap enqueue; parallel batches are fine.
266        ToolExecutionMode::Parallel
267    }
268
269    async fn execute(
270        &self,
271        _tool_call_id: &str,
272        params: serde_json::Value,
273        signal: CancellationToken,
274        _on_update: Arc<dyn Fn(ToolResultPartial) + Send + Sync>,
275    ) -> Result<AgentToolResult, AgentError> {
276        let input: MessageAgentInput = serde_json::from_value(params).map_err(|error| {
277            AgentError::Validation(format!("message_agent input invalid: {error}"))
278        })?;
279        if signal.is_cancelled() {
280            return Err(AgentError::Tool("message_agent cancelled".into()));
281        }
282        let caller = self.caller().await?;
283        let host = handler().map_err(AgentError::Tool)?;
284        execute_input(host, &caller.session_id, input, &signal).await
285    }
286}
287
288/// Execution body shared by `execute` and the unit tests (which supply a fake
289/// door + session id instead of a live harness).
290async fn execute_input(
291    host: &Arc<dyn MessageAgentHandler>,
292    source_session_id: &str,
293    input: MessageAgentInput,
294    signal: &CancellationToken,
295) -> Result<AgentToolResult, AgentError> {
296    match parse_call(&input).map_err(AgentError::Validation)? {
297        MessageAgentCall::Cancel { delivery_id } => {
298            host.cancel(source_session_id, &delivery_id)
299                .await
300                .map_err(AgentError::Tool)?;
301            Ok(AgentToolResult::text(
302                serde_json::json!({
303                    "status": "cancelled",
304                    "delivery_id": delivery_id,
305                })
306                .to_string(),
307            ))
308        }
309        MessageAgentCall::Send {
310            target,
311            message,
312            constraints,
313            expecting,
314            expects_reply,
315        } => {
316            let ack = host
317                .dispatch(MessageAgentRequest {
318                    source_session_id: source_session_id.to_owned(),
319                    target,
320                    message,
321                    constraints,
322                    expecting,
323                    expects_reply,
324                })
325                .await
326                .map_err(AgentError::Tool)?;
327            if signal.is_cancelled() {
328                return Err(AgentError::Tool("message_agent cancelled".into()));
329            }
330            Ok(AgentToolResult::text(
331                serde_json::json!({
332                    "status": ack.status,
333                    "delivery_id": ack.delivery_id,
334                    "reply_delivery": if expects_reply { "notification" } else { "none" },
335                })
336                .to_string(),
337            ))
338        }
339    }
340}
341
342impl MessageAgentTool {
343    async fn caller(&self) -> Result<ResolvedCaller, AgentError> {
344        let weak = self
345            .binding
346            .get()
347            .ok_or_else(|| AgentError::Tool("message_agent: session binding not ready".into()))?;
348        let harness = weak
349            .upgrade()
350            .ok_or_else(|| AgentError::Tool("message_agent: session is gone".into()))?;
351        let metadata = harness.session().get_metadata().await.map_err(|error| {
352            AgentError::Tool(format!(
353                "message_agent: session metadata unavailable: {error}"
354            ))
355        })?;
356        Ok(ResolvedCaller {
357            session_id: metadata.id,
358        })
359    }
360}
361
362struct ResolvedCaller {
363    session_id: String,
364}
365
366#[cfg(test)]
367mod tests {
368    use super::*;
369    use std::sync::Mutex;
370
371    #[derive(Default)]
372    struct RecordingDoor {
373        dispatched: Mutex<Vec<MessageAgentRequest>>,
374        cancelled: Mutex<Vec<(String, String)>>,
375    }
376
377    #[async_trait]
378    impl MessageAgentHandler for RecordingDoor {
379        async fn dispatch(&self, request: MessageAgentRequest) -> Result<MessageAgentAck, String> {
380            self.dispatched.lock().unwrap().push(request);
381            Ok(MessageAgentAck {
382                delivery_id: "delivery-1".into(),
383                status: "queued".into(),
384            })
385        }
386
387        async fn cancel(&self, source: &str, delivery: &str) -> Result<(), String> {
388            self.cancelled
389                .lock()
390                .unwrap()
391                .push((source.to_owned(), delivery.to_owned()));
392            Ok(())
393        }
394    }
395
396    fn input(value: serde_json::Value) -> MessageAgentInput {
397        serde_json::from_value(value).unwrap()
398    }
399
400    async fn run(
401        door: &Arc<dyn MessageAgentHandler>,
402        value: serde_json::Value,
403    ) -> Result<AgentToolResult, AgentError> {
404        execute_input(door, "session-1", input(value), &CancellationToken::new()).await
405    }
406
407    #[test]
408    fn targets_are_trimmed_and_bounded() {
409        assert_eq!(validate_target(" 微软 ").unwrap(), "微软");
410        assert!(validate_target("   ").is_err());
411        assert!(validate_target(&"a".repeat(TARGET_MAX_CHARS + 1)).is_err());
412    }
413
414    #[test]
415    fn delivery_ids_are_validated() {
416        assert_eq!(validate_delivery_id(" delivery-1 ").unwrap(), "delivery-1");
417        assert!(validate_delivery_id("   ").is_err());
418        assert!(validate_delivery_id(&"a".repeat(DELIVERY_ID_MAX_CHARS + 1)).is_err());
419        assert!(validate_delivery_id("bad id!").is_err());
420    }
421
422    fn text_of(result: &AgentToolResult) -> String {
423        match result.content.first() {
424            Some(rpi_agent::types::TextContentOrImage::Text(text)) => text.text.clone(),
425            other => panic!("expected a single text block, got {other:?}"),
426        }
427    }
428
429    /// Send shape reaches the door with the caller's session id and every
430    /// field intact; ack is surfaced as the tool's JSON result (reviewer #5:
431    /// execution, not just shape).
432    #[tokio::test]
433    async fn send_dispatches_through_the_door() {
434        let door = Arc::new(RecordingDoor::default());
435        let door_dyn: Arc<dyn MessageAgentHandler> = door.clone();
436        let result = run(
437            &door_dyn,
438            serde_json::json!({
439                "target": "微软",
440                "message": "hi",
441                "constraints": "short",
442                "expecting": "one line",
443                "expects_reply": true,
444            }),
445        )
446        .await
447        .unwrap();
448        let output = text_of(&result);
449        assert!(output.contains("\"status\":\"queued\""));
450        assert!(output.contains("\"delivery_id\":\"delivery-1\""));
451        assert!(output.contains("\"reply_delivery\":\"notification\""));
452        let recorded = door.dispatched.lock().unwrap();
453        assert_eq!(recorded.len(), 1);
454        assert_eq!(recorded[0].source_session_id, "session-1");
455        assert_eq!(recorded[0].target, "微软");
456        assert_eq!(recorded[0].expecting.as_deref(), Some("one line"));
457    }
458
459    /// Cancel shape never dispatches; the delivery door gets the ack id.
460    #[tokio::test]
461    async fn cancel_goes_to_the_cancel_door_only() {
462        let door = Arc::new(RecordingDoor::default());
463        let door_dyn: Arc<dyn MessageAgentHandler> = door.clone();
464        let result = run(&door_dyn, serde_json::json!({ "cancel": "delivery-9" }))
465            .await
466            .unwrap();
467        assert!(text_of(&result).contains("\"status\":\"cancelled\""));
468        assert!(door.dispatched.lock().unwrap().is_empty());
469        let cancelled = door.cancelled.lock().unwrap();
470        assert_eq!(
471            cancelled.as_slice(),
472            &[("session-1".to_owned(), "delivery-9".to_owned())]
473        );
474    }
475
476    /// Mixing cancel with send fields is rejected before any door call.
477    #[tokio::test]
478    async fn cancel_with_send_fields_is_invalid() {
479        let door = Arc::new(RecordingDoor::default());
480        let door_dyn: Arc<dyn MessageAgentHandler> = door.clone();
481        let error = run(
482            &door_dyn,
483            serde_json::json!({ "cancel": "delivery-9", "target": "微软" }),
484        )
485        .await
486        .unwrap_err();
487        assert!(matches!(error, AgentError::Validation(_)));
488        assert!(door.dispatched.lock().unwrap().is_empty());
489        assert!(door.cancelled.lock().unwrap().is_empty());
490    }
491
492    #[test]
493    fn handler_installation_is_process_global() {
494        // Runs in its own test binary slice; another test may have set it.
495        if !handler_installed() {
496            assert!(set_handler(Arc::new(RecordingDoor::default())));
497        }
498        assert!(handler_installed());
499    }
500}