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 expects_reply = expects_reply;
317            let ack = host
318                .dispatch(MessageAgentRequest {
319                    source_session_id: source_session_id.to_owned(),
320                    target,
321                    message,
322                    constraints,
323                    expecting,
324                    expects_reply,
325                })
326                .await
327                .map_err(AgentError::Tool)?;
328            if signal.is_cancelled() {
329                return Err(AgentError::Tool("message_agent cancelled".into()));
330            }
331            Ok(AgentToolResult::text(
332                serde_json::json!({
333                    "status": ack.status,
334                    "delivery_id": ack.delivery_id,
335                    "reply_delivery": if expects_reply { "notification" } else { "none" },
336                })
337                .to_string(),
338            ))
339        }
340    }
341}
342
343impl MessageAgentTool {
344    async fn caller(&self) -> Result<ResolvedCaller, AgentError> {
345        let weak = self
346            .binding
347            .get()
348            .ok_or_else(|| AgentError::Tool("message_agent: session binding not ready".into()))?;
349        let harness = weak
350            .upgrade()
351            .ok_or_else(|| AgentError::Tool("message_agent: session is gone".into()))?;
352        let metadata = harness.session().get_metadata().await.map_err(|error| {
353            AgentError::Tool(format!(
354                "message_agent: session metadata unavailable: {error}"
355            ))
356        })?;
357        Ok(ResolvedCaller {
358            session_id: metadata.id,
359        })
360    }
361}
362
363struct ResolvedCaller {
364    session_id: String,
365}
366
367#[cfg(test)]
368mod tests {
369    use super::*;
370    use std::sync::Mutex;
371
372    #[derive(Default)]
373    struct RecordingDoor {
374        dispatched: Mutex<Vec<MessageAgentRequest>>,
375        cancelled: Mutex<Vec<(String, String)>>,
376    }
377
378    #[async_trait]
379    impl MessageAgentHandler for RecordingDoor {
380        async fn dispatch(&self, request: MessageAgentRequest) -> Result<MessageAgentAck, String> {
381            self.dispatched.lock().unwrap().push(request);
382            Ok(MessageAgentAck {
383                delivery_id: "delivery-1".into(),
384                status: "queued".into(),
385            })
386        }
387
388        async fn cancel(&self, source: &str, delivery: &str) -> Result<(), String> {
389            self.cancelled
390                .lock()
391                .unwrap()
392                .push((source.to_owned(), delivery.to_owned()));
393            Ok(())
394        }
395    }
396
397    fn input(value: serde_json::Value) -> MessageAgentInput {
398        serde_json::from_value(value).unwrap()
399    }
400
401    async fn run(
402        door: &Arc<dyn MessageAgentHandler>,
403        value: serde_json::Value,
404    ) -> Result<AgentToolResult, AgentError> {
405        execute_input(door, "session-1", input(value), &CancellationToken::new()).await
406    }
407
408    #[test]
409    fn targets_are_trimmed_and_bounded() {
410        assert_eq!(validate_target(" 微软 ").unwrap(), "微软");
411        assert!(validate_target("   ").is_err());
412        assert!(validate_target(&"a".repeat(TARGET_MAX_CHARS + 1)).is_err());
413    }
414
415    #[test]
416    fn delivery_ids_are_validated() {
417        assert_eq!(validate_delivery_id(" delivery-1 ").unwrap(), "delivery-1");
418        assert!(validate_delivery_id("   ").is_err());
419        assert!(validate_delivery_id(&"a".repeat(DELIVERY_ID_MAX_CHARS + 1)).is_err());
420        assert!(validate_delivery_id("bad id!").is_err());
421    }
422
423    fn text_of(result: &AgentToolResult) -> String {
424        match result.content.first() {
425            Some(rpi_agent::types::TextContentOrImage::Text(text)) => text.text.clone(),
426            other => panic!("expected a single text block, got {other:?}"),
427        }
428    }
429
430    /// Send shape reaches the door with the caller's session id and every
431    /// field intact; ack is surfaced as the tool's JSON result (reviewer #5:
432    /// execution, not just shape).
433    #[tokio::test]
434    async fn send_dispatches_through_the_door() {
435        let door = Arc::new(RecordingDoor::default());
436        let door_dyn: Arc<dyn MessageAgentHandler> = door.clone();
437        let result = run(
438            &door_dyn,
439            serde_json::json!({
440                "target": "微软",
441                "message": "hi",
442                "constraints": "short",
443                "expecting": "one line",
444                "expects_reply": true,
445            }),
446        )
447        .await
448        .unwrap();
449        let output = text_of(&result);
450        assert!(output.contains("\"status\":\"queued\""));
451        assert!(output.contains("\"delivery_id\":\"delivery-1\""));
452        assert!(output.contains("\"reply_delivery\":\"notification\""));
453        let recorded = door.dispatched.lock().unwrap();
454        assert_eq!(recorded.len(), 1);
455        assert_eq!(recorded[0].source_session_id, "session-1");
456        assert_eq!(recorded[0].target, "微软");
457        assert_eq!(recorded[0].expecting.as_deref(), Some("one line"));
458    }
459
460    /// Cancel shape never dispatches; the delivery door gets the ack id.
461    #[tokio::test]
462    async fn cancel_goes_to_the_cancel_door_only() {
463        let door = Arc::new(RecordingDoor::default());
464        let door_dyn: Arc<dyn MessageAgentHandler> = door.clone();
465        let result = run(&door_dyn, serde_json::json!({ "cancel": "delivery-9" }))
466            .await
467            .unwrap();
468        assert!(text_of(&result).contains("\"status\":\"cancelled\""));
469        assert!(door.dispatched.lock().unwrap().is_empty());
470        let cancelled = door.cancelled.lock().unwrap();
471        assert_eq!(
472            cancelled.as_slice(),
473            &[("session-1".to_owned(), "delivery-9".to_owned())]
474        );
475    }
476
477    /// Mixing cancel with send fields is rejected before any door call.
478    #[tokio::test]
479    async fn cancel_with_send_fields_is_invalid() {
480        let door = Arc::new(RecordingDoor::default());
481        let door_dyn: Arc<dyn MessageAgentHandler> = door.clone();
482        let error = run(
483            &door_dyn,
484            serde_json::json!({ "cancel": "delivery-9", "target": "微软" }),
485        )
486        .await
487        .unwrap_err();
488        assert!(matches!(error, AgentError::Validation(_)));
489        assert!(door.dispatched.lock().unwrap().is_empty());
490        assert!(door.cancelled.lock().unwrap().is_empty());
491    }
492
493    #[test]
494    fn handler_installation_is_process_global() {
495        // Runs in its own test binary slice; another test may have set it.
496        if !handler_installed() {
497            assert!(set_handler(Arc::new(RecordingDoor::default())));
498        }
499        assert!(handler_installed());
500    }
501}