1use chrono::{DateTime, Utc};
4use serde::{Deserialize, Serialize};
5use serde_json::Value;
6use uuid::Uuid;
7
8#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
10pub struct IpcMessage {
11 pub topic: String,
13 pub payload: IpcPayload,
15 #[serde(default)]
17 pub signature: Option<Vec<u8>>,
18 pub source_id: Uuid,
20 #[cfg_attr(feature = "clock", serde(default = "Utc::now"))]
29 #[cfg_attr(not(feature = "clock"), serde(default = "default_unix_epoch"))]
30 pub timestamp: DateTime<Utc>,
31 #[serde(default)]
34 pub seq: u64,
35 #[serde(default, skip_serializing_if = "Option::is_none")]
41 pub principal: Option<String>,
42}
43
44#[cfg(not(feature = "clock"))]
49fn default_unix_epoch() -> DateTime<Utc> {
50 DateTime::<Utc>::from_timestamp(0, 0).unwrap_or_else(|| {
51 DateTime::<Utc>::MIN_UTC
54 })
55}
56
57impl IpcMessage {
58 #[cfg(feature = "clock")]
63 #[must_use]
64 pub fn new(topic: impl Into<String>, payload: IpcPayload, source_id: Uuid) -> Self {
65 Self {
66 topic: topic.into(),
67 payload,
68 signature: None,
69 source_id,
70 timestamp: Utc::now(),
71 seq: 0,
72 principal: None,
73 }
74 }
75
76 #[must_use]
78 pub fn with_signature(mut self, signature: Vec<u8>) -> Self {
79 self.signature = Some(signature);
80 self
81 }
82
83 #[must_use]
85 pub fn with_principal(mut self, principal: impl Into<String>) -> Self {
86 self.principal = Some(principal.into());
87 self
88 }
89}
90
91fn default_session_id() -> String {
93 "default".into()
94}
95
96#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
98#[serde(tag = "type", rename_all = "snake_case")]
99pub enum IpcPayload {
100 RawJson(Value),
102 UserInput {
104 text: String,
106 #[serde(default = "default_session_id")]
108 session_id: String,
109 #[serde(default, skip_serializing_if = "Option::is_none")]
111 context: Option<Value>,
112 },
113 AgentResponse {
115 text: String,
117 is_final: bool,
119 #[serde(default = "default_session_id")]
121 session_id: String,
122 },
123 ApprovalRequired {
125 request_id: String,
127 action: String,
129 resource: String,
131 reason: String,
133 },
134 ApprovalResponse {
136 request_id: String,
138 decision: String,
140 #[serde(default, skip_serializing_if = "Option::is_none")]
142 reason: Option<String>,
143 },
144 OnboardingRequired {
146 capsule_id: String,
148 fields: Vec<OnboardingField>,
150 },
151 LlmRequest {
153 request_id: Uuid,
155 model: String,
157 messages: Vec<crate::llm::Message>,
159 tools: Vec<crate::llm::LlmToolDefinition>,
161 system: String,
163 },
164 LlmStreamEvent {
166 request_id: Uuid,
168 event: crate::llm::StreamEvent,
170 },
171 LlmResponse {
173 request_id: Uuid,
175 response: crate::llm::LlmResponse,
177 },
178 ToolExecuteRequest {
180 call_id: String,
182 tool_name: String,
184 arguments: Value,
186 },
187 ToolExecuteResult {
189 call_id: String,
191 result: crate::llm::ToolCallResult,
193 },
194 ToolCancelRequest {
196 call_ids: Vec<String>,
198 },
199 SelectionRequired {
201 request_id: String,
203 title: String,
205 options: Vec<SelectionOption>,
207 callback_topic: String,
209 },
210 ElicitRequest {
212 request_id: Uuid,
214 capsule_id: String,
216 field: OnboardingField,
218 },
219 ElicitResponse {
221 request_id: Uuid,
223 #[serde(default, skip_serializing_if = "Option::is_none")]
225 value: Option<String>,
226 #[serde(default, skip_serializing_if = "Option::is_none")]
228 values: Option<Vec<String>>,
229 },
230 Connect,
232 Disconnect {
234 #[serde(default, skip_serializing_if = "Option::is_none")]
236 reason: Option<String>,
237 },
238 Custom {
240 data: Value,
242 },
243 #[serde(other)]
245 Unknown,
246}
247
248impl IpcPayload {
249 #[must_use]
251 pub fn is_known_tag(tag: &str) -> bool {
252 matches!(
253 tag,
254 "raw_json"
255 | "user_input"
256 | "agent_response"
257 | "approval_required"
258 | "approval_response"
259 | "onboarding_required"
260 | "llm_request"
261 | "llm_stream_event"
262 | "llm_response"
263 | "tool_execute_request"
264 | "tool_execute_result"
265 | "tool_cancel_request"
266 | "selection_required"
267 | "elicit_request"
268 | "elicit_response"
269 | "connect"
270 | "disconnect"
271 | "custom"
272 )
273 }
274
275 pub fn from_json_value(data: Value) -> Self {
278 let is_known = data
279 .get("type")
280 .and_then(|v| v.as_str())
281 .is_some_and(Self::is_known_tag);
282
283 if is_known {
284 serde_json::from_value::<Self>(data.clone()).unwrap_or(Self::Custom { data })
285 } else {
286 Self::Custom { data }
287 }
288 }
289
290 pub fn to_guest_bytes(&self) -> Result<Vec<u8>, serde_json::Error> {
300 match self {
301 Self::Custom { data } | Self::RawJson(data) => serde_json::to_vec(data),
302 other => serde_json::to_vec(other),
303 }
304 }
305}
306
307#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
309pub struct SelectionOption {
310 pub id: String,
312 pub label: String,
314 #[serde(default, skip_serializing_if = "Option::is_none")]
316 pub description: Option<String>,
317}
318
319#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
321pub struct OnboardingField {
322 pub key: String,
324 pub prompt: String,
326 #[serde(default, skip_serializing_if = "Option::is_none")]
328 pub description: Option<String>,
329 pub field_type: OnboardingFieldType,
331 #[serde(default, skip_serializing_if = "Option::is_none")]
333 pub default: Option<String>,
334 #[serde(default, skip_serializing_if = "Option::is_none")]
336 pub placeholder: Option<String>,
337}
338
339#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
341pub enum OnboardingFieldType {
342 Text,
344 Secret,
346 Enum(Vec<String>),
348 Array,
350}
351
352#[cfg(test)]
353mod tests {
354 use super::*;
355
356 #[test]
357 fn ipc_message_signature() {
358 let msg = IpcMessage::new(
359 "test.topic",
360 IpcPayload::AgentResponse {
361 text: "hello".into(),
362 is_final: true,
363 session_id: "default".into(),
364 },
365 Uuid::new_v4(),
366 );
367 assert!(msg.signature.is_none());
368
369 let signed = msg.with_signature(vec![1, 2, 3]);
370 assert_eq!(signed.signature, Some(vec![1, 2, 3]));
371 }
372
373 #[test]
374 fn ipc_message_principal() {
375 let msg = IpcMessage::new(
376 "test.topic",
377 IpcPayload::Custom {
378 data: serde_json::json!({}),
379 },
380 Uuid::new_v4(),
381 );
382 assert!(msg.principal.is_none());
383
384 let with_principal = msg.with_principal("alice");
385 assert_eq!(with_principal.principal.as_deref(), Some("alice"));
386 }
387
388 #[test]
389 fn ipc_message_principal_serde_roundtrip() {
390 let msg = IpcMessage::new(
391 "test.topic",
392 IpcPayload::Custom {
393 data: serde_json::json!({}),
394 },
395 Uuid::nil(),
396 )
397 .with_principal("bob");
398 let json = serde_json::to_string(&msg).unwrap();
399 assert!(json.contains(r#""principal":"bob""#));
400
401 let parsed: IpcMessage = serde_json::from_str(&json).unwrap();
402 assert_eq!(parsed.principal.as_deref(), Some("bob"));
403 }
404
405 #[test]
406 fn ipc_message_principal_absent_in_json() {
407 let json = r#"{"topic":"t","payload":{"type":"connect"},"source_id":"00000000-0000-0000-0000-000000000000","timestamp":"2024-01-01T00:00:00Z","seq":0}"#;
409 let msg: IpcMessage = serde_json::from_str(json).unwrap();
410 assert!(msg.principal.is_none());
411 }
412
413 #[test]
414 fn ipc_message_principal_not_serialized_when_none() {
415 let msg = IpcMessage::new("test.topic", IpcPayload::Connect, Uuid::nil());
416 let json = serde_json::to_string(&msg).unwrap();
417 assert!(!json.contains("principal"));
418 }
419
420 #[test]
421 fn unknown_type_tag_deserializes_to_unknown() {
422 let json = r#"{"type":"future_variant","some_data":42}"#;
423 let payload: IpcPayload = serde_json::from_str(json).unwrap();
424 assert_eq!(payload, IpcPayload::Unknown);
425 }
426
427 #[test]
428 fn ipc_message_parses_cli_proxy_wire_format() {
429 let wire = r#"{"topic":"agent.v1.response","payload":{"type":"agent_response","text":"hi","is_final":true,"session_id":"00000000-0000-0000-0000-000000000000"},"source_id":"00000000-0000-0000-0000-000000000000"}"#;
437 let msg: IpcMessage = serde_json::from_str(wire).expect("cli proxy frame must parse");
438 assert_eq!(msg.topic, "agent.v1.response");
439 assert!(msg.signature.is_none());
440 assert_eq!(msg.seq, 0);
441 match msg.payload {
442 IpcPayload::AgentResponse { text, is_final, .. } => {
443 assert_eq!(text, "hi");
444 assert!(is_final);
445 },
446 other => panic!("unexpected payload variant: {other:?}"),
447 }
448 }
449
450 #[test]
451 fn known_variants_unaffected_by_unknown() {
452 let payload = IpcPayload::AgentResponse {
453 text: "hello".into(),
454 is_final: true,
455 session_id: "s1".into(),
456 };
457 let json = serde_json::to_string(&payload).unwrap();
458 let parsed: IpcPayload = serde_json::from_str(&json).unwrap();
459 assert_eq!(parsed, payload);
460 }
461
462 #[test]
463 fn unknown_variant_serializes_as_type_unknown() {
464 let json = serde_json::to_string(&IpcPayload::Unknown).unwrap();
465 assert_eq!(json, r#"{"type":"unknown"}"#);
466 }
467
468 #[test]
472 fn is_known_tag_covers_all_variants() {
473 const EXPECTED_VARIANT_COUNT: usize = 17;
474
475 let representatives: Vec<IpcPayload> = vec![
476 IpcPayload::RawJson(serde_json::json!({"key": "val"})),
477 IpcPayload::UserInput {
478 text: String::new(),
479 session_id: "s".into(),
480 context: None,
481 },
482 IpcPayload::AgentResponse {
483 text: String::new(),
484 is_final: false,
485 session_id: "s".into(),
486 },
487 IpcPayload::ApprovalRequired {
488 request_id: "req-1".into(),
489 action: String::new(),
490 resource: String::new(),
491 reason: String::new(),
492 },
493 IpcPayload::ApprovalResponse {
494 request_id: "req-1".into(),
495 decision: "approve".into(),
496 reason: None,
497 },
498 IpcPayload::OnboardingRequired {
499 capsule_id: String::new(),
500 fields: vec![],
501 },
502 IpcPayload::LlmRequest {
503 request_id: Uuid::nil(),
504 model: String::new(),
505 messages: vec![],
506 tools: vec![],
507 system: String::new(),
508 },
509 IpcPayload::LlmStreamEvent {
510 request_id: Uuid::nil(),
511 event: crate::llm::StreamEvent::TextDelta(String::new()),
512 },
513 IpcPayload::LlmResponse {
514 request_id: Uuid::nil(),
515 response: crate::llm::LlmResponse {
516 message: crate::llm::Message {
517 role: crate::llm::MessageRole::Assistant,
518 content: crate::llm::MessageContent::Text(String::new()),
519 },
520 has_tool_calls: false,
521 stop_reason: crate::llm::StopReason::EndTurn,
522 usage: crate::llm::Usage {
523 input_tokens: 0,
524 output_tokens: 0,
525 },
526 },
527 },
528 IpcPayload::ToolExecuteRequest {
529 call_id: String::new(),
530 tool_name: String::new(),
531 arguments: Value::Null,
532 },
533 IpcPayload::ToolExecuteResult {
534 call_id: String::new(),
535 result: crate::llm::ToolCallResult {
536 call_id: String::new(),
537 content: String::new(),
538 is_error: false,
539 },
540 },
541 IpcPayload::SelectionRequired {
542 request_id: String::new(),
543 title: String::new(),
544 options: vec![],
545 callback_topic: String::new(),
546 },
547 IpcPayload::ElicitRequest {
548 request_id: Uuid::nil(),
549 capsule_id: String::new(),
550 field: OnboardingField {
551 key: String::new(),
552 prompt: String::new(),
553 description: None,
554 field_type: OnboardingFieldType::Text,
555 default: None,
556 placeholder: None,
557 },
558 },
559 IpcPayload::ElicitResponse {
560 request_id: Uuid::nil(),
561 value: None,
562 values: None,
563 },
564 IpcPayload::Connect,
565 IpcPayload::Disconnect { reason: None },
566 IpcPayload::Custom {
567 data: Value::Object(serde_json::Map::new()),
568 },
569 ];
570
571 assert_eq!(
572 representatives.len(),
573 EXPECTED_VARIANT_COUNT,
574 "IpcPayload variant count changed. Update the representatives list \
575 and bump EXPECTED_VARIANT_COUNT."
576 );
577
578 for variant in &representatives {
579 let json = serde_json::to_value(variant).unwrap();
580 let tag = json["type"]
581 .as_str()
582 .unwrap_or_else(|| panic!("variant {variant:?} has no `type` tag"));
583 assert!(
584 IpcPayload::is_known_tag(tag),
585 "is_known_tag does not recognise tag '{tag}' from variant {variant:?}"
586 );
587 }
588 }
589
590 #[test]
591 fn is_known_tag_rejects_unknown_tags() {
592 assert!(!IpcPayload::is_known_tag("my_plugin_msg"));
593 assert!(!IpcPayload::is_known_tag("unknown"));
594 assert!(!IpcPayload::is_known_tag(""));
595 assert!(!IpcPayload::is_known_tag("Raw_Json"));
596 }
597
598 #[test]
599 fn onboarding_field_roundtrip() {
600 let field = OnboardingField {
601 key: "apiKey".into(),
602 prompt: "Enter API key".into(),
603 description: None,
604 field_type: OnboardingFieldType::Secret,
605 default: None,
606 placeholder: None,
607 };
608 let json = serde_json::to_string(&field).unwrap();
609 let parsed: OnboardingField = serde_json::from_str(&json).unwrap();
610 assert_eq!(parsed, field);
611 }
612
613 #[test]
614 fn onboarding_field_roundtrip_array() {
615 let field = OnboardingField {
616 key: "relays".into(),
617 prompt: "Enter relay URLs".into(),
618 description: Some("Nostr relay endpoints".into()),
619 field_type: OnboardingFieldType::Array,
620 default: None,
621 placeholder: None,
622 };
623 let json = serde_json::to_string(&field).unwrap();
624 let parsed: OnboardingField = serde_json::from_str(&json).unwrap();
625 assert_eq!(parsed, field);
626 }
627
628 #[test]
629 fn onboarding_required_payload_roundtrip() {
630 let payload = IpcPayload::OnboardingRequired {
631 capsule_id: "test-capsule".into(),
632 fields: vec![
633 OnboardingField {
634 key: "network".into(),
635 prompt: "Select network".into(),
636 description: Some("Choose the target network".into()),
637 field_type: OnboardingFieldType::Enum(vec!["testnet".into(), "mainnet".into()]),
638 default: Some("testnet".into()),
639 placeholder: None,
640 },
641 OnboardingField {
642 key: "apiKey".into(),
643 prompt: "Enter API key".into(),
644 description: None,
645 field_type: OnboardingFieldType::Secret,
646 default: None,
647 placeholder: None,
648 },
649 ],
650 };
651 let json = serde_json::to_string(&payload).unwrap();
652 let parsed: IpcPayload = serde_json::from_str(&json).unwrap();
653 assert_eq!(parsed, payload);
654 }
655
656 #[test]
657 fn elicit_request_roundtrip() {
658 let payload = IpcPayload::ElicitRequest {
659 request_id: Uuid::nil(),
660 capsule_id: "my-capsule".into(),
661 field: OnboardingField {
662 key: "api_url".into(),
663 prompt: "Enter API URL".into(),
664 description: Some("The backend endpoint".into()),
665 field_type: OnboardingFieldType::Text,
666 default: Some("https://example.com".into()),
667 placeholder: None,
668 },
669 };
670 let json = serde_json::to_string(&payload).unwrap();
671 let parsed: IpcPayload = serde_json::from_str(&json).unwrap();
672 assert_eq!(parsed, payload);
673 }
674
675 #[test]
676 fn elicit_response_roundtrip() {
677 let payload = IpcPayload::ElicitResponse {
678 request_id: Uuid::nil(),
679 value: Some("hello".into()),
680 values: None,
681 };
682 let json = serde_json::to_string(&payload).unwrap();
683 let parsed: IpcPayload = serde_json::from_str(&json).unwrap();
684 assert_eq!(parsed, payload);
685 }
686
687 #[test]
688 fn disconnect_with_reason_roundtrip() {
689 let payload = IpcPayload::Disconnect {
690 reason: Some("quit".into()),
691 };
692 let json = serde_json::to_string(&payload).unwrap();
693 let parsed: IpcPayload = serde_json::from_str(&json).unwrap();
694 assert_eq!(parsed, payload);
695 assert!(json.contains(r#""type":"disconnect""#), "json: {json}");
696 }
697
698 #[test]
699 fn disconnect_without_reason_roundtrip() {
700 let payload = IpcPayload::Disconnect { reason: None };
701 let json = serde_json::to_string(&payload).unwrap();
702 let parsed: IpcPayload = serde_json::from_str(&json).unwrap();
703 assert_eq!(parsed, payload);
704 assert!(!json.contains("reason"), "json: {json}");
705 }
706
707 #[test]
708 fn to_guest_bytes_custom_returns_inner_data() {
709 let data = serde_json::json!({"session_id": "abc", "messages": []});
710 let payload = IpcPayload::Custom { data: data.clone() };
711 let bytes = payload.to_guest_bytes().unwrap();
712 let roundtrip: Value = serde_json::from_slice(&bytes).unwrap();
713 assert_eq!(roundtrip, data);
714 assert!(roundtrip.get("type").is_none());
715 }
716
717 #[test]
718 fn to_guest_bytes_structured_preserves_type_tag() {
719 let payload = IpcPayload::UserInput {
720 text: "hello".into(),
721 session_id: "default".into(),
722 context: None,
723 };
724 let bytes = payload.to_guest_bytes().unwrap();
725 let roundtrip: Value = serde_json::from_slice(&bytes).unwrap();
726 assert_eq!(
727 roundtrip.get("type").and_then(|v| v.as_str()),
728 Some("user_input")
729 );
730 }
731
732 #[test]
733 fn to_guest_bytes_raw_json_unwraps() {
734 let inner = serde_json::json!({"key": "value"});
735 let payload = IpcPayload::RawJson(inner.clone());
736 let bytes = payload.to_guest_bytes().unwrap();
737 let roundtrip: Value = serde_json::from_slice(&bytes).unwrap();
738 assert_eq!(roundtrip, inner);
739 assert!(roundtrip.get("type").is_none());
740 }
741
742 #[test]
743 fn to_guest_bytes_connect_unit_variant() {
744 let payload = IpcPayload::Connect;
745 let bytes = payload.to_guest_bytes().unwrap();
746 let roundtrip: Value = serde_json::from_slice(&bytes).unwrap();
747 assert_eq!(
748 roundtrip.get("type").and_then(|v| v.as_str()),
749 Some("connect")
750 );
751 }
752
753 #[test]
754 fn from_json_value_unknown_tag_becomes_custom() {
755 let data = serde_json::json!({"type": "my_plugin_msg", "foo": 42});
756 let payload = IpcPayload::from_json_value(data.clone());
757 assert_eq!(payload, IpcPayload::Custom { data });
758 }
759
760 #[test]
761 fn from_json_value_known_tag_parses() {
762 let data = serde_json::json!({
763 "type": "user_input",
764 "text": "hi",
765 "session_id": "s1"
766 });
767 let payload = IpcPayload::from_json_value(data);
768 assert!(matches!(payload, IpcPayload::UserInput { .. }));
769 }
770}