Skip to main content

rpi_cli/remote/
protocol.rs

1//! Shared wire protocol for rpi's headless RPC mode (`--mode rpc`, the server)
2//! and the remote client (`--connect`).
3//!
4//! Single source of truth: the server serializes these types and the client
5//! deserializes them, so the contract cannot drift between the two ends.
6//!
7//! Wire shape (one JSON object per line):
8//! - the server opens with `{"type":"ready"}`, then
9//! - streams [`RemoteEvent`]s (`{"type":"agent_start"}`, `{"type":"message_update",…}`, …), and
10//! - answers each [`RemoteCommand`] with a [`RemoteResponse`] (`{"type":"response",…}`).
11//!
12//! These are intentionally **not** the core `pi-agent`/`pi-ai` types: `AgentEvent`
13//! is documented as process-local (see `pi-agent/src/events.rs`) and deliberately
14//! has no serde impl. This module projects the process-local events into a
15//! stable, wire-safe shape, and translates back only the subset the client needs.
16//! That keeps the core crates untouched and the client free of local resources.
17
18use serde::{Deserialize, Serialize};
19use serde_json::Value;
20
21use rpi_agent::events::AgentEvent;
22use rpi_agent::types::AgentToolResult;
23
24/// A fine-grained lifecycle event streamed from the server to the client.
25///
26/// Mirrors the shape produced by the previous hand-rolled projection in
27/// `modes.rs`; kept field-for-field compatible so existing clients keep working.
28#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
29#[serde(tag = "type", rename_all = "snake_case")]
30pub enum RemoteEvent {
31    UiDialogRequest {
32        #[serde(rename = "requestId")]
33        request_id: String,
34        #[serde(rename = "toolCallId", default)]
35        tool_call_id: Option<String>,
36        ui: Value,
37    },
38    UiDialogClosed {
39        #[serde(rename = "requestId")]
40        request_id: String,
41    },
42    ExtensionUiRequest {
43        id: String,
44        method: String,
45        message: String,
46        #[serde(
47            rename = "notifyType",
48            default,
49            skip_serializing_if = "Option::is_none"
50        )]
51        notify_type: Option<rpi_extensions::UiNotificationLevel>,
52    },
53    AgentStart,
54    AgentEnd {
55        #[serde(rename = "messageCount")]
56        message_count: usize,
57        messages: Value,
58    },
59    RetryScheduled {
60        attempt: u32,
61        #[serde(rename = "maxRetries")]
62        max_retries: u32,
63        #[serde(rename = "delayMs")]
64        delay_ms: u64,
65        error: String,
66    },
67    TurnStart,
68    TurnEnd {
69        message: Value,
70        #[serde(rename = "toolResultCount")]
71        tool_result_count: usize,
72        #[serde(rename = "toolResults")]
73        tool_results: Value,
74        /// Queue depth when this turn settled, so a client can render
75        /// "N queued". Defaulted for wire compatibility with older peers.
76        #[serde(default, rename = "pendingMessages")]
77        pending_messages: usize,
78    },
79    MessageStart {
80        #[serde(rename = "messageId", default, skip_serializing_if = "Option::is_none")]
81        message_id: Option<String>,
82        #[serde(default)]
83        message: Value,
84    },
85    MessageEnd {
86        #[serde(rename = "messageId", default, skip_serializing_if = "Option::is_none")]
87        message_id: Option<String>,
88        #[serde(default)]
89        message: Value,
90    },
91    MessageUpdate {
92        #[serde(rename = "messageId", default, skip_serializing_if = "Option::is_none")]
93        message_id: Option<String>,
94        #[serde(default)]
95        message: Value,
96        #[serde(rename = "assistantMessageEvent", default)]
97        assistant_message_event: Value,
98        #[serde(rename = "eventType", default)]
99        event_type: String,
100        /// Convenience mirror of the delta's content index (text/thinking/tool-call
101        /// deltas only), so the client can apply deltas without re-parsing the
102        /// nested event.
103        #[serde(
104            rename = "contentIndex",
105            default,
106            skip_serializing_if = "Option::is_none"
107        )]
108        content_index: Option<u64>,
109        /// Convenience mirror of the appended text for text/thinking deltas.
110        #[serde(default, skip_serializing_if = "Option::is_none")]
111        delta: Option<String>,
112    },
113    ToolExecutionStart {
114        #[serde(rename = "toolCallId")]
115        tool_call_id: String,
116        #[serde(rename = "toolName")]
117        tool_name: String,
118        #[serde(default)]
119        args: Value,
120    },
121    ToolExecutionUpdate {
122        #[serde(rename = "toolCallId")]
123        tool_call_id: String,
124        #[serde(rename = "toolName")]
125        tool_name: String,
126        #[serde(default)]
127        args: Value,
128        #[serde(rename = "partialResult")]
129        partial_result: Value,
130    },
131    ToolExecutionEnd {
132        #[serde(rename = "toolCallId")]
133        tool_call_id: String,
134        #[serde(rename = "toolName")]
135        tool_name: String,
136        #[serde(rename = "isError")]
137        is_error: bool,
138        result: Value,
139    },
140}
141
142impl RemoteEvent {
143    /// The wire `type` tag (kept in sync with the serde `rename_all`).
144    pub fn type_tag(&self) -> &'static str {
145        match self {
146            RemoteEvent::UiDialogRequest { .. } => "ui_dialog_request",
147            RemoteEvent::UiDialogClosed { .. } => "ui_dialog_closed",
148            RemoteEvent::ExtensionUiRequest { .. } => "extension_ui_request",
149            RemoteEvent::AgentStart => "agent_start",
150            RemoteEvent::AgentEnd { .. } => "agent_end",
151            RemoteEvent::RetryScheduled { .. } => "retry_scheduled",
152            RemoteEvent::TurnStart => "turn_start",
153            RemoteEvent::TurnEnd { .. } => "turn_end",
154            RemoteEvent::MessageStart { .. } => "message_start",
155            RemoteEvent::MessageUpdate { .. } => "message_update",
156            RemoteEvent::MessageEnd { .. } => "message_end",
157            RemoteEvent::ToolExecutionStart { .. } => "tool_execution_start",
158            RemoteEvent::ToolExecutionUpdate { .. } => "tool_execution_update",
159            RemoteEvent::ToolExecutionEnd { .. } => "tool_execution_end",
160        }
161    }
162
163    /// True for the terminal `AgentEnd` event.
164    pub fn is_terminal(&self) -> bool {
165        matches!(self, RemoteEvent::AgentEnd { .. })
166    }
167
168    /// Project a process-local [`AgentEvent`] onto the wire shape.
169    pub fn from_agent_event(event: &AgentEvent) -> Self {
170        use rpi_ai::types::AssistantMessageEvent;
171        match event {
172            AgentEvent::AgentStart => RemoteEvent::AgentStart,
173            AgentEvent::AgentEnd { messages } => RemoteEvent::AgentEnd {
174                message_count: messages.len(),
175                messages: serde_json::to_value(messages).unwrap_or(Value::Null),
176            },
177            AgentEvent::RetryScheduled {
178                attempt,
179                max_retries,
180                delay_ms,
181                error,
182            } => RemoteEvent::RetryScheduled {
183                attempt: *attempt,
184                max_retries: *max_retries,
185                delay_ms: *delay_ms,
186                error: error.clone(),
187            },
188            AgentEvent::TurnStart => RemoteEvent::TurnStart,
189            AgentEvent::TurnEnd {
190                message,
191                tool_results,
192                pending_messages,
193                ..
194            } => RemoteEvent::TurnEnd {
195                message: serde_json::to_value(message).unwrap_or(Value::Null),
196                tool_result_count: tool_results.len(),
197                tool_results: serde_json::to_value(tool_results).unwrap_or(Value::Null),
198                pending_messages: *pending_messages,
199            },
200            AgentEvent::MessageStart {
201                message,
202                message_id,
203            } => RemoteEvent::MessageStart {
204                message_id: message_id.clone(),
205                message: serde_json::to_value(message).unwrap_or(Value::Null),
206            },
207            AgentEvent::MessageEnd {
208                message,
209                message_id,
210            } => RemoteEvent::MessageEnd {
211                message_id: message_id.clone(),
212                message: serde_json::to_value(message).unwrap_or(Value::Null),
213            },
214            AgentEvent::MessageUpdate {
215                message_id,
216                message,
217                assistant_message_event,
218            } => {
219                let (content_index, delta) = match assistant_message_event.as_ref() {
220                    AssistantMessageEvent::TextDelta {
221                        content_index,
222                        delta,
223                        ..
224                    }
225                    | AssistantMessageEvent::ThinkingDelta {
226                        content_index,
227                        delta,
228                        ..
229                    }
230                    | AssistantMessageEvent::ToolCallDelta {
231                        content_index,
232                        delta,
233                        ..
234                    } => (Some(*content_index as u64), Some(delta.clone())),
235                    _ => (None, None),
236                };
237                RemoteEvent::MessageUpdate {
238                    message_id: message_id.clone(),
239                    // `assistant_json` keeps this identical to the
240                    // `AgentMessage` encoding without copying the message.
241                    message: rpi_agent::message::assistant_json(message),
242                    assistant_message_event: serde_json::to_value(assistant_message_event)
243                        .unwrap_or(Value::Null),
244                    event_type: assistant_message_event.type_tag().to_string(),
245                    content_index,
246                    delta,
247                }
248            }
249            AgentEvent::ToolExecutionStart {
250                tool_call_id,
251                tool_name,
252                args,
253            } => RemoteEvent::ToolExecutionStart {
254                tool_call_id: tool_call_id.clone(),
255                tool_name: tool_name.clone(),
256                args: args.clone(),
257            },
258            AgentEvent::ToolExecutionUpdate {
259                tool_call_id,
260                tool_name,
261                args,
262                partial_result,
263            } => RemoteEvent::ToolExecutionUpdate {
264                tool_call_id: tool_call_id.clone(),
265                tool_name: tool_name.clone(),
266                args: args.clone(),
267                partial_result: tool_result_json(partial_result),
268            },
269            AgentEvent::ToolExecutionEnd {
270                tool_call_id,
271                tool_name,
272                result,
273                is_error,
274            } => RemoteEvent::ToolExecutionEnd {
275                tool_call_id: tool_call_id.clone(),
276                tool_name: tool_name.clone(),
277                is_error: *is_error,
278                result: tool_result_json(result),
279            },
280        }
281    }
282}
283
284/// Serialize a tool result into the stable wire shape (content blocks, details,
285/// usage, and the batch hints).
286pub fn tool_result_json(result: &AgentToolResult) -> Value {
287    serde_json::to_value(result)
288        .expect("AgentToolResult contains only JSON-serializable native content, details and usage")
289}
290
291/// A command sent from the client to the server (`{"id":…,"type":…,…}`).
292///
293/// The `id` is attached by the client when sending (see
294/// [`with_id`](RemoteCommand::with_id)) so responses can be correlated.
295#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
296#[serde(tag = "type", rename_all = "snake_case")]
297pub enum RemoteCommand {
298    UiDialogResponse {
299        #[serde(rename = "requestId")]
300        request_id: String,
301        #[serde(default, skip_serializing_if = "Option::is_none")]
302        answer: Option<Value>,
303        #[serde(default)]
304        cancelled: bool,
305    },
306    /// Run a prompt on the remote `main` lane; events stream until `agent_end`.
307    Prompt { content: String },
308    /// Abort the in-flight run.
309    Abort,
310    /// Fetch the current session state (model, thinking, tools, ids).
311    GetState,
312    /// Switch the active model by id.
313    SetModel { model: String },
314    /// Set the thinking level (`off`…`max`).
315    SetThinkingLevel { level: String },
316    /// Replace the active tool set.
317    SetActiveTools { tools: Vec<String> },
318    /// Liveness probe.
319    Ping,
320    /// Ask the server to end the session loop.
321    Stop,
322}
323
324impl RemoteCommand {
325    /// Serialize the command with an `id` field for request/response correlation.
326    pub fn with_id(&self, id: impl Into<Value>) -> Value {
327        let mut value = serde_json::to_value(self).unwrap_or(Value::Null);
328        if let Some(object) = value.as_object_mut() {
329            object.insert("id".to_string(), id.into());
330        }
331        value
332    }
333}
334
335/// Response status for a [`RemoteResponse`].
336#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
337#[serde(rename_all = "lowercase")]
338pub enum ResponseStatus {
339    Ok,
340    Error,
341}
342
343/// The server's answer to a single [`RemoteCommand`].
344#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
345pub struct RemoteResponse {
346    #[serde(default)]
347    pub id: Value,
348    pub status: ResponseStatus,
349    #[serde(default, skip_serializing_if = "Option::is_none")]
350    pub result: Option<Value>,
351    #[serde(default, skip_serializing_if = "Option::is_none")]
352    pub error: Option<String>,
353}
354
355impl RemoteResponse {
356    /// A successful response carrying an optional result payload.
357    pub fn ok(id: Value, result: Value) -> Self {
358        Self {
359            id,
360            status: ResponseStatus::Ok,
361            result: Some(result),
362            error: None,
363        }
364    }
365
366    /// A failed response carrying an error message.
367    pub fn error(id: Value, error: impl Into<String>) -> Self {
368        Self {
369            id,
370            status: ResponseStatus::Error,
371            result: None,
372            error: Some(error.into()),
373        }
374    }
375
376    /// True when the request succeeded.
377    pub fn is_ok(&self) -> bool {
378        matches!(self.status, ResponseStatus::Ok)
379    }
380
381    /// Serialize to the wire shape, adding the `"type":"response"` tag.
382    pub fn to_json(&self) -> Value {
383        let mut value = serde_json::to_value(self).unwrap_or(Value::Null);
384        if let Some(object) = value.as_object_mut() {
385            object.insert("type".to_string(), Value::String("response".to_string()));
386        }
387        value
388    }
389}
390
391/// The `get_state` result payload, as a typed view over the response.
392#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
393pub struct SessionState {
394    #[serde(default)]
395    pub model: Option<String>,
396    #[serde(rename = "thinkingLevel", default)]
397    pub thinking_level: Option<Value>,
398    #[serde(rename = "activeTools", default)]
399    pub active_tools: Vec<String>,
400    #[serde(rename = "leafId", default)]
401    pub leaf_id: Option<String>,
402    #[serde(rename = "sessionId", default)]
403    pub session_id: Option<String>,
404}
405
406/// The `prompt` result payload (`{outcome, finalText}`).
407#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
408pub struct PromptOutcome {
409    #[serde(default)]
410    pub outcome: Option<String>,
411    #[serde(rename = "finalText", default)]
412    pub final_text: Option<String>,
413}
414
415#[cfg(test)]
416mod tests {
417    use super::*;
418    use rpi_agent::types::AgentToolResult;
419
420    fn signed_native_result() -> AgentToolResult {
421        use rpi_agent::types::TextContentOrImage;
422        AgentToolResult {
423            content: vec![
424                TextContentOrImage::Text(
425                    serde_json::from_value(serde_json::json!({
426                        "type":"text", "text":"signed 界😀", "textSignature":
427                            "{ \"version\": 1, \"id\": \"sig-😀\" }",
428                    }))
429                    .unwrap(),
430                ),
431                TextContentOrImage::Image(
432                    serde_json::from_value(serde_json::json!({
433                        "type":"image", "data":"AAEC+/==", "mimeType":"image/png",
434                    }))
435                    .unwrap(),
436                ),
437            ],
438            details: serde_json::json!({"runtimeKey":"business", "runtimeHandle":{"id":7},
439                "__rpi":{"owner":"customer"}, "__rpiRuntimeKey":"unchanged"}),
440            usage: Some(rpi_ai::types::Usage::zero()),
441            added_tool_names: vec!["read".into(), "read".into()],
442            terminate: true,
443        }
444    }
445
446    #[test]
447    fn tool_update_preserves_canonical_native_result_and_text_signature() {
448        let result = signed_native_result();
449        let expected = serde_json::to_value(&result).unwrap();
450        let event = AgentEvent::ToolExecutionUpdate {
451            tool_call_id: "call".into(),
452            tool_name: "read".into(),
453            args: serde_json::json!({"path":"file"}),
454            partial_result: result.into(),
455        };
456        let wire = serde_json::to_value(RemoteEvent::from_agent_event(&event)).unwrap();
457        assert_eq!(wire["type"], "tool_execution_update");
458        assert_eq!(wire["partialResult"], expected);
459        assert_eq!(
460            wire["partialResult"]["content"][0]["textSignature"],
461            "{ \"version\": 1, \"id\": \"sig-😀\" }"
462        );
463        assert!(wire["partialResult"].get("isError").is_none());
464    }
465
466    #[test]
467    fn tool_end_preserves_canonical_native_result_and_separate_error_authority() {
468        let result = signed_native_result();
469        let expected = serde_json::to_value(&result).unwrap();
470        let event = AgentEvent::ToolExecutionEnd {
471            tool_call_id: "call".into(),
472            tool_name: "read".into(),
473            result,
474            is_error: true,
475        };
476        let wire = serde_json::to_value(RemoteEvent::from_agent_event(&event)).unwrap();
477        assert_eq!(wire["type"], "tool_execution_end");
478        assert_eq!(wire["result"], expected);
479        assert!(wire["result"]["content"][0]["textSignature"].is_string());
480        assert_eq!(wire["isError"], true);
481        assert!(wire["result"].get("isError").is_none());
482        let plain = tool_result_json(&AgentToolResult::text("unsigned"));
483        assert!(plain["content"][0].get("textSignature").is_none());
484        assert!(plain["usage"].is_null());
485    }
486
487    /// The queue depth must survive the native remote projection: a client that
488    /// never sees it cannot render the "N queued" indicator.
489    #[test]
490    fn turn_end_projects_pending_messages() {
491        let event = AgentEvent::TurnEnd {
492            message: rpi_agent::AgentMessage::Assistant(Box::new(
493                rpi_ai::types::AssistantMessage::empty(
494                    rpi_ai::types::Api::AnthropicMessages,
495                    "p",
496                    "m",
497                    0,
498                ),
499            )),
500            tool_results: vec![],
501            pending_messages: 3,
502        };
503        let projected = RemoteEvent::from_agent_event(&event);
504        assert_eq!(projected.type_tag(), "turn_end");
505        let wire = serde_json::to_value(&projected).unwrap();
506        assert_eq!(wire["pendingMessages"], 3, "{wire}");
507
508        // Zero is a real value, not an absent field.
509        let zero = AgentEvent::TurnEnd {
510            message: rpi_agent::AgentMessage::Assistant(Box::new(
511                rpi_ai::types::AssistantMessage::empty(
512                    rpi_ai::types::Api::AnthropicMessages,
513                    "p",
514                    "m",
515                    0,
516                ),
517            )),
518            tool_results: vec![],
519            pending_messages: 0,
520        };
521        let wire = serde_json::to_value(RemoteEvent::from_agent_event(&zero)).unwrap();
522        assert_eq!(wire["pendingMessages"], 0, "{wire}");
523
524        // A peer that predates the field still deserializes.
525        let legacy: RemoteEvent = serde_json::from_value(serde_json::json!({
526            "type":"turn_end", "message":null, "toolResultCount":0, "toolResults":[],
527        }))
528        .unwrap();
529        assert!(matches!(
530            legacy,
531            RemoteEvent::TurnEnd {
532                pending_messages: 0,
533                ..
534            }
535        ));
536    }
537
538    #[test]
539    fn notify_wire_matches_pi_with_an_optional_level() {
540        for wire in [
541            serde_json::json!({"type":"extension_ui_request","id":"n1","method":"notify","message":"ready"}),
542            serde_json::json!({"type":"extension_ui_request","id":"n2","method":"notify","message":"failed","notifyType":"error"}),
543        ] {
544            let event: RemoteEvent = serde_json::from_value(wire.clone()).unwrap();
545            assert_eq!(event.type_tag(), "extension_ui_request");
546            assert_eq!(serde_json::to_value(event).unwrap(), wire);
547        }
548    }
549
550    #[test]
551    fn dialog_wire_shapes_round_trip_with_request_ids() {
552        let event: RemoteEvent = serde_json::from_value(serde_json::json!({
553            "type":"ui_dialog_request", "requestId":"q", "toolCallId":"c",
554            "ui":{"question":"Allow?", "options":["Yes","No"]},
555        }))
556        .unwrap();
557        assert_eq!(event.type_tag(), "ui_dialog_request");
558        assert_eq!(serde_json::to_value(&event).unwrap()["requestId"], "q");
559        let answer = RemoteCommand::UiDialogResponse {
560            request_id: "q".into(),
561            answer: Some(serde_json::json!({"values":["No"]})),
562            cancelled: false,
563        }
564        .with_id(7);
565        assert_eq!(answer["type"], "ui_dialog_response");
566        assert_eq!(answer["requestId"], "q");
567        assert_eq!(answer["answer"]["values"][0], "No");
568        let cancelled = RemoteCommand::UiDialogResponse {
569            request_id: "q".into(),
570            answer: None,
571            cancelled: true,
572        }
573        .with_id(8);
574        assert_eq!(cancelled["cancelled"], true);
575        assert!(cancelled.get("answer").is_none());
576        assert!(
577            matches!(serde_json::from_value::<RemoteEvent>(serde_json::json!({
578            "type":"ui_dialog_closed", "requestId":"q",
579        })).unwrap(), RemoteEvent::UiDialogClosed { request_id } if request_id == "q")
580        );
581    }
582
583    #[test]
584    fn event_projection_matches_wire_shape() {
585        let end = serde_json::to_value(RemoteEvent::from_agent_event(&AgentEvent::AgentEnd {
586            messages: vec![],
587        }))
588        .unwrap();
589        assert_eq!(end["type"], "agent_end");
590        assert_eq!(end["messages"], serde_json::json!([]));
591        assert_eq!(end["messageCount"], 0);
592
593        let tool = serde_json::to_value(RemoteEvent::from_agent_event(
594            &AgentEvent::ToolExecutionEnd {
595                tool_call_id: "call-1".into(),
596                tool_name: "read".into(),
597                result: AgentToolResult::text("hello"),
598                is_error: false,
599            },
600        ))
601        .unwrap();
602        assert_eq!(tool["type"], "tool_execution_end");
603        assert_eq!(tool["result"]["content"][0]["text"], "hello");
604        assert_eq!(tool["result"]["terminate"], false);
605
606        let retry =
607            serde_json::to_value(RemoteEvent::from_agent_event(&AgentEvent::RetryScheduled {
608                attempt: 3,
609                max_retries: 10,
610                delay_ms: 8_000,
611                error: "503 service unavailable".into(),
612            }))
613            .unwrap();
614        assert_eq!(retry["type"], "retry_scheduled");
615        assert_eq!(retry["attempt"], 3);
616        assert_eq!(retry["maxRetries"], 10);
617        assert_eq!(retry["delayMs"], 8_000);
618    }
619
620    #[test]
621    fn native_message_ids_round_trip_and_legacy_messages_remain_optional() {
622        for kind in ["message_start", "message_update", "message_end"] {
623            let legacy = serde_json::json!({"type": kind, "message": {"role":"assistant"}});
624            let parsed: RemoteEvent = serde_json::from_value(legacy).unwrap();
625            assert!(serde_json::to_value(parsed)
626                .unwrap()
627                .get("messageId")
628                .is_none());
629            let value = serde_json::json!({"type": kind, "messageId": "native-\"🐈", "message": {"role":"assistant"}});
630            let parsed: RemoteEvent = serde_json::from_value(value).unwrap();
631            assert_eq!(
632                serde_json::to_value(parsed).unwrap()["messageId"],
633                "native-\"🐈"
634            );
635        }
636    }
637
638    #[test]
639    fn events_round_trip_over_the_wire() {
640        for event in [
641            RemoteEvent::AgentStart,
642            RemoteEvent::MessageUpdate {
643                message_id: Some("entry-1".into()),
644                message: serde_json::json!({"role": "assistant"}),
645                assistant_message_event: serde_json::json!({"type": "text_delta"}),
646                event_type: "text_delta".into(),
647                content_index: Some(0),
648                delta: Some("hi".into()),
649            },
650            RemoteEvent::ToolExecutionEnd {
651                tool_call_id: "c1".into(),
652                tool_name: "read".into(),
653                is_error: true,
654                result: tool_result_json(&AgentToolResult::text("nope")),
655            },
656        ] {
657            let json = serde_json::to_value(&event).unwrap();
658            let back: RemoteEvent = serde_json::from_value(json).unwrap();
659            assert_eq!(event, back);
660        }
661    }
662
663    #[test]
664    fn command_and_response_round_trip() {
665        let cmd = RemoteCommand::Prompt {
666            content: "hi".into(),
667        };
668        let value = cmd.with_id("r1");
669        assert_eq!(value["type"], "prompt");
670        assert_eq!(value["content"], "hi");
671        assert_eq!(value["id"], "r1");
672
673        let response =
674            RemoteResponse::ok(serde_json::json!("r1"), serde_json::json!({"pong": true}));
675        let json = response.to_json();
676        assert_eq!(json["type"], "response");
677        assert_eq!(json["id"], "r1");
678        assert_eq!(json["status"], "ok");
679        let parsed: RemoteResponse = serde_json::from_value(json).unwrap();
680        assert!(parsed.is_ok());
681
682        let err = RemoteResponse::error(Value::Null, "boom").to_json();
683        assert_eq!(err["status"], "error");
684        assert_eq!(err["error"], "boom");
685    }
686}