1use std::{collections::BTreeMap, sync::Arc};
7
8use derive_more::{Display, From};
9#[cfg(feature = "schemars")]
10use schemars::Schema;
11use serde::{Deserialize, Serialize};
12use serde_with::{DefaultOnError, VecSkipError, serde_as, skip_serializing_none};
13
14#[cfg(feature = "unstable_auth_status")]
15use super::AuthStatusUpdateNotification;
16#[cfg(feature = "unstable_plan_operations")]
17use super::PlanRemoved;
18#[cfg(feature = "unstable_end_turn_token_usage")]
19use super::Usage;
20use super::{
21 AbsolutePath, ContentBlock, ExtNotification, ExtRequest, ExtResponse, Meta, PlanUpdate,
22 SessionConfigOption, SessionId, StopReason, TerminalId, TerminalOutputChunk, TerminalUpdate,
23 ToolCallContentChunk, ToolCallId, ToolCallUpdate,
24};
25use super::{
26 CompleteElicitationNotification, CreateElicitationRequest, CreateElicitationResponse,
27 ElicitationCapabilities,
28};
29use crate::{IntoMaybeUndefined, IntoOption, MaybeUndefined};
30
31#[cfg(feature = "unstable_mcp_over_acp")]
32use super::mcp::{MCP_MESSAGE_METHOD_NAME, MessageMcpRequest, MessageMcpResponse};
33
34#[serde_as]
42#[skip_serializing_none]
43#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
44#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
45#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = SESSION_UPDATE_NOTIFICATION)))]
46#[serde(rename_all = "camelCase")]
47#[non_exhaustive]
48pub struct UpdateSessionNotification {
49 pub session_id: SessionId,
51 pub update: SessionUpdate,
53 #[serde_as(deserialize_as = "DefaultOnError")]
59 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
60 #[serde(default)]
61 #[serde(rename = "_meta")]
62 pub meta: Option<Meta>,
63}
64
65impl UpdateSessionNotification {
66 #[must_use]
68 pub fn new(session_id: impl Into<SessionId>, update: SessionUpdate) -> Self {
69 Self {
70 session_id: session_id.into(),
71 update,
72 meta: None,
73 }
74 }
75
76 #[must_use]
82 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
83 self.meta = meta.into_option();
84 self
85 }
86}
87
88#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
94#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
95#[serde(tag = "sessionUpdate", rename_all = "snake_case")]
96#[non_exhaustive]
97pub enum SessionUpdate {
98 UserMessageChunk(ContentChunk),
100 UserMessage(UserMessage),
106 AgentMessageChunk(ContentChunk),
108 AgentMessage(AgentMessage),
114 AgentThoughtChunk(ContentChunk),
116 AgentThought(AgentThought),
122 StateUpdate(StateUpdate),
124 ToolCallContentChunk(ToolCallContentChunk),
126 ToolCallUpdate(ToolCallUpdate),
128 TerminalUpdate(TerminalUpdate),
130 TerminalOutputChunk(TerminalOutputChunk),
132 PlanUpdate(PlanUpdate),
135 #[cfg(feature = "unstable_plan_operations")]
141 PlanRemoved(PlanRemoved),
142 AvailableCommandsUpdate(AvailableCommandsUpdate),
144 ConfigOptionUpdate(ConfigOptionUpdate),
146 SessionInfoUpdate(SessionInfoUpdate),
148 UsageUpdate(UsageUpdate),
150 Notice(Notice),
155 CompactionUpdate(CompactionUpdate),
157 CompactionSummaryChunk(CompactionSummaryChunk),
159 ReplayComplete(ReplayComplete),
164 #[cfg(feature = "unstable_prompt_suggestions")]
173 PromptSuggestionsUpdate(PromptSuggestionsUpdate),
174 SubagentUpdate(SubagentUpdate),
177 SessionMessage(SessionMessage),
180 SessionMessageChunk(SessionMessageChunk),
182 #[serde(untagged)]
192 Other(OtherSessionUpdate),
193}
194
195#[serde_as]
200#[skip_serializing_none]
201#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
202#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
203#[serde(rename_all = "camelCase")]
204#[non_exhaustive]
205pub struct SessionMessageChunk {
206 pub message_id: MessageId,
208 pub content: ContentBlock,
210 #[serde_as(deserialize_as = "DefaultOnError")]
217 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
218 #[serde(default, rename = "_meta")]
219 pub meta: Option<Meta>,
220}
221
222impl SessionMessageChunk {
223 #[must_use]
225 pub fn new(message_id: impl Into<MessageId>, content: ContentBlock) -> Self {
226 Self {
227 message_id: message_id.into(),
228 content,
229 meta: None,
230 }
231 }
232
233 #[must_use]
235 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
236 self.meta = meta.into_option();
237 self
238 }
239}
240
241#[serde_as]
243#[skip_serializing_none]
244#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
245#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
246#[serde(rename_all = "camelCase")]
247#[non_exhaustive]
248pub struct SessionMessage {
249 pub message_id: MessageId,
251 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
255 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
256 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
257 pub sender_session_id: MaybeUndefined<SessionId>,
258 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
262 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
263 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
264 pub recipient_session_id: MaybeUndefined<SessionId>,
265 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
271 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
272 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
273 pub sender_message_id: MaybeUndefined<MessageId>,
274 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
280 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
281 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
282 pub recipient_message_id: MaybeUndefined<MessageId>,
283 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<VecSkipError<_>>>")]
286 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
287 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
288 pub content: MaybeUndefined<Vec<ContentBlock>>,
289 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
298 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
299 #[serde(
300 default,
301 rename = "_meta",
302 skip_serializing_if = "MaybeUndefined::is_undefined"
303 )]
304 pub meta: MaybeUndefined<Meta>,
305}
306
307impl SessionMessage {
308 #[must_use]
310 pub fn new(message_id: impl Into<MessageId>) -> Self {
311 Self {
312 message_id: message_id.into(),
313 sender_session_id: MaybeUndefined::Undefined,
314 recipient_session_id: MaybeUndefined::Undefined,
315 sender_message_id: MaybeUndefined::Undefined,
316 recipient_message_id: MaybeUndefined::Undefined,
317 content: MaybeUndefined::Undefined,
318 meta: MaybeUndefined::Undefined,
319 }
320 }
321
322 #[must_use]
324 pub fn sender_session_id(
325 mut self,
326 sender_session_id: impl IntoMaybeUndefined<SessionId>,
327 ) -> Self {
328 self.sender_session_id = sender_session_id.into_maybe_undefined();
329 self
330 }
331
332 #[must_use]
334 pub fn recipient_session_id(
335 mut self,
336 recipient_session_id: impl IntoMaybeUndefined<SessionId>,
337 ) -> Self {
338 self.recipient_session_id = recipient_session_id.into_maybe_undefined();
339 self
340 }
341
342 #[must_use]
344 pub fn sender_message_id(
345 mut self,
346 sender_message_id: impl IntoMaybeUndefined<MessageId>,
347 ) -> Self {
348 self.sender_message_id = sender_message_id.into_maybe_undefined();
349 self
350 }
351
352 #[must_use]
354 pub fn recipient_message_id(
355 mut self,
356 recipient_message_id: impl IntoMaybeUndefined<MessageId>,
357 ) -> Self {
358 self.recipient_message_id = recipient_message_id.into_maybe_undefined();
359 self
360 }
361
362 #[must_use]
364 pub fn content(mut self, content: impl IntoMaybeUndefined<Vec<ContentBlock>>) -> Self {
365 self.content = content.into_maybe_undefined();
366 self
367 }
368
369 #[must_use]
374 pub fn meta(mut self, meta: impl IntoMaybeUndefined<Meta>) -> Self {
375 self.meta = meta.into_maybe_undefined();
376 self
377 }
378}
379
380#[cfg(test)]
381mod session_message_tests {
382 use super::*;
383 use serde_json::{Value, json};
384
385 #[test]
386 fn transcript_envelopes_and_multimodal_content() {
387 for (transcript, sender, recipient, id) in [
388 ("parent", "parent", "child", "sent-1"),
389 ("child", "parent", "child", "received-9"),
390 ("child", "child", "parent", "sent-2"),
391 ] {
392 let wire = json!({"sessionId": transcript, "update": {
393 "sessionUpdate": "session_message", "messageId": id,
394 "senderSessionId": sender, "recipientSessionId": recipient, "content": [
395 {"type": "text", "text": "hello"},
396 {"type": "image", "data": "aGVsbG8=", "mimeType": "image/png"}
397 ]
398 }});
399 let decoded: UpdateSessionNotification = serde_json::from_value(wire.clone()).unwrap();
400 assert_eq!(serde_json::to_value(decoded).unwrap(), wire);
401 }
402 }
403
404 #[test]
405 fn chunks_and_upserts_share_transcript_local_identity() {
406 for (transcript, id) in [("parent", "sent-1"), ("child", "received-9")] {
407 let wire = json!({"sessionId": transcript, "update": {
408 "sessionUpdate": "session_message_chunk", "messageId": id,
409 "content": {"type": "text", "text": "hello"}
410 }});
411 let decoded: UpdateSessionNotification = serde_json::from_value(wire.clone()).unwrap();
412 assert_eq!(serde_json::to_value(decoded).unwrap(), wire);
413 let upsert = SessionMessage::new(id)
414 .sender_session_id(SessionId::new("parent"))
415 .recipient_session_id(SessionId::new("child"))
416 .content(vec![]);
417 let chunk = SessionMessageChunk::new(
418 id,
419 ContentBlock::Text(crate::v2::TextContent::new("hello")),
420 );
421 assert_eq!(chunk.message_id, upsert.message_id);
422 assert_eq!(
423 serde_json::to_value(SessionUpdate::SessionMessageChunk(chunk)).unwrap(),
424 wire["update"]
425 );
426 assert_eq!(serde_json::to_value(upsert).unwrap()["content"], json!([]));
427 }
428 let with_identity = json!({"sessionUpdate": "session_message_chunk", "messageId": "m1",
430 "senderSessionId": "parent", "recipientSessionId": "child",
431 "senderMessageId": "sent-1", "recipientMessageId": "received-1",
432 "content": {"type": "text", "text": "hello"}});
433 let decoded: SessionUpdate = serde_json::from_value(with_identity).unwrap();
434 assert_eq!(
435 serde_json::to_value(decoded).unwrap(),
436 json!({"sessionUpdate": "session_message_chunk", "messageId": "m1",
437 "content": {"type": "text", "text": "hello"}})
438 );
439 }
440
441 #[test]
442 fn required_ids_and_chunk_content_with_upsert_patch_semantics() {
443 for (kind, content) in [
444 ("session_message", json!([])),
445 (
446 "session_message_chunk",
447 json!({"type": "text", "text": "hello"}),
448 ),
449 ] {
450 let mut base = json!({"sessionUpdate": kind, "messageId": "m1", "content": content});
451 if kind == "session_message" {
452 base["senderSessionId"] = json!("parent");
453 base["recipientSessionId"] = json!("child");
454 }
455 {
456 let key = "messageId";
457 let mut missing = base.clone();
458 missing.as_object_mut().unwrap().remove(key);
459 assert!(
460 serde_json::from_value::<SessionUpdate>(missing).is_err(),
461 "{kind} {key}"
462 );
463 let mut null = base.clone();
464 null[key] = Value::Null;
465 assert!(
466 serde_json::from_value::<SessionUpdate>(null).is_err(),
467 "{kind} {key}"
468 );
469 let mut non_string = base.clone();
470 non_string[key] = json!(42);
471 assert!(
472 serde_json::from_value::<SessionUpdate>(non_string).is_err(),
473 "{kind} {key}"
474 );
475 }
476 if kind == "session_message_chunk" {
477 for content in [None, Some(Value::Null), Some(json!([]))] {
478 let mut invalid = base.clone();
479 invalid.as_object_mut().unwrap().remove("content");
480 if let Some(content) = content {
481 invalid["content"] = content;
482 }
483 assert!(serde_json::from_value::<SessionUpdate>(invalid).is_err());
484 }
485 } else {
486 for content in [None, Some(Value::Null), Some(json!([])), Some(json!({}))] {
487 let mut wire = base.clone();
488 wire.as_object_mut().unwrap().remove("content");
489 if let Some(content) = content {
490 wire["content"] = content;
491 }
492 let decoded: SessionUpdate = serde_json::from_value(wire.clone()).unwrap();
493 let encoded = serde_json::to_value(decoded).unwrap();
494 if wire["content"].is_object() {
495 wire.as_object_mut().unwrap().remove("content");
496 }
497 assert_eq!(encoded, wire);
498 }
499 }
500 for meta in [None, Some(Value::Null), Some(json!({"tag": "value"}))] {
501 let mut wire = base.clone();
502 if let Some(meta) = meta {
503 wire["_meta"] = meta;
504 }
505 let decoded: SessionUpdate = serde_json::from_value(wire.clone()).unwrap();
506 let encoded = serde_json::to_value(decoded).unwrap();
507 if kind == "session_message" {
508 assert_eq!(encoded, wire);
509 } else if wire["_meta"].is_null() {
510 assert_eq!(encoded, base);
511 } else {
512 assert_eq!(encoded, wire);
513 }
514 }
515 }
516 let metadata_only = json!({"sessionUpdate": "session_message",
517 "messageId": "m1", "senderSessionId": "parent",
518 "recipientSessionId": "child", "_meta": {"tag": "value"}});
519 let decoded: SessionUpdate = serde_json::from_value(metadata_only.clone()).unwrap();
520 assert_eq!(serde_json::to_value(decoded).unwrap(), metadata_only);
521 let cleared = SessionMessage::new("m1")
522 .sender_session_id(SessionId::new("parent"))
523 .recipient_session_id(SessionId::new("child"))
524 .content(None)
525 .meta(None);
526 assert_eq!(
527 serde_json::to_value(cleared).unwrap(),
528 json!({"messageId": "m1", "senderSessionId": "parent",
529 "recipientSessionId": "child", "content": null, "_meta": null})
530 );
531 }
532
533 #[cfg(feature = "schemars")]
534 #[test]
535 fn schemas_require_ids_and_chunk_content_but_not_upsert_content() {
536 let upsert = serde_json::to_value(schemars::schema_for!(SessionMessage)).unwrap();
537 let required = upsert["required"].as_array().unwrap();
538 assert_eq!(required, &vec![json!("messageId")]);
539 let chunk = serde_json::to_value(schemars::schema_for!(SessionMessageChunk)).unwrap();
540 let required = chunk["required"].as_array().unwrap();
541 assert_eq!(required.len(), 2);
542 assert!(required.contains(&json!("messageId")));
543 assert!(required.contains(&json!("content")));
544 }
545
546 #[test]
547 fn endpoints_can_arrive_late_or_be_omitted_from_later_events() {
548 let block = ContentBlock::Text(crate::v2::TextContent::new("hello"));
549 let minimal = SessionMessage::new("m1");
550 let first = SessionMessageChunk::new("m1", block.clone());
551 assert_eq!(
552 serde_json::to_value(&minimal).unwrap(),
553 json!({"messageId": "m1"})
554 );
555 assert_eq!(
556 serde_json::to_value(&first).unwrap(),
557 json!({"messageId": "m1", "content": {"type": "text", "text": "hello"}})
558 );
559 let enriched = SessionMessage::new("m1")
560 .sender_session_id(SessionId::new("parent"))
561 .recipient_session_id(SessionId::new("child"));
562 assert_eq!(
563 enriched.sender_session_id,
564 MaybeUndefined::Value(SessionId::new("parent"))
565 );
566 assert_eq!(
567 enriched.recipient_session_id,
568 MaybeUndefined::Value(SessionId::new("child"))
569 );
570 let later = SessionMessage::new("m1").sender_session_id(SessionId::new("parent"));
571 assert_eq!(
572 later.sender_session_id,
573 MaybeUndefined::Value(SessionId::new("parent"))
574 );
575 assert_eq!(later.recipient_session_id, MaybeUndefined::Undefined);
576 let more = SessionMessageChunk::new("m1", block);
577 for update in [
578 SessionUpdate::SessionMessage(minimal),
579 SessionUpdate::SessionMessageChunk(first),
580 SessionUpdate::SessionMessage(enriched),
581 SessionUpdate::SessionMessage(later),
582 SessionUpdate::SessionMessageChunk(more),
583 ] {
584 let wire = serde_json::to_value(&update).unwrap();
585 let decoded: SessionUpdate = serde_json::from_value(wire.clone()).unwrap();
586 assert_eq!(serde_json::to_value(decoded).unwrap(), wire);
587 }
588 }
589
590 #[test]
591 fn null_endpoints_clear_invalid_are_absent_but_message_id_is_required() {
592 let mut base = json!({"sessionUpdate": "session_message", "messageId": "m1",
593 "senderSessionId": null, "recipientSessionId": 42});
594 let decoded: SessionUpdate = serde_json::from_value(base.clone()).unwrap();
595 let encoded = serde_json::to_value(decoded).unwrap();
596 base.as_object_mut().unwrap().remove("recipientSessionId");
597 assert_eq!(encoded, base);
598 for bad in [Value::Null, json!(42)] {
599 let mut invalid = base.clone();
600 invalid["messageId"] = bad;
601 assert!(serde_json::from_value::<SessionUpdate>(invalid).is_err());
602 }
603 }
604
605 #[test]
606 fn message_references_link_views_and_can_arrive_late() {
607 let block = ContentBlock::Text(crate::v2::TextContent::new("hello"));
608 let incoming = SessionMessage::new("received-1")
609 .sender_session_id(SessionId::new("parent"))
610 .recipient_session_id(SessionId::new("child"))
611 .sender_message_id(MessageId::new("sent-1"))
612 .content(vec![block]);
613 let outgoing =
615 SessionMessage::new("sent-1").recipient_message_id(MessageId::new("received-1"));
616 for (update, wire) in [
617 (
618 SessionUpdate::SessionMessage(incoming),
619 json!({"sessionUpdate": "session_message", "messageId": "received-1",
620 "senderSessionId": "parent", "recipientSessionId": "child",
621 "senderMessageId": "sent-1", "content": [{"type": "text", "text": "hello"}]}),
622 ),
623 (
624 SessionUpdate::SessionMessage(outgoing),
625 json!({"sessionUpdate": "session_message", "messageId": "sent-1",
626 "recipientMessageId": "received-1"}),
627 ),
628 ] {
629 assert_eq!(serde_json::to_value(&update).unwrap(), wire);
630 let decoded: SessionUpdate = serde_json::from_value(wire.clone()).unwrap();
631 assert_eq!(decoded, update);
632 }
633
634 let mut wire = json!({"sessionUpdate": "session_message", "messageId": "m1",
635 "senderMessageId": null, "recipientMessageId": 42});
636 let decoded: SessionUpdate = serde_json::from_value(wire.clone()).unwrap();
637 wire.as_object_mut().unwrap().remove("recipientMessageId");
638 assert_eq!(
639 serde_json::to_value(decoded).unwrap(),
640 wire,
641 "null clears a reference and a malformed one is not supplied"
642 );
643 }
644}
645
646#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
648#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
649#[serde(rename_all = "snake_case")]
650#[non_exhaustive]
651pub enum NoticeSeverity {
652 Info,
654 Warning,
656 Error,
658 #[serde(untagged)]
663 Other(String),
664}
665
666#[serde_as]
674#[skip_serializing_none]
675#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
676#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
677#[serde(rename_all = "camelCase")]
678#[non_exhaustive]
679pub struct Notice {
680 pub severity: NoticeSeverity,
682 #[cfg_attr(feature = "schemars", schemars(length(min = 1)))]
684 pub title: String,
685 #[serde_as(deserialize_as = "DefaultOnError")]
689 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
690 #[serde(default)]
691 pub description: Option<String>,
692 #[serde_as(deserialize_as = "DefaultOnError")]
698 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
699 #[serde(default, rename = "_meta")]
700 pub meta: Option<Meta>,
701}
702
703impl Notice {
704 #[must_use]
706 pub fn new(severity: NoticeSeverity, title: impl Into<String>) -> Self {
707 Self {
708 severity,
709 title: title.into(),
710 description: None,
711 meta: None,
712 }
713 }
714
715 #[must_use]
717 pub fn description(mut self, description: impl IntoOption<String>) -> Self {
718 self.description = description.into_option();
719 self
720 }
721
722 #[must_use]
724 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
725 self.meta = meta.into_option();
726 self
727 }
728}
729
730#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
732#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
733#[serde(transparent)]
734#[from(forward)]
735#[non_exhaustive]
736pub struct CompactionId(pub Arc<str>);
737
738impl CompactionId {
739 #[must_use]
741 pub fn new(id: impl Into<Self>) -> Self {
742 id.into()
743 }
744}
745
746#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
748#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
749#[serde(rename_all = "snake_case")]
750#[non_exhaustive]
751pub enum CompactionStatus {
752 #[default]
754 InProgress,
755 Completed,
757 Failed,
759 Cancelled,
761 #[serde(untagged)]
766 Other(String),
767}
768
769#[serde_as]
777#[skip_serializing_none]
778#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
779#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
780#[serde(rename_all = "camelCase")]
781#[non_exhaustive]
782pub struct CompactionUpdate {
783 pub compaction_id: CompactionId,
785 pub status: CompactionStatus,
787 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<VecSkipError<_>>>")]
789 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
790 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
791 pub summary: MaybeUndefined<Vec<ContentBlock>>,
792 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
794 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
795 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
796 pub error: MaybeUndefined<String>,
797 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
806 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
807 #[serde(
808 rename = "_meta",
809 default,
810 skip_serializing_if = "MaybeUndefined::is_undefined"
811 )]
812 pub meta: MaybeUndefined<Meta>,
813}
814
815impl CompactionUpdate {
816 #[must_use]
818 pub fn new(compaction_id: impl Into<CompactionId>, status: CompactionStatus) -> Self {
819 Self {
820 compaction_id: compaction_id.into(),
821 status,
822 summary: MaybeUndefined::Undefined,
823 error: MaybeUndefined::Undefined,
824 meta: MaybeUndefined::Undefined,
825 }
826 }
827
828 #[must_use]
830 pub fn summary(mut self, summary: impl IntoMaybeUndefined<Vec<ContentBlock>>) -> Self {
831 self.summary = summary.into_maybe_undefined();
832 self
833 }
834
835 #[must_use]
837 pub fn error(mut self, error: impl IntoMaybeUndefined<String>) -> Self {
838 self.error = error.into_maybe_undefined();
839 self
840 }
841
842 #[must_use]
847 pub fn meta(mut self, meta: impl IntoMaybeUndefined<Meta>) -> Self {
848 self.meta = meta.into_maybe_undefined();
849 self
850 }
851}
852
853#[serde_as]
856#[skip_serializing_none]
857#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
858#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
859#[serde(rename_all = "camelCase")]
860#[non_exhaustive]
861pub struct CompactionSummaryChunk {
862 pub compaction_id: CompactionId,
864 pub content: ContentBlock,
866 #[serde_as(deserialize_as = "DefaultOnError")]
873 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
874 #[serde(default, rename = "_meta")]
875 pub meta: Option<Meta>,
876}
877
878impl CompactionSummaryChunk {
879 #[must_use]
881 pub fn new(compaction_id: impl Into<CompactionId>, content: ContentBlock) -> Self {
882 Self {
883 compaction_id: compaction_id.into(),
884 content,
885 meta: None,
886 }
887 }
888
889 #[must_use]
891 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
892 self.meta = meta.into_option();
893 self
894 }
895}
896
897#[serde_as]
911#[skip_serializing_none]
912#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
913#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq, Eq)]
914#[serde(rename_all = "camelCase")]
915#[non_exhaustive]
916pub struct ReplayComplete {
917 #[serde_as(deserialize_as = "DefaultOnError")]
923 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
924 #[serde(default, rename = "_meta")]
925 pub meta: Option<Meta>,
926}
927
928impl ReplayComplete {
929 #[must_use]
931 pub fn new() -> Self {
932 Self::default()
933 }
934
935 #[must_use]
937 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
938 self.meta = meta.into_option();
939 self
940 }
941}
942
943#[serde_as]
976#[skip_serializing_none]
977#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
978#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
979#[serde(rename_all = "camelCase")]
980#[non_exhaustive]
981pub struct SubagentUpdate {
982 pub session_id: SessionId,
984 #[serde_as(deserialize_as = "DefaultOnError")]
989 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
990 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
991 pub title: MaybeUndefined<String>,
992 #[serde_as(deserialize_as = "DefaultOnError")]
997 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
998 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
999 pub description: MaybeUndefined<String>,
1000 #[serde_as(deserialize_as = "DefaultOnError")]
1005 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1006 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
1007 pub capabilities: MaybeUndefined<SubagentSessionCapabilities>,
1008 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
1014 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1015 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
1016 pub state: MaybeUndefined<StateUpdate>,
1017 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
1023 pub cwd: MaybeUndefined<AbsolutePath>,
1024 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
1031 pub additional_directories: MaybeUndefined<Vec<AbsolutePath>>,
1032 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
1041 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1042 #[serde(
1043 rename = "_meta",
1044 default,
1045 skip_serializing_if = "MaybeUndefined::is_undefined"
1046 )]
1047 pub meta: MaybeUndefined<Meta>,
1048}
1049
1050impl SubagentUpdate {
1051 #[must_use]
1053 pub fn new(session_id: impl Into<SessionId>) -> Self {
1054 Self {
1055 session_id: session_id.into(),
1056 title: MaybeUndefined::Undefined,
1057 description: MaybeUndefined::Undefined,
1058 capabilities: MaybeUndefined::Undefined,
1059 state: MaybeUndefined::Undefined,
1060 cwd: MaybeUndefined::Undefined,
1061 additional_directories: MaybeUndefined::Undefined,
1062 meta: MaybeUndefined::Undefined,
1063 }
1064 }
1065
1066 #[must_use]
1068 pub fn title(mut self, title: impl IntoMaybeUndefined<String>) -> Self {
1069 self.title = title.into_maybe_undefined();
1070 self
1071 }
1072
1073 #[must_use]
1075 pub fn description(mut self, description: impl IntoMaybeUndefined<String>) -> Self {
1076 self.description = description.into_maybe_undefined();
1077 self
1078 }
1079
1080 #[must_use]
1082 pub fn capabilities(
1083 mut self,
1084 capabilities: impl IntoMaybeUndefined<SubagentSessionCapabilities>,
1085 ) -> Self {
1086 self.capabilities = capabilities.into_maybe_undefined();
1087 self
1088 }
1089
1090 #[must_use]
1092 pub fn state(mut self, state: impl IntoMaybeUndefined<StateUpdate>) -> Self {
1093 self.state = state.into_maybe_undefined();
1094 self
1095 }
1096
1097 #[must_use]
1101 pub fn cwd(mut self, cwd: impl IntoMaybeUndefined<AbsolutePath>) -> Self {
1102 self.cwd = cwd.into_maybe_undefined();
1103 self
1104 }
1105
1106 #[must_use]
1110 pub fn additional_directories(
1111 mut self,
1112 additional_directories: impl IntoMaybeUndefined<Vec<AbsolutePath>>,
1113 ) -> Self {
1114 self.additional_directories = additional_directories.into_maybe_undefined();
1115 self
1116 }
1117
1118 #[must_use]
1123 pub fn meta(mut self, meta: impl IntoMaybeUndefined<Meta>) -> Self {
1124 self.meta = meta.into_maybe_undefined();
1125 self
1126 }
1127}
1128
1129#[serde_as]
1134#[skip_serializing_none]
1135#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1136#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1137#[serde(rename_all = "camelCase")]
1138#[non_exhaustive]
1139pub struct SubagentSessionCapabilities {
1140 #[serde_as(deserialize_as = "DefaultOnError")]
1144 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1145 #[serde(default)]
1146 pub cancel: Option<SessionCancelCapabilities>,
1147 #[serde_as(deserialize_as = "DefaultOnError")]
1153 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1154 #[serde(default)]
1155 #[serde(rename = "_meta")]
1156 pub meta: Option<Meta>,
1157}
1158
1159impl SubagentSessionCapabilities {
1160 #[must_use]
1162 pub fn new() -> Self {
1163 Self::default()
1164 }
1165
1166 #[must_use]
1168 pub fn cancel(mut self, cancel: impl IntoOption<SessionCancelCapabilities>) -> Self {
1169 self.cancel = cancel.into_option();
1170 self
1171 }
1172
1173 #[must_use]
1177 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1178 self.meta = meta.into_option();
1179 self
1180 }
1181}
1182
1183#[serde_as]
1187#[skip_serializing_none]
1188#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1189#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1190#[non_exhaustive]
1191pub struct SessionCancelCapabilities {
1192 #[serde_as(deserialize_as = "DefaultOnError")]
1198 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1199 #[serde(default)]
1200 #[serde(rename = "_meta")]
1201 pub meta: Option<Meta>,
1202}
1203
1204impl SessionCancelCapabilities {
1205 #[must_use]
1207 pub fn new() -> Self {
1208 Self::default()
1209 }
1210
1211 #[must_use]
1217 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1218 self.meta = meta.into_option();
1219 self
1220 }
1221}
1222
1223#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1229#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
1230#[cfg_attr(feature = "schemars", schemars(inline))]
1231#[cfg_attr(feature = "schemars", schemars(transform = other_session_update_schema))]
1232#[serde(rename_all = "camelCase")]
1233#[non_exhaustive]
1234pub struct OtherSessionUpdate {
1235 #[serde(rename = "sessionUpdate")]
1241 pub session_update: String,
1242 #[serde(flatten)]
1244 pub fields: BTreeMap<String, serde_json::Value>,
1245}
1246
1247impl OtherSessionUpdate {
1248 #[must_use]
1250 pub fn new(
1251 session_update: impl Into<String>,
1252 mut fields: BTreeMap<String, serde_json::Value>,
1253 ) -> Self {
1254 fields.remove("sessionUpdate");
1255 Self {
1256 session_update: session_update.into(),
1257 fields,
1258 }
1259 }
1260}
1261
1262impl<'de> Deserialize<'de> for OtherSessionUpdate {
1263 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1264 where
1265 D: serde::Deserializer<'de>,
1266 {
1267 let mut fields = BTreeMap::<String, serde_json::Value>::deserialize(deserializer)?;
1268 let session_update = fields
1269 .remove("sessionUpdate")
1270 .ok_or_else(|| serde::de::Error::missing_field("sessionUpdate"))?;
1271 let serde_json::Value::String(session_update) = session_update else {
1272 return Err(serde::de::Error::custom("`sessionUpdate` must be a string"));
1273 };
1274
1275 if is_known_session_update(&session_update) {
1276 return Err(serde::de::Error::custom(format!(
1277 "known session update `{session_update}` did not match its schema"
1278 )));
1279 }
1280
1281 Ok(Self {
1282 session_update,
1283 fields,
1284 })
1285 }
1286}
1287
1288fn is_known_session_update(session_update: &str) -> bool {
1289 if session_update == "notice" {
1290 return true;
1291 }
1292 if matches!(
1293 session_update,
1294 "compaction_update" | "compaction_summary_chunk" | "replay_complete"
1295 ) {
1296 return true;
1297 }
1298 #[cfg(feature = "unstable_plan_operations")]
1299 if session_update == "plan_removed" {
1300 return true;
1301 }
1302 #[cfg(feature = "unstable_prompt_suggestions")]
1303 if session_update == "prompt_suggestions_update" {
1304 return true;
1305 }
1306 if matches!(
1307 session_update,
1308 "subagent_update" | "session_message" | "session_message_chunk"
1309 ) {
1310 return true;
1311 }
1312 matches!(
1313 session_update,
1314 "user_message_chunk"
1315 | "user_message"
1316 | "agent_message_chunk"
1317 | "agent_message"
1318 | "agent_thought_chunk"
1319 | "agent_thought"
1320 | "state_update"
1321 | "tool_call_content_chunk"
1322 | "tool_call_update"
1323 | "terminal_update"
1324 | "terminal_output_chunk"
1325 | "plan_update"
1326 | "available_commands_update"
1327 | "config_option_update"
1328 | "session_info_update"
1329 | "usage_update"
1330 )
1331}
1332
1333#[cfg(feature = "schemars")]
1334fn other_session_update_schema(schema: &mut Schema) {
1335 super::schema_util::reject_known_string_discriminators(
1336 schema,
1337 "sessionUpdate",
1338 &[
1339 "user_message_chunk",
1340 "user_message",
1341 "agent_message_chunk",
1342 "agent_message",
1343 "agent_thought_chunk",
1344 "agent_thought",
1345 "state_update",
1346 "tool_call_content_chunk",
1347 "tool_call_update",
1348 "terminal_update",
1349 "terminal_output_chunk",
1350 "plan_update",
1351 "available_commands_update",
1352 "config_option_update",
1353 "session_info_update",
1354 #[cfg(feature = "unstable_plan_operations")]
1355 "plan_removed",
1356 "usage_update",
1357 "notice",
1358 "compaction_update",
1359 "compaction_summary_chunk",
1360 "replay_complete",
1361 #[cfg(feature = "unstable_prompt_suggestions")]
1362 "prompt_suggestions_update",
1363 "subagent_update",
1364 "session_message",
1365 "session_message_chunk",
1366 ],
1367 );
1368}
1369
1370#[serde_as]
1372#[skip_serializing_none]
1373#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1374#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1375#[serde(rename_all = "camelCase")]
1376#[non_exhaustive]
1377pub struct ConfigOptionUpdate {
1378 #[serde_as(deserialize_as = "VecSkipError<_>")]
1380 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-skip-invalid-items" = true)))]
1381 pub config_options: Vec<SessionConfigOption>,
1382 #[serde_as(deserialize_as = "DefaultOnError")]
1388 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1389 #[serde(default)]
1390 #[serde(rename = "_meta")]
1391 pub meta: Option<Meta>,
1392}
1393
1394impl ConfigOptionUpdate {
1395 #[must_use]
1397 pub fn new(config_options: Vec<SessionConfigOption>) -> Self {
1398 Self {
1399 config_options,
1400 meta: None,
1401 }
1402 }
1403
1404 #[must_use]
1410 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1411 self.meta = meta.into_option();
1412 self
1413 }
1414}
1415
1416#[serde_as]
1425#[skip_serializing_none]
1426#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1427#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1428#[serde(rename_all = "camelCase")]
1429#[non_exhaustive]
1430pub struct SessionInfoUpdate {
1431 #[serde_as(deserialize_as = "DefaultOnError")]
1433 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1434 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
1435 pub title: MaybeUndefined<String>,
1436 #[serde_as(deserialize_as = "DefaultOnError")]
1438 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "format" = "date-time")))]
1439 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
1440 pub updated_at: MaybeUndefined<String>,
1441 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
1450 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1451 #[serde(
1452 rename = "_meta",
1453 default,
1454 skip_serializing_if = "MaybeUndefined::is_undefined"
1455 )]
1456 pub meta: MaybeUndefined<Meta>,
1457}
1458
1459impl SessionInfoUpdate {
1460 #[must_use]
1462 pub fn new() -> Self {
1463 Self::default()
1464 }
1465
1466 #[must_use]
1468 pub fn title(mut self, title: impl IntoMaybeUndefined<String>) -> Self {
1469 self.title = title.into_maybe_undefined();
1470 self
1471 }
1472
1473 #[must_use]
1475 pub fn updated_at(mut self, updated_at: impl IntoMaybeUndefined<String>) -> Self {
1476 self.updated_at = updated_at.into_maybe_undefined();
1477 self
1478 }
1479
1480 #[must_use]
1485 pub fn meta(mut self, meta: impl IntoMaybeUndefined<Meta>) -> Self {
1486 self.meta = meta.into_maybe_undefined();
1487 self
1488 }
1489}
1490
1491#[serde_as]
1493#[skip_serializing_none]
1494#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1495#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1496#[serde(rename_all = "camelCase")]
1497#[non_exhaustive]
1498pub struct UsageUpdate {
1499 pub used: u64,
1501 pub size: u64,
1503 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
1507 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1508 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
1509 pub cost: MaybeUndefined<Cost>,
1510 #[serde_as(deserialize_as = "DefaultOnError")]
1516 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1517 #[serde(default)]
1518 #[serde(rename = "_meta")]
1519 pub meta: Option<Meta>,
1520}
1521
1522impl UsageUpdate {
1523 #[must_use]
1525 pub fn new(used: u64, size: u64) -> Self {
1526 Self {
1527 used,
1528 size,
1529 cost: MaybeUndefined::Undefined,
1530 meta: None,
1531 }
1532 }
1533
1534 #[must_use]
1536 pub fn cost(mut self, cost: impl IntoMaybeUndefined<Cost>) -> Self {
1537 self.cost = cost.into_maybe_undefined();
1538 self
1539 }
1540
1541 #[must_use]
1547 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1548 self.meta = meta.into_option();
1549 self
1550 }
1551}
1552
1553#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1594#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1595#[serde(tag = "state", rename_all = "snake_case")]
1596#[non_exhaustive]
1597pub enum StateUpdate {
1598 Running(RunningStateUpdate),
1600 Idle(IdleStateUpdate),
1602 RequiresAction(RequiresActionStateUpdate),
1604 Unknown(UnknownStateUpdate),
1607 #[serde(untagged)]
1619 Other(OtherStateUpdate),
1620}
1621
1622impl StateUpdate {
1623 #[must_use]
1631 pub fn background(&self) -> Option<&[BackgroundWork]> {
1632 match self {
1633 Self::Running(state) => state.background.as_deref(),
1634 Self::Idle(state) => state.background.as_deref(),
1635 Self::RequiresAction(state) => state.background.as_deref(),
1636 Self::Unknown(state) => state.background.as_deref(),
1637 Self::Other(_) => None,
1638 }
1639 }
1640}
1641
1642#[serde_as]
1644#[skip_serializing_none]
1645#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1646#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1647#[serde(rename_all = "camelCase")]
1648#[non_exhaustive]
1649pub struct RunningStateUpdate {
1650 #[serde_as(deserialize_as = "DefaultOnError")]
1659 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1660 #[serde(default)]
1661 pub background: Option<Vec<BackgroundWork>>,
1662 #[serde_as(deserialize_as = "DefaultOnError")]
1668 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1669 #[serde(default)]
1670 #[serde(rename = "_meta")]
1671 pub meta: Option<Meta>,
1672}
1673
1674impl RunningStateUpdate {
1675 #[must_use]
1677 pub fn new() -> Self {
1678 Self::default()
1679 }
1680
1681 #[must_use]
1683 pub fn background(mut self, background: impl IntoOption<Vec<BackgroundWork>>) -> Self {
1684 self.background = background.into_option();
1685 self
1686 }
1687
1688 #[must_use]
1694 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1695 self.meta = meta.into_option();
1696 self
1697 }
1698}
1699
1700#[serde_as]
1709#[skip_serializing_none]
1710#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1711#[cfg_attr(feature = "schemars", schemars(transform = idle_state_update_schema))]
1712#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1713#[serde(rename_all = "camelCase")]
1714#[non_exhaustive]
1715pub struct IdleStateUpdate {
1716 #[serde(flatten)]
1718 pub stop_reason: Option<StopReason>,
1719 #[cfg(feature = "unstable_end_turn_token_usage")]
1728 #[serde_as(deserialize_as = "DefaultOnError")]
1729 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1730 #[serde(default)]
1731 pub usage: Option<Box<Usage>>,
1732 #[serde_as(deserialize_as = "DefaultOnError")]
1741 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1742 #[serde(default)]
1743 pub background: Option<Vec<BackgroundWork>>,
1744 #[serde_as(deserialize_as = "DefaultOnError")]
1750 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1751 #[serde(default)]
1752 #[serde(rename = "_meta")]
1753 pub meta: Option<Meta>,
1754}
1755
1756impl IdleStateUpdate {
1757 #[must_use]
1759 pub fn new() -> Self {
1760 Self::default()
1761 }
1762
1763 #[must_use]
1765 pub fn stop_reason(mut self, stop_reason: impl IntoOption<StopReason>) -> Self {
1766 self.stop_reason = stop_reason.into_option();
1767 self
1768 }
1769
1770 #[cfg(feature = "unstable_end_turn_token_usage")]
1776 #[must_use]
1777 pub fn usage(mut self, usage: impl IntoOption<Usage>) -> Self {
1778 self.usage = usage.into_option().map(Box::new);
1779 self
1780 }
1781
1782 #[must_use]
1784 pub fn background(mut self, background: impl IntoOption<Vec<BackgroundWork>>) -> Self {
1785 self.background = background.into_option();
1786 self
1787 }
1788
1789 #[must_use]
1795 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1796 self.meta = meta.into_option();
1797 self
1798 }
1799}
1800
1801#[cfg(feature = "schemars")]
1810fn idle_state_update_schema(schema: &mut Schema) {
1811 if let Some(properties) = schema
1812 .get_mut("properties")
1813 .and_then(serde_json::Value::as_object_mut)
1814 {
1815 properties.insert(
1816 "stopReason".into(),
1817 serde_json::json!({
1818 "description": "Why foreground work stopped. The value selects one of this type's variants, which may add fields of their own.\n\nOptional. Omitted and `null` are equivalent and mean the agent is not reporting a stop reason; a malformed value is treated the same way.\n\nSee protocol docs: [Stop Reasons](https://agentclientprotocol.com/protocol/v2/prompt-lifecycle#stop-reasons)",
1819 "type": ["string", "null"],
1820 "x-deserialize-default-on-error": true
1821 }),
1822 );
1823 }
1824 let Some(variants) = schema
1825 .get_mut("anyOf")
1826 .and_then(serde_json::Value::as_array_mut)
1827 else {
1828 return;
1829 };
1830 for variant in variants {
1831 if variant.as_object().is_some_and(serde_json::Map::is_empty) {
1832 *variant = serde_json::json!({
1833 "title": "none",
1834 "description": "No stop reason: `stopReason` is omitted or `null`.",
1835 "type": "object",
1836 "properties": {
1837 "stopReason": { "type": "null" }
1838 }
1839 });
1840 }
1841 }
1842}
1843
1844#[serde_as]
1853#[skip_serializing_none]
1854#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1855#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1856#[serde(rename_all = "camelCase")]
1857#[non_exhaustive]
1858pub struct RequiresActionStateUpdate {
1859 #[serde_as(deserialize_as = "DefaultOnError")]
1868 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1869 #[serde(default)]
1870 pub background: Option<Vec<BackgroundWork>>,
1871 #[serde_as(deserialize_as = "DefaultOnError")]
1877 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1878 #[serde(default)]
1879 #[serde(rename = "_meta")]
1880 pub meta: Option<Meta>,
1881}
1882
1883impl RequiresActionStateUpdate {
1884 #[must_use]
1886 pub fn new() -> Self {
1887 Self::default()
1888 }
1889
1890 #[must_use]
1892 pub fn background(mut self, background: impl IntoOption<Vec<BackgroundWork>>) -> Self {
1893 self.background = background.into_option();
1894 self
1895 }
1896
1897 #[must_use]
1903 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1904 self.meta = meta.into_option();
1905 self
1906 }
1907}
1908
1909#[serde_as]
1922#[skip_serializing_none]
1923#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1924#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1925#[serde(rename_all = "camelCase")]
1926#[non_exhaustive]
1927pub struct UnknownStateUpdate {
1928 #[serde_as(deserialize_as = "DefaultOnError")]
1937 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1938 #[serde(default)]
1939 pub background: Option<Vec<BackgroundWork>>,
1940 #[serde_as(deserialize_as = "DefaultOnError")]
1946 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1947 #[serde(default, rename = "_meta")]
1948 pub meta: Option<Meta>,
1949}
1950
1951impl UnknownStateUpdate {
1952 #[must_use]
1954 pub fn new() -> Self {
1955 Self::default()
1956 }
1957
1958 #[must_use]
1960 pub fn background(mut self, background: impl IntoOption<Vec<BackgroundWork>>) -> Self {
1961 self.background = background.into_option();
1962 self
1963 }
1964
1965 #[must_use]
1967 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1968 self.meta = meta.into_option();
1969 self
1970 }
1971}
1972
1973#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1978#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
1979#[cfg_attr(feature = "schemars", schemars(inline))]
1980#[cfg_attr(feature = "schemars", schemars(transform = other_state_update_schema))]
1981#[serde(rename_all = "camelCase")]
1982#[non_exhaustive]
1983pub struct OtherStateUpdate {
1984 #[serde(rename = "state")]
1990 pub state: String,
1991 #[serde(flatten)]
1993 pub fields: BTreeMap<String, serde_json::Value>,
1994}
1995
1996impl OtherStateUpdate {
1997 #[must_use]
1999 pub fn new(state: impl Into<String>, mut fields: BTreeMap<String, serde_json::Value>) -> Self {
2000 fields.remove("state");
2001 Self {
2002 state: state.into(),
2003 fields,
2004 }
2005 }
2006}
2007
2008impl<'de> Deserialize<'de> for OtherStateUpdate {
2009 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2010 where
2011 D: serde::Deserializer<'de>,
2012 {
2013 let mut fields = BTreeMap::<String, serde_json::Value>::deserialize(deserializer)?;
2014 let state = fields
2015 .remove("state")
2016 .ok_or_else(|| serde::de::Error::missing_field("state"))?;
2017 let serde_json::Value::String(state) = state else {
2018 return Err(serde::de::Error::custom("`state` must be a string"));
2019 };
2020
2021 if is_known_state_update(&state) {
2022 return Err(serde::de::Error::custom(format!(
2023 "known state update `{state}` did not match its schema"
2024 )));
2025 }
2026
2027 Ok(Self { state, fields })
2028 }
2029}
2030
2031const KNOWN_STATE_UPDATE_STATES: &[&str] = &["running", "idle", "requires_action", "unknown"];
2032
2033fn is_known_state_update(state: &str) -> bool {
2034 KNOWN_STATE_UPDATE_STATES.contains(&state)
2035}
2036
2037#[cfg(feature = "schemars")]
2038fn other_state_update_schema(schema: &mut Schema) {
2039 super::schema_util::reject_known_string_discriminators(
2040 schema,
2041 "state",
2042 KNOWN_STATE_UPDATE_STATES,
2043 );
2044}
2045
2046#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2055#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2056#[serde(tag = "type", rename_all = "snake_case")]
2057#[non_exhaustive]
2058pub enum BackgroundWork {
2059 Terminal(BackgroundTerminal),
2062 ToolCall(BackgroundToolCall),
2066 Subagent(BackgroundSubagent),
2069 #[serde(untagged)]
2078 Other(OtherBackgroundWork),
2079}
2080
2081#[serde_as]
2083#[skip_serializing_none]
2084#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2085#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2086#[serde(rename_all = "camelCase")]
2087#[non_exhaustive]
2088pub struct BackgroundTerminal {
2089 pub terminal_id: TerminalId,
2091 #[serde_as(deserialize_as = "DefaultOnError")]
2097 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2098 #[serde(default)]
2099 #[serde(rename = "_meta")]
2100 pub meta: Option<Meta>,
2101}
2102
2103impl BackgroundTerminal {
2104 #[must_use]
2106 pub fn new(terminal_id: impl Into<TerminalId>) -> Self {
2107 Self {
2108 terminal_id: terminal_id.into(),
2109 meta: None,
2110 }
2111 }
2112
2113 #[must_use]
2119 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2120 self.meta = meta.into_option();
2121 self
2122 }
2123}
2124
2125#[serde_as]
2127#[skip_serializing_none]
2128#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2129#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2130#[serde(rename_all = "camelCase")]
2131#[non_exhaustive]
2132pub struct BackgroundToolCall {
2133 pub tool_call_id: ToolCallId,
2135 #[serde_as(deserialize_as = "DefaultOnError")]
2141 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2142 #[serde(default)]
2143 #[serde(rename = "_meta")]
2144 pub meta: Option<Meta>,
2145}
2146
2147impl BackgroundToolCall {
2148 #[must_use]
2150 pub fn new(tool_call_id: impl Into<ToolCallId>) -> Self {
2151 Self {
2152 tool_call_id: tool_call_id.into(),
2153 meta: None,
2154 }
2155 }
2156
2157 #[must_use]
2163 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2164 self.meta = meta.into_option();
2165 self
2166 }
2167}
2168
2169#[serde_as]
2171#[skip_serializing_none]
2172#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2173#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2174#[serde(rename_all = "camelCase")]
2175#[non_exhaustive]
2176pub struct BackgroundSubagent {
2177 pub session_id: SessionId,
2179 #[serde_as(deserialize_as = "DefaultOnError")]
2185 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2186 #[serde(default)]
2187 #[serde(rename = "_meta")]
2188 pub meta: Option<Meta>,
2189}
2190
2191impl BackgroundSubagent {
2192 #[must_use]
2194 pub fn new(session_id: impl Into<SessionId>) -> Self {
2195 Self {
2196 session_id: session_id.into(),
2197 meta: None,
2198 }
2199 }
2200
2201 #[must_use]
2207 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2208 self.meta = meta.into_option();
2209 self
2210 }
2211}
2212
2213#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2218#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
2219#[cfg_attr(feature = "schemars", schemars(inline))]
2220#[cfg_attr(feature = "schemars", schemars(transform = other_background_work_schema))]
2221#[serde(rename_all = "camelCase")]
2222#[non_exhaustive]
2223pub struct OtherBackgroundWork {
2224 #[serde(rename = "type")]
2230 pub kind: String,
2231 #[serde(flatten)]
2233 pub fields: BTreeMap<String, serde_json::Value>,
2234}
2235
2236impl OtherBackgroundWork {
2237 #[must_use]
2239 pub fn new(kind: impl Into<String>, mut fields: BTreeMap<String, serde_json::Value>) -> Self {
2240 fields.remove("type");
2241 Self {
2242 kind: kind.into(),
2243 fields,
2244 }
2245 }
2246}
2247
2248impl<'de> Deserialize<'de> for OtherBackgroundWork {
2249 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2250 where
2251 D: serde::Deserializer<'de>,
2252 {
2253 let mut fields = BTreeMap::<String, serde_json::Value>::deserialize(deserializer)?;
2254 let kind = fields
2255 .remove("type")
2256 .ok_or_else(|| serde::de::Error::missing_field("type"))?;
2257 let serde_json::Value::String(kind) = kind else {
2258 return Err(serde::de::Error::custom("`type` must be a string"));
2259 };
2260
2261 if KNOWN_BACKGROUND_WORK_TYPES.contains(&kind.as_str()) {
2262 return Err(serde::de::Error::custom(format!(
2263 "known background work `{kind}` did not match its schema"
2264 )));
2265 }
2266
2267 Ok(Self { kind, fields })
2268 }
2269}
2270
2271const KNOWN_BACKGROUND_WORK_TYPES: &[&str] = &["terminal", "tool_call", "subagent"];
2272
2273#[cfg(feature = "schemars")]
2274fn other_background_work_schema(schema: &mut Schema) {
2275 super::schema_util::reject_known_string_discriminators(
2276 schema,
2277 "type",
2278 KNOWN_BACKGROUND_WORK_TYPES,
2279 );
2280}
2281
2282#[serde_as]
2284#[skip_serializing_none]
2285#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2286#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
2287#[serde(rename_all = "camelCase")]
2288#[non_exhaustive]
2289pub struct Cost {
2290 pub amount: f64,
2292 pub currency: String,
2295 #[serde_as(deserialize_as = "DefaultOnError")]
2301 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2302 #[serde(default)]
2303 #[serde(rename = "_meta")]
2304 pub meta: Option<Meta>,
2305}
2306
2307impl Cost {
2308 #[must_use]
2310 pub fn new(amount: f64, currency: impl Into<String>) -> Self {
2311 Self {
2312 amount,
2313 currency: currency.into(),
2314 meta: None,
2315 }
2316 }
2317
2318 #[must_use]
2324 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2325 self.meta = meta.into_option();
2326 self
2327 }
2328}
2329
2330#[serde_as]
2332#[skip_serializing_none]
2333#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2334#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2335#[serde(rename_all = "camelCase")]
2336#[non_exhaustive]
2337pub struct ContentChunk {
2338 pub message_id: MessageId,
2343 pub content: ContentBlock,
2345 #[serde_as(deserialize_as = "DefaultOnError")]
2352 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2353 #[serde(default)]
2354 #[serde(rename = "_meta")]
2355 pub meta: Option<Meta>,
2356}
2357
2358impl ContentChunk {
2359 #[must_use]
2361 pub fn new(content: ContentBlock, message_id: impl Into<MessageId>) -> Self {
2362 Self {
2363 content,
2364 message_id: message_id.into(),
2365 meta: None,
2366 }
2367 }
2368
2369 #[must_use]
2375 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2376 self.meta = meta.into_option();
2377 self
2378 }
2379}
2380
2381#[serde_as]
2395#[skip_serializing_none]
2396#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2397#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2398#[serde(rename_all = "camelCase")]
2399#[non_exhaustive]
2400pub struct UserMessage {
2401 pub message_id: MessageId,
2403 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<VecSkipError<_>>>")]
2405 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
2406 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
2407 pub content: MaybeUndefined<Vec<ContentBlock>>,
2408 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
2417 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2418 #[serde(
2419 rename = "_meta",
2420 default,
2421 skip_serializing_if = "MaybeUndefined::is_undefined"
2422 )]
2423 pub meta: MaybeUndefined<Meta>,
2424}
2425
2426impl UserMessage {
2427 #[must_use]
2429 pub fn new(message_id: impl Into<MessageId>) -> Self {
2430 Self {
2431 message_id: message_id.into(),
2432 content: MaybeUndefined::Undefined,
2433 meta: MaybeUndefined::Undefined,
2434 }
2435 }
2436
2437 #[must_use]
2439 pub fn content(mut self, content: impl IntoMaybeUndefined<Vec<ContentBlock>>) -> Self {
2440 self.content = content.into_maybe_undefined();
2441 self
2442 }
2443
2444 #[must_use]
2449 pub fn meta(mut self, meta: impl IntoMaybeUndefined<Meta>) -> Self {
2450 self.meta = meta.into_maybe_undefined();
2451 self
2452 }
2453}
2454
2455#[serde_as]
2469#[skip_serializing_none]
2470#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2471#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2472#[serde(rename_all = "camelCase")]
2473#[non_exhaustive]
2474pub struct AgentMessage {
2475 pub message_id: MessageId,
2477 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<VecSkipError<_>>>")]
2479 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
2480 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
2481 pub content: MaybeUndefined<Vec<ContentBlock>>,
2482 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
2491 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2492 #[serde(
2493 rename = "_meta",
2494 default,
2495 skip_serializing_if = "MaybeUndefined::is_undefined"
2496 )]
2497 pub meta: MaybeUndefined<Meta>,
2498}
2499
2500impl AgentMessage {
2501 #[must_use]
2503 pub fn new(message_id: impl Into<MessageId>) -> Self {
2504 Self {
2505 message_id: message_id.into(),
2506 content: MaybeUndefined::Undefined,
2507 meta: MaybeUndefined::Undefined,
2508 }
2509 }
2510
2511 #[must_use]
2513 pub fn content(mut self, content: impl IntoMaybeUndefined<Vec<ContentBlock>>) -> Self {
2514 self.content = content.into_maybe_undefined();
2515 self
2516 }
2517
2518 #[must_use]
2523 pub fn meta(mut self, meta: impl IntoMaybeUndefined<Meta>) -> Self {
2524 self.meta = meta.into_maybe_undefined();
2525 self
2526 }
2527}
2528
2529#[serde_as]
2543#[skip_serializing_none]
2544#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2545#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2546#[serde(rename_all = "camelCase")]
2547#[non_exhaustive]
2548pub struct AgentThought {
2549 pub message_id: MessageId,
2551 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<VecSkipError<_>>>")]
2553 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
2554 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
2555 pub content: MaybeUndefined<Vec<ContentBlock>>,
2556 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
2565 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2566 #[serde(
2567 rename = "_meta",
2568 default,
2569 skip_serializing_if = "MaybeUndefined::is_undefined"
2570 )]
2571 pub meta: MaybeUndefined<Meta>,
2572}
2573
2574impl AgentThought {
2575 #[must_use]
2577 pub fn new(message_id: impl Into<MessageId>) -> Self {
2578 Self {
2579 message_id: message_id.into(),
2580 content: MaybeUndefined::Undefined,
2581 meta: MaybeUndefined::Undefined,
2582 }
2583 }
2584
2585 #[must_use]
2587 pub fn content(mut self, content: impl IntoMaybeUndefined<Vec<ContentBlock>>) -> Self {
2588 self.content = content.into_maybe_undefined();
2589 self
2590 }
2591
2592 #[must_use]
2597 pub fn meta(mut self, meta: impl IntoMaybeUndefined<Meta>) -> Self {
2598 self.meta = meta.into_maybe_undefined();
2599 self
2600 }
2601}
2602
2603#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2609#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
2610#[serde(transparent)]
2611#[from(forward)]
2612#[non_exhaustive]
2613pub struct MessageId(pub Arc<str>);
2614
2615impl MessageId {
2616 #[must_use]
2618 pub fn new(id: impl Into<Self>) -> Self {
2619 id.into()
2620 }
2621}
2622
2623#[cfg(feature = "unstable_prompt_suggestions")]
2640#[serde_as]
2641#[skip_serializing_none]
2642#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2643#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2644#[serde(rename_all = "camelCase")]
2645#[non_exhaustive]
2646pub struct PromptSuggestionsUpdate {
2647 #[serde_as(deserialize_as = "VecSkipError<_>")]
2653 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-skip-invalid-items" = true)))]
2654 pub suggestions: Vec<PromptSuggestion>,
2655 #[serde_as(deserialize_as = "DefaultOnError")]
2661 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2662 #[serde(default)]
2663 #[serde(rename = "_meta")]
2664 pub meta: Option<Meta>,
2665}
2666
2667#[cfg(feature = "unstable_prompt_suggestions")]
2668impl PromptSuggestionsUpdate {
2669 #[must_use]
2673 pub fn new(suggestions: Vec<PromptSuggestion>) -> Self {
2674 Self {
2675 suggestions,
2676 meta: None,
2677 }
2678 }
2679
2680 #[must_use]
2686 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2687 self.meta = meta.into_option();
2688 self
2689 }
2690}
2691
2692#[cfg(feature = "unstable_prompt_suggestions")]
2698#[serde_as]
2699#[skip_serializing_none]
2700#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2701#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2702#[serde(rename_all = "camelCase")]
2703#[non_exhaustive]
2704pub struct PromptSuggestion {
2705 #[cfg_attr(feature = "schemars", schemars(length(min = 1)))]
2717 pub prompt: Vec<ContentBlock>,
2718 #[serde_as(deserialize_as = "DefaultOnError")]
2724 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2725 #[serde(default)]
2726 #[serde(rename = "_meta")]
2727 pub meta: Option<Meta>,
2728}
2729
2730#[cfg(feature = "unstable_prompt_suggestions")]
2731impl PromptSuggestion {
2732 #[must_use]
2734 pub fn new(prompt: Vec<ContentBlock>) -> Self {
2735 Self { prompt, meta: None }
2736 }
2737
2738 #[must_use]
2744 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2745 self.meta = meta.into_option();
2746 self
2747 }
2748}
2749
2750#[serde_as]
2752#[skip_serializing_none]
2753#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2754#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2755#[serde(rename_all = "camelCase")]
2756#[non_exhaustive]
2757pub struct AvailableCommandsUpdate {
2758 #[serde_as(deserialize_as = "VecSkipError<_>")]
2760 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-skip-invalid-items" = true)))]
2761 pub available_commands: Vec<AvailableCommand>,
2762 #[serde_as(deserialize_as = "DefaultOnError")]
2768 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2769 #[serde(default)]
2770 #[serde(rename = "_meta")]
2771 pub meta: Option<Meta>,
2772}
2773
2774impl AvailableCommandsUpdate {
2775 #[must_use]
2777 pub fn new(available_commands: Vec<AvailableCommand>) -> Self {
2778 Self {
2779 available_commands,
2780 meta: None,
2781 }
2782 }
2783
2784 #[must_use]
2790 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2791 self.meta = meta.into_option();
2792 self
2793 }
2794}
2795
2796#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2800#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2801#[serde(tag = "type", rename_all = "snake_case")]
2802#[non_exhaustive]
2803pub enum AvailableCommand {
2804 Command(Command),
2806 #[cfg(feature = "unstable_agent_skills")]
2815 Skill(Skill),
2816 #[serde(untagged)]
2827 Other(OtherAvailableCommand),
2828}
2829
2830impl AvailableCommand {
2831 #[must_use]
2833 pub fn name(&self) -> &str {
2834 match self {
2835 Self::Command(c) => &c.name,
2836 #[cfg(feature = "unstable_agent_skills")]
2837 Self::Skill(c) => &c.name,
2838 Self::Other(c) => &c.name,
2839 }
2840 }
2841
2842 #[must_use]
2844 pub fn description(&self) -> &str {
2845 match self {
2846 Self::Command(c) => &c.description,
2847 #[cfg(feature = "unstable_agent_skills")]
2848 Self::Skill(c) => &c.description,
2849 Self::Other(c) => &c.description,
2850 }
2851 }
2852
2853 #[must_use]
2859 pub fn meta(&self) -> Option<&Meta> {
2860 match self {
2861 Self::Command(c) => c.meta.as_ref(),
2862 #[cfg(feature = "unstable_agent_skills")]
2863 Self::Skill(c) => c.meta.as_ref(),
2864 Self::Other(c) => c.fields.get("_meta").and_then(serde_json::Value::as_object),
2865 }
2866 }
2867}
2868
2869#[serde_as]
2871#[skip_serializing_none]
2872#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2873#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
2874#[cfg_attr(feature = "schemars", schemars(inline))]
2875#[cfg_attr(feature = "schemars", schemars(transform = other_available_command_schema))]
2876#[serde(rename_all = "camelCase")]
2877#[non_exhaustive]
2878pub struct OtherAvailableCommand {
2879 #[serde(rename = "type")]
2885 pub type_: String,
2886 pub name: String,
2888 pub description: String,
2890 #[serde(flatten)]
2893 pub fields: BTreeMap<String, serde_json::Value>,
2894}
2895
2896impl OtherAvailableCommand {
2897 #[must_use]
2899 pub fn new(
2900 type_: impl Into<String>,
2901 name: impl Into<String>,
2902 description: impl Into<String>,
2903 mut fields: BTreeMap<String, serde_json::Value>,
2904 ) -> Self {
2905 fields.remove("type");
2906 fields.remove("name");
2907 fields.remove("description");
2908 Self {
2909 type_: type_.into(),
2910 name: name.into(),
2911 description: description.into(),
2912 fields,
2913 }
2914 }
2915}
2916
2917impl<'de> Deserialize<'de> for OtherAvailableCommand {
2918 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2919 where
2920 D: serde::Deserializer<'de>,
2921 {
2922 #[derive(Deserialize)]
2923 struct RawOtherAvailableCommand {
2924 #[serde(rename = "type")]
2925 type_: String,
2926 name: String,
2927 description: String,
2928 #[serde(flatten)]
2929 fields: BTreeMap<String, serde_json::Value>,
2930 }
2931
2932 let raw = RawOtherAvailableCommand::deserialize(deserializer)?;
2933 if is_known_available_command_type(&raw.type_) {
2934 return Err(serde::de::Error::custom(format!(
2935 "known available command type `{}` did not match its schema",
2936 raw.type_
2937 )));
2938 }
2939
2940 Ok(Self {
2941 type_: raw.type_,
2942 name: raw.name,
2943 description: raw.description,
2944 fields: raw.fields,
2945 })
2946 }
2947}
2948
2949const KNOWN_AVAILABLE_COMMAND_TYPES: &[&str] = &[
2950 "command",
2951 #[cfg(feature = "unstable_agent_skills")]
2952 "skill",
2953];
2954
2955fn is_known_available_command_type(type_: &str) -> bool {
2956 KNOWN_AVAILABLE_COMMAND_TYPES.contains(&type_)
2957}
2958
2959#[cfg(feature = "schemars")]
2960fn other_available_command_schema(schema: &mut Schema) {
2961 super::schema_util::reject_known_string_discriminators(
2962 schema,
2963 "type",
2964 KNOWN_AVAILABLE_COMMAND_TYPES,
2965 );
2966}
2967
2968#[serde_as]
2972#[skip_serializing_none]
2973#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2974#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2975#[serde(rename_all = "camelCase")]
2976#[non_exhaustive]
2977pub struct Command {
2978 pub name: String,
2982 pub description: String,
2984 #[serde_as(deserialize_as = "DefaultOnError")]
2988 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2989 #[serde(default)]
2990 pub input: Option<AvailableCommandInput>,
2991 #[serde_as(deserialize_as = "DefaultOnError")]
2997 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2998 #[serde(default)]
2999 #[serde(rename = "_meta")]
3000 pub meta: Option<Meta>,
3001}
3002
3003impl Command {
3004 #[must_use]
3006 pub fn new(name: impl Into<String>, description: impl Into<String>) -> Self {
3007 Self {
3008 name: name.into(),
3009 description: description.into(),
3010 input: None,
3011 meta: None,
3012 }
3013 }
3014
3015 #[must_use]
3017 pub fn input(mut self, input: impl IntoOption<AvailableCommandInput>) -> Self {
3018 self.input = input.into_option();
3019 self
3020 }
3021
3022 #[must_use]
3028 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3029 self.meta = meta.into_option();
3030 self
3031 }
3032}
3033
3034#[cfg(feature = "unstable_agent_skills")]
3050#[serde_as]
3051#[skip_serializing_none]
3052#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3053#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3054#[serde(rename_all = "camelCase")]
3055#[non_exhaustive]
3056pub struct Skill {
3057 pub name: String,
3063 pub description: String,
3065 #[serde_as(deserialize_as = "DefaultOnError")]
3071 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3072 #[serde(default)]
3073 pub path: Option<AbsolutePath>,
3074 #[serde_as(deserialize_as = "DefaultOnError")]
3080 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3081 #[serde(default)]
3082 #[serde(rename = "_meta")]
3083 pub meta: Option<Meta>,
3084}
3085
3086#[cfg(feature = "unstable_agent_skills")]
3087impl Skill {
3088 #[must_use]
3090 pub fn new(name: impl Into<String>, description: impl Into<String>) -> Self {
3091 Self {
3092 name: name.into(),
3093 description: description.into(),
3094 path: None,
3095 meta: None,
3096 }
3097 }
3098
3099 #[must_use]
3102 pub fn path(mut self, path: impl IntoOption<AbsolutePath>) -> Self {
3103 self.path = path.into_option();
3104 self
3105 }
3106
3107 #[must_use]
3113 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3114 self.meta = meta.into_option();
3115 self
3116 }
3117}
3118
3119#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3121#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3122#[serde(tag = "type", rename_all = "snake_case")]
3123#[non_exhaustive]
3124pub enum AvailableCommandInput {
3125 #[serde(rename = "text")]
3127 Text(TextCommandInput),
3128 #[serde(untagged)]
3139 Other(OtherAvailableCommandInput),
3140}
3141
3142#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3144#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
3145#[cfg_attr(feature = "schemars", schemars(inline))]
3146#[cfg_attr(feature = "schemars", schemars(transform = other_available_command_input_schema))]
3147#[serde(rename_all = "camelCase")]
3148#[non_exhaustive]
3149pub struct OtherAvailableCommandInput {
3150 #[serde(rename = "type")]
3156 pub type_: String,
3157 #[serde(flatten)]
3159 pub fields: BTreeMap<String, serde_json::Value>,
3160}
3161
3162impl OtherAvailableCommandInput {
3163 #[must_use]
3165 pub fn new(type_: impl Into<String>, mut fields: BTreeMap<String, serde_json::Value>) -> Self {
3166 fields.remove("type");
3167 Self {
3168 type_: type_.into(),
3169 fields,
3170 }
3171 }
3172}
3173
3174impl<'de> Deserialize<'de> for OtherAvailableCommandInput {
3175 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
3176 where
3177 D: serde::Deserializer<'de>,
3178 {
3179 let mut fields = BTreeMap::<String, serde_json::Value>::deserialize(deserializer)?;
3180 let type_ = fields
3181 .remove("type")
3182 .ok_or_else(|| serde::de::Error::missing_field("type"))?;
3183 let serde_json::Value::String(type_) = type_ else {
3184 return Err(serde::de::Error::custom("`type` must be a string"));
3185 };
3186
3187 if is_known_available_command_input_type(&type_) {
3188 return Err(serde::de::Error::custom(format!(
3189 "known available command input type `{type_}` did not match its schema"
3190 )));
3191 }
3192
3193 Ok(Self { type_, fields })
3194 }
3195}
3196
3197const KNOWN_AVAILABLE_COMMAND_INPUT_TYPES: &[&str] = &["text"];
3198
3199fn is_known_available_command_input_type(type_: &str) -> bool {
3200 KNOWN_AVAILABLE_COMMAND_INPUT_TYPES.contains(&type_)
3201}
3202
3203#[cfg(feature = "schemars")]
3204fn other_available_command_input_schema(schema: &mut Schema) {
3205 super::schema_util::reject_known_string_discriminators(
3206 schema,
3207 "type",
3208 KNOWN_AVAILABLE_COMMAND_INPUT_TYPES,
3209 );
3210}
3211
3212#[serde_as]
3214#[skip_serializing_none]
3215#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3216#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3217#[serde(rename_all = "camelCase")]
3218#[non_exhaustive]
3219pub struct TextCommandInput {
3220 pub hint: String,
3222 #[serde_as(deserialize_as = "DefaultOnError")]
3228 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3229 #[serde(default)]
3230 #[serde(rename = "_meta")]
3231 pub meta: Option<Meta>,
3232}
3233
3234impl TextCommandInput {
3235 #[must_use]
3237 pub fn new(hint: impl Into<String>) -> Self {
3238 Self {
3239 hint: hint.into(),
3240 meta: None,
3241 }
3242 }
3243
3244 #[must_use]
3250 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3251 self.meta = meta.into_option();
3252 self
3253 }
3254}
3255
3256#[serde_as]
3264#[skip_serializing_none]
3265#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3266#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3267#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = SESSION_REQUEST_PERMISSION_METHOD_NAME)))]
3268#[serde(rename_all = "camelCase")]
3269#[non_exhaustive]
3270pub struct RequestPermissionRequest {
3271 pub session_id: SessionId,
3273 pub title: String,
3278 #[serde_as(deserialize_as = "DefaultOnError")]
3284 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3285 #[serde(default)]
3286 pub description: Option<String>,
3287 #[serde(default)]
3291 pub subject: Option<RequestPermissionSubject>,
3292 #[cfg_attr(feature = "schemars", schemars(length(min = 1)))]
3295 pub options: Vec<PermissionOption>,
3296 #[serde_as(deserialize_as = "DefaultOnError")]
3302 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3303 #[serde(default)]
3304 #[serde(rename = "_meta")]
3305 pub meta: Option<Meta>,
3306}
3307
3308impl RequestPermissionRequest {
3309 #[must_use]
3311 pub fn new(
3312 session_id: impl Into<SessionId>,
3313 title: impl Into<String>,
3314 options: Vec<PermissionOption>,
3315 ) -> Self {
3316 Self {
3317 session_id: session_id.into(),
3318 title: title.into(),
3319 description: None,
3320 subject: None,
3321 options,
3322 meta: None,
3323 }
3324 }
3325
3326 #[must_use]
3328 pub fn description(mut self, description: impl IntoOption<String>) -> Self {
3329 self.description = description.into_option();
3330 self
3331 }
3332
3333 #[must_use]
3335 pub fn subject(mut self, subject: impl IntoOption<RequestPermissionSubject>) -> Self {
3336 self.subject = subject.into_option();
3337 self
3338 }
3339
3340 #[must_use]
3346 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3347 self.meta = meta.into_option();
3348 self
3349 }
3350}
3351
3352#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3354#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3355#[serde(tag = "type", rename_all = "snake_case")]
3356#[non_exhaustive]
3357pub enum RequestPermissionSubject {
3358 ToolCall(Box<ToolCallPermissionSubject>),
3360 Command(CommandPermissionSubject),
3362 #[serde(untagged)]
3373 Other(OtherRequestPermissionSubject),
3374}
3375
3376impl From<ToolCallPermissionSubject> for RequestPermissionSubject {
3377 fn from(subject: ToolCallPermissionSubject) -> Self {
3378 Self::ToolCall(Box::new(subject))
3379 }
3380}
3381
3382impl From<ToolCallUpdate> for RequestPermissionSubject {
3383 fn from(tool_call: ToolCallUpdate) -> Self {
3384 ToolCallPermissionSubject::new(tool_call).into()
3385 }
3386}
3387
3388impl From<CommandPermissionSubject> for RequestPermissionSubject {
3389 fn from(subject: CommandPermissionSubject) -> Self {
3390 Self::Command(subject)
3391 }
3392}
3393
3394#[serde_as]
3396#[skip_serializing_none]
3397#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3398#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3399#[serde(rename_all = "camelCase")]
3400#[non_exhaustive]
3401pub struct ToolCallPermissionSubject {
3402 pub tool_call: ToolCallUpdate,
3408 #[serde_as(deserialize_as = "DefaultOnError")]
3414 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3415 #[serde(default)]
3416 #[serde(rename = "_meta")]
3417 pub meta: Option<Meta>,
3418}
3419
3420impl ToolCallPermissionSubject {
3421 #[must_use]
3423 pub fn new(tool_call: ToolCallUpdate) -> Self {
3424 Self {
3425 tool_call,
3426 meta: None,
3427 }
3428 }
3429
3430 #[must_use]
3436 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3437 self.meta = meta.into_option();
3438 self
3439 }
3440}
3441
3442#[serde_as]
3444#[skip_serializing_none]
3445#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3446#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3447#[serde(rename_all = "camelCase")]
3448#[non_exhaustive]
3449pub struct CommandPermissionSubject {
3450 pub command: String,
3452 pub cwd: AbsolutePath,
3454 #[serde_as(deserialize_as = "DefaultOnError")]
3456 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3457 #[serde(default)]
3458 pub tool_call_id: Option<ToolCallId>,
3459 #[serde_as(deserialize_as = "DefaultOnError")]
3461 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3462 #[serde(default)]
3463 pub terminal_id: Option<TerminalId>,
3464 #[serde_as(deserialize_as = "DefaultOnError")]
3470 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3471 #[serde(default)]
3472 #[serde(rename = "_meta")]
3473 pub meta: Option<Meta>,
3474}
3475
3476impl CommandPermissionSubject {
3477 #[must_use]
3479 pub fn new(command: impl Into<String>, cwd: impl Into<AbsolutePath>) -> Self {
3480 Self {
3481 command: command.into(),
3482 cwd: cwd.into(),
3483 tool_call_id: None,
3484 terminal_id: None,
3485 meta: None,
3486 }
3487 }
3488
3489 #[must_use]
3491 pub fn tool_call_id(mut self, tool_call_id: impl IntoOption<ToolCallId>) -> Self {
3492 self.tool_call_id = tool_call_id.into_option();
3493 self
3494 }
3495
3496 #[must_use]
3498 pub fn terminal_id(mut self, terminal_id: impl IntoOption<TerminalId>) -> Self {
3499 self.terminal_id = terminal_id.into_option();
3500 self
3501 }
3502
3503 #[must_use]
3505 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3506 self.meta = meta.into_option();
3507 self
3508 }
3509}
3510
3511#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3513#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
3514#[cfg_attr(feature = "schemars", schemars(inline))]
3515#[cfg_attr(feature = "schemars", schemars(transform = other_request_permission_subject_schema))]
3516#[serde(rename_all = "camelCase")]
3517#[non_exhaustive]
3518pub struct OtherRequestPermissionSubject {
3519 #[serde(rename = "type")]
3525 pub type_: String,
3526 #[serde(flatten)]
3528 pub fields: BTreeMap<String, serde_json::Value>,
3529}
3530
3531impl OtherRequestPermissionSubject {
3532 #[must_use]
3534 pub fn new(type_: impl Into<String>, mut fields: BTreeMap<String, serde_json::Value>) -> Self {
3535 fields.remove("type");
3536 Self {
3537 type_: type_.into(),
3538 fields,
3539 }
3540 }
3541}
3542
3543impl<'de> Deserialize<'de> for OtherRequestPermissionSubject {
3544 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
3545 where
3546 D: serde::Deserializer<'de>,
3547 {
3548 let mut fields = BTreeMap::<String, serde_json::Value>::deserialize(deserializer)?;
3549 let type_ = fields
3550 .remove("type")
3551 .ok_or_else(|| serde::de::Error::missing_field("type"))?;
3552 let serde_json::Value::String(type_) = type_ else {
3553 return Err(serde::de::Error::custom("`type` must be a string"));
3554 };
3555
3556 if is_known_request_permission_subject_type(&type_) {
3557 return Err(serde::de::Error::custom(format!(
3558 "known request permission subject `{type_}` did not match its schema"
3559 )));
3560 }
3561
3562 Ok(Self { type_, fields })
3563 }
3564}
3565
3566fn is_known_request_permission_subject_type(type_: &str) -> bool {
3567 matches!(type_, "tool_call" | "command")
3568}
3569
3570#[cfg(feature = "schemars")]
3571fn other_request_permission_subject_schema(schema: &mut Schema) {
3572 super::schema_util::reject_known_string_discriminators(
3573 schema,
3574 "type",
3575 &["tool_call", "command"],
3576 );
3577}
3578
3579#[serde_as]
3581#[skip_serializing_none]
3582#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3583#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3584#[serde(rename_all = "camelCase")]
3585#[non_exhaustive]
3586pub struct PermissionOption {
3587 pub option_id: PermissionOptionId,
3589 pub name: String,
3591 pub kind: PermissionOptionKind,
3593 #[serde_as(deserialize_as = "DefaultOnError")]
3599 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3600 #[serde(default)]
3601 #[serde(rename = "_meta")]
3602 pub meta: Option<Meta>,
3603}
3604
3605impl PermissionOption {
3606 #[must_use]
3608 pub fn new(
3609 option_id: impl Into<PermissionOptionId>,
3610 name: impl Into<String>,
3611 kind: PermissionOptionKind,
3612 ) -> Self {
3613 Self {
3614 option_id: option_id.into(),
3615 name: name.into(),
3616 kind,
3617 meta: None,
3618 }
3619 }
3620
3621 #[must_use]
3627 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3628 self.meta = meta.into_option();
3629 self
3630 }
3631}
3632
3633#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3635#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
3636#[serde(transparent)]
3637#[from(forward)]
3638#[non_exhaustive]
3639pub struct PermissionOptionId(pub Arc<str>);
3640
3641impl PermissionOptionId {
3642 #[must_use]
3644 pub fn new(id: impl Into<Self>) -> Self {
3645 id.into()
3646 }
3647}
3648
3649#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3653#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3654#[serde(rename_all = "snake_case")]
3655#[non_exhaustive]
3656pub enum PermissionOptionKind {
3657 AllowOnce,
3659 AllowAlways,
3661 RejectOnce,
3663 RejectAlways,
3665 #[serde(untagged)]
3671 Other(String),
3672}
3673
3674#[serde_as]
3676#[skip_serializing_none]
3677#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3678#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3679#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = SESSION_REQUEST_PERMISSION_METHOD_NAME)))]
3680#[serde(rename_all = "camelCase")]
3681#[non_exhaustive]
3682pub struct RequestPermissionResponse {
3683 pub outcome: RequestPermissionOutcome,
3685 #[serde_as(deserialize_as = "DefaultOnError")]
3691 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3692 #[serde(default)]
3693 #[serde(rename = "_meta")]
3694 pub meta: Option<Meta>,
3695}
3696
3697impl RequestPermissionResponse {
3698 #[must_use]
3700 pub fn new(outcome: RequestPermissionOutcome) -> Self {
3701 Self {
3702 outcome,
3703 meta: None,
3704 }
3705 }
3706
3707 #[must_use]
3713 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3714 self.meta = meta.into_option();
3715 self
3716 }
3717}
3718
3719#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3721#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3722#[serde(tag = "outcome", rename_all = "snake_case")]
3723#[non_exhaustive]
3724pub enum RequestPermissionOutcome {
3725 Cancelled(CancelledPermissionOutcome),
3736 #[serde(rename_all = "camelCase")]
3741 Selected(SelectedPermissionOutcome),
3742 #[serde(untagged)]
3753 Other(OtherRequestPermissionOutcome),
3754}
3755
3756#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3762#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
3763#[cfg_attr(feature = "schemars", schemars(inline))]
3764#[cfg_attr(feature = "schemars", schemars(transform = other_request_permission_outcome_schema))]
3765#[serde(rename_all = "camelCase")]
3766#[non_exhaustive]
3767pub struct OtherRequestPermissionOutcome {
3768 pub outcome: String,
3774 #[serde(flatten)]
3776 pub fields: BTreeMap<String, serde_json::Value>,
3777}
3778
3779impl OtherRequestPermissionOutcome {
3780 #[must_use]
3782 pub fn new(
3783 outcome: impl Into<String>,
3784 mut fields: BTreeMap<String, serde_json::Value>,
3785 ) -> Self {
3786 fields.remove("outcome");
3787 Self {
3788 outcome: outcome.into(),
3789 fields,
3790 }
3791 }
3792}
3793
3794impl<'de> Deserialize<'de> for OtherRequestPermissionOutcome {
3795 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
3796 where
3797 D: serde::Deserializer<'de>,
3798 {
3799 let mut fields = BTreeMap::<String, serde_json::Value>::deserialize(deserializer)?;
3800 let outcome = fields
3801 .remove("outcome")
3802 .ok_or_else(|| serde::de::Error::missing_field("outcome"))?;
3803 let serde_json::Value::String(outcome) = outcome else {
3804 return Err(serde::de::Error::custom("`outcome` must be a string"));
3805 };
3806
3807 if is_known_request_permission_outcome(&outcome) {
3808 return Err(serde::de::Error::custom(format!(
3809 "known request permission outcome `{outcome}` did not match its schema"
3810 )));
3811 }
3812
3813 Ok(Self { outcome, fields })
3814 }
3815}
3816
3817fn is_known_request_permission_outcome(outcome: &str) -> bool {
3818 matches!(outcome, "cancelled" | "selected")
3819}
3820
3821#[cfg(feature = "schemars")]
3822fn other_request_permission_outcome_schema(schema: &mut Schema) {
3823 super::schema_util::reject_known_string_discriminators(
3824 schema,
3825 "outcome",
3826 &["cancelled", "selected"],
3827 );
3828}
3829
3830#[serde_as]
3832#[skip_serializing_none]
3833#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3834#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3835#[serde(rename_all = "camelCase")]
3836#[non_exhaustive]
3837pub struct CancelledPermissionOutcome {
3838 #[serde_as(deserialize_as = "DefaultOnError")]
3844 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3845 #[serde(default)]
3846 #[serde(rename = "_meta")]
3847 pub meta: Option<Meta>,
3848}
3849
3850impl CancelledPermissionOutcome {
3851 #[must_use]
3853 pub fn new() -> Self {
3854 Self::default()
3855 }
3856
3857 #[must_use]
3863 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3864 self.meta = meta.into_option();
3865 self
3866 }
3867}
3868
3869impl From<CancelledPermissionOutcome> for RequestPermissionOutcome {
3870 fn from(outcome: CancelledPermissionOutcome) -> Self {
3871 Self::Cancelled(outcome)
3872 }
3873}
3874
3875#[serde_as]
3877#[skip_serializing_none]
3878#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3879#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3880#[serde(rename_all = "camelCase")]
3881#[non_exhaustive]
3882pub struct SelectedPermissionOutcome {
3883 pub option_id: PermissionOptionId,
3885 #[serde_as(deserialize_as = "DefaultOnError")]
3891 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3892 #[serde(default)]
3893 #[serde(rename = "_meta")]
3894 pub meta: Option<Meta>,
3895}
3896
3897impl SelectedPermissionOutcome {
3898 #[must_use]
3900 pub fn new(option_id: impl Into<PermissionOptionId>) -> Self {
3901 Self {
3902 option_id: option_id.into(),
3903 meta: None,
3904 }
3905 }
3906
3907 #[must_use]
3913 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3914 self.meta = meta.into_option();
3915 self
3916 }
3917}
3918
3919#[serde_as]
3928#[skip_serializing_none]
3929#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3930#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3931#[serde(rename_all = "camelCase")]
3932#[non_exhaustive]
3933pub struct ClientCapabilities {
3934 #[serde_as(deserialize_as = "DefaultOnError")]
3941 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3942 #[serde(default)]
3943 pub auth: Option<ClientAuthCapabilities>,
3944 #[serde_as(deserialize_as = "DefaultOnError")]
3950 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3951 #[serde(default)]
3952 pub elicitation: Option<ElicitationCapabilities>,
3953 #[cfg(any(
3963 feature = "unstable_prompt_suggestions",
3964 feature = "unstable_agent_skills"
3965 ))]
3966 #[serde_as(deserialize_as = "DefaultOnError")]
3967 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3968 #[serde(default)]
3969 pub session: Option<ClientSessionCapabilities>,
3970
3971 #[serde_as(deserialize_as = "DefaultOnError")]
3977 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3978 #[serde(default)]
3979 #[serde(rename = "_meta")]
3980 pub meta: Option<Meta>,
3981}
3982
3983impl ClientCapabilities {
3984 #[must_use]
3986 pub fn new() -> Self {
3987 Self::default()
3988 }
3989
3990 #[must_use]
3994 pub fn auth(mut self, auth: impl IntoOption<ClientAuthCapabilities>) -> Self {
3995 self.auth = auth.into_option();
3996 self
3997 }
3998
3999 #[must_use]
4002 pub fn elicitation(mut self, elicitation: impl IntoOption<ElicitationCapabilities>) -> Self {
4003 self.elicitation = elicitation.into_option();
4004 self
4005 }
4006
4007 #[cfg(any(
4013 feature = "unstable_prompt_suggestions",
4014 feature = "unstable_agent_skills"
4015 ))]
4016 #[must_use]
4017 pub fn session(mut self, session: impl IntoOption<ClientSessionCapabilities>) -> Self {
4018 self.session = session.into_option();
4019 self
4020 }
4021
4022 #[must_use]
4028 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4029 self.meta = meta.into_option();
4030 self
4031 }
4032}
4033
4034#[cfg(any(
4044 feature = "unstable_prompt_suggestions",
4045 feature = "unstable_agent_skills"
4046))]
4047#[serde_as]
4048#[skip_serializing_none]
4049#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4050#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4051#[serde(rename_all = "camelCase")]
4052#[non_exhaustive]
4053pub struct ClientSessionCapabilities {
4054 #[cfg(feature = "unstable_prompt_suggestions")]
4060 #[serde_as(deserialize_as = "DefaultOnError")]
4061 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4062 #[serde(default)]
4063 pub prompt_suggestions: Option<PromptSuggestionsCapabilities>,
4064 #[cfg(feature = "unstable_agent_skills")]
4069 #[serde_as(deserialize_as = "DefaultOnError")]
4070 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4071 #[serde(default)]
4072 pub commands: Option<CommandsCapabilities>,
4073 #[serde_as(deserialize_as = "DefaultOnError")]
4079 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4080 #[serde(default)]
4081 #[serde(rename = "_meta")]
4082 pub meta: Option<Meta>,
4083}
4084
4085#[cfg(any(
4086 feature = "unstable_prompt_suggestions",
4087 feature = "unstable_agent_skills"
4088))]
4089impl ClientSessionCapabilities {
4090 #[must_use]
4092 pub fn new() -> Self {
4093 Self::default()
4094 }
4095
4096 #[cfg(feature = "unstable_prompt_suggestions")]
4098 #[must_use]
4099 pub fn prompt_suggestions(
4100 mut self,
4101 prompt_suggestions: impl IntoOption<PromptSuggestionsCapabilities>,
4102 ) -> Self {
4103 self.prompt_suggestions = prompt_suggestions.into_option();
4104 self
4105 }
4106
4107 #[cfg(feature = "unstable_agent_skills")]
4109 #[must_use]
4110 pub fn commands(mut self, commands: impl IntoOption<CommandsCapabilities>) -> Self {
4111 self.commands = commands.into_option();
4112 self
4113 }
4114
4115 #[must_use]
4121 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4122 self.meta = meta.into_option();
4123 self
4124 }
4125}
4126
4127#[cfg(feature = "unstable_agent_skills")]
4137#[serde_as]
4138#[skip_serializing_none]
4139#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4140#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4141#[serde(rename_all = "camelCase")]
4142#[non_exhaustive]
4143pub struct CommandsCapabilities {
4144 #[serde_as(deserialize_as = "DefaultOnError")]
4150 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4151 #[serde(default)]
4152 pub skill: Option<CommandsSkillCapabilities>,
4153 #[serde_as(deserialize_as = "DefaultOnError")]
4159 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4160 #[serde(default)]
4161 #[serde(rename = "_meta")]
4162 pub meta: Option<Meta>,
4163}
4164
4165#[cfg(feature = "unstable_agent_skills")]
4166impl CommandsCapabilities {
4167 #[must_use]
4169 pub fn new() -> Self {
4170 Self::default()
4171 }
4172
4173 #[must_use]
4175 pub fn skill(mut self, skill: impl IntoOption<CommandsSkillCapabilities>) -> Self {
4176 self.skill = skill.into_option();
4177 self
4178 }
4179
4180 #[must_use]
4186 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4187 self.meta = meta.into_option();
4188 self
4189 }
4190}
4191
4192#[cfg(feature = "unstable_agent_skills")]
4201#[serde_as]
4202#[skip_serializing_none]
4203#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4204#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4205#[non_exhaustive]
4206pub struct CommandsSkillCapabilities {
4207 #[serde_as(deserialize_as = "DefaultOnError")]
4213 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4214 #[serde(default)]
4215 #[serde(rename = "_meta")]
4216 pub meta: Option<Meta>,
4217}
4218
4219#[cfg(feature = "unstable_agent_skills")]
4220impl CommandsSkillCapabilities {
4221 #[must_use]
4223 pub fn new() -> Self {
4224 Self::default()
4225 }
4226
4227 #[must_use]
4233 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4234 self.meta = meta.into_option();
4235 self
4236 }
4237}
4238
4239#[cfg(feature = "unstable_prompt_suggestions")]
4250#[serde_as]
4251#[skip_serializing_none]
4252#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4253#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4254#[serde(rename_all = "camelCase")]
4255#[non_exhaustive]
4256pub struct PromptSuggestionsCapabilities {
4257 #[serde_as(deserialize_as = "DefaultOnError")]
4262 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4263 #[serde(default)]
4264 pub image: Option<PromptSuggestionsImageCapabilities>,
4265 #[serde_as(deserialize_as = "DefaultOnError")]
4270 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4271 #[serde(default)]
4272 pub audio: Option<PromptSuggestionsAudioCapabilities>,
4273 #[serde_as(deserialize_as = "DefaultOnError")]
4279 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4280 #[serde(default)]
4281 pub embedded_context: Option<PromptSuggestionsEmbeddedContextCapabilities>,
4282 #[serde_as(deserialize_as = "DefaultOnError")]
4288 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4289 #[serde(default)]
4290 #[serde(rename = "_meta")]
4291 pub meta: Option<Meta>,
4292}
4293
4294#[cfg(feature = "unstable_prompt_suggestions")]
4295impl PromptSuggestionsCapabilities {
4296 #[must_use]
4298 pub fn new() -> Self {
4299 Self::default()
4300 }
4301
4302 #[must_use]
4304 pub fn image(mut self, image: impl IntoOption<PromptSuggestionsImageCapabilities>) -> Self {
4305 self.image = image.into_option();
4306 self
4307 }
4308
4309 #[must_use]
4311 pub fn audio(mut self, audio: impl IntoOption<PromptSuggestionsAudioCapabilities>) -> Self {
4312 self.audio = audio.into_option();
4313 self
4314 }
4315
4316 #[must_use]
4318 pub fn embedded_context(
4319 mut self,
4320 embedded_context: impl IntoOption<PromptSuggestionsEmbeddedContextCapabilities>,
4321 ) -> Self {
4322 self.embedded_context = embedded_context.into_option();
4323 self
4324 }
4325
4326 #[must_use]
4332 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4333 self.meta = meta.into_option();
4334 self
4335 }
4336}
4337
4338#[cfg(feature = "unstable_prompt_suggestions")]
4346#[serde_as]
4347#[skip_serializing_none]
4348#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4349#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4350#[non_exhaustive]
4351pub struct PromptSuggestionsImageCapabilities {
4352 #[serde_as(deserialize_as = "DefaultOnError")]
4358 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4359 #[serde(default)]
4360 #[serde(rename = "_meta")]
4361 pub meta: Option<Meta>,
4362}
4363
4364#[cfg(feature = "unstable_prompt_suggestions")]
4365impl PromptSuggestionsImageCapabilities {
4366 #[must_use]
4368 pub fn new() -> Self {
4369 Self::default()
4370 }
4371
4372 #[must_use]
4378 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4379 self.meta = meta.into_option();
4380 self
4381 }
4382}
4383
4384#[cfg(feature = "unstable_prompt_suggestions")]
4392#[serde_as]
4393#[skip_serializing_none]
4394#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4395#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4396#[non_exhaustive]
4397pub struct PromptSuggestionsAudioCapabilities {
4398 #[serde_as(deserialize_as = "DefaultOnError")]
4404 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4405 #[serde(default)]
4406 #[serde(rename = "_meta")]
4407 pub meta: Option<Meta>,
4408}
4409
4410#[cfg(feature = "unstable_prompt_suggestions")]
4411impl PromptSuggestionsAudioCapabilities {
4412 #[must_use]
4414 pub fn new() -> Self {
4415 Self::default()
4416 }
4417
4418 #[must_use]
4424 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4425 self.meta = meta.into_option();
4426 self
4427 }
4428}
4429
4430#[cfg(feature = "unstable_prompt_suggestions")]
4439#[serde_as]
4440#[skip_serializing_none]
4441#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4442#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4443#[non_exhaustive]
4444pub struct PromptSuggestionsEmbeddedContextCapabilities {
4445 #[serde_as(deserialize_as = "DefaultOnError")]
4451 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4452 #[serde(default)]
4453 #[serde(rename = "_meta")]
4454 pub meta: Option<Meta>,
4455}
4456
4457#[cfg(feature = "unstable_prompt_suggestions")]
4458impl PromptSuggestionsEmbeddedContextCapabilities {
4459 #[must_use]
4461 pub fn new() -> Self {
4462 Self::default()
4463 }
4464
4465 #[must_use]
4471 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4472 self.meta = meta.into_option();
4473 self
4474 }
4475}
4476
4477#[serde_as]
4483#[skip_serializing_none]
4484#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4485#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4486#[serde(rename_all = "camelCase")]
4487#[non_exhaustive]
4488pub struct ClientAuthCapabilities {
4489 #[serde_as(deserialize_as = "DefaultOnError")]
4496 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4497 #[serde(default)]
4498 pub terminal: Option<TerminalAuthCapabilities>,
4499 #[serde_as(deserialize_as = "DefaultOnError")]
4505 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4506 #[serde(default)]
4507 #[serde(rename = "_meta")]
4508 pub meta: Option<Meta>,
4509}
4510
4511impl ClientAuthCapabilities {
4512 #[must_use]
4514 pub fn new() -> Self {
4515 Self::default()
4516 }
4517
4518 #[must_use]
4526 pub fn terminal(mut self, terminal: impl IntoOption<TerminalAuthCapabilities>) -> Self {
4527 self.terminal = terminal.into_option();
4528 self
4529 }
4530
4531 #[must_use]
4537 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4538 self.meta = meta.into_option();
4539 self
4540 }
4541}
4542
4543#[serde_as]
4549#[skip_serializing_none]
4550#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4551#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4552#[non_exhaustive]
4553pub struct TerminalAuthCapabilities {
4554 #[serde_as(deserialize_as = "DefaultOnError")]
4560 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4561 #[serde(default)]
4562 #[serde(rename = "_meta")]
4563 pub meta: Option<Meta>,
4564}
4565
4566impl TerminalAuthCapabilities {
4567 #[must_use]
4569 pub fn new() -> Self {
4570 Self::default()
4571 }
4572
4573 #[must_use]
4579 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4580 self.meta = meta.into_option();
4581 self
4582 }
4583}
4584
4585#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4591#[non_exhaustive]
4592pub struct ClientMethodNames {
4593 pub session_request_permission: &'static str,
4595 pub session_update: &'static str,
4597 #[cfg(feature = "unstable_mcp_over_acp")]
4599 pub mcp_message: &'static str,
4600 pub elicitation_create: &'static str,
4602 pub elicitation_complete: &'static str,
4604 #[cfg(feature = "unstable_auth_status")]
4606 pub auth_status_update: &'static str,
4607}
4608
4609pub const CLIENT_METHOD_NAMES: ClientMethodNames = ClientMethodNames {
4611 session_update: SESSION_UPDATE_NOTIFICATION,
4612 session_request_permission: SESSION_REQUEST_PERMISSION_METHOD_NAME,
4613 #[cfg(feature = "unstable_mcp_over_acp")]
4614 mcp_message: MCP_MESSAGE_METHOD_NAME,
4615 elicitation_create: ELICITATION_CREATE_METHOD_NAME,
4616 elicitation_complete: ELICITATION_COMPLETE_NOTIFICATION,
4617 #[cfg(feature = "unstable_auth_status")]
4618 auth_status_update: AUTH_STATUS_UPDATE_NOTIFICATION,
4619};
4620
4621pub(crate) const SESSION_UPDATE_NOTIFICATION: &str = "session/update";
4623pub(crate) const SESSION_REQUEST_PERMISSION_METHOD_NAME: &str = "session/request_permission";
4625pub(crate) const ELICITATION_CREATE_METHOD_NAME: &str = "elicitation/create";
4627pub(crate) const ELICITATION_COMPLETE_NOTIFICATION: &str = "elicitation/complete";
4629#[cfg(feature = "unstable_auth_status")]
4631pub(crate) const AUTH_STATUS_UPDATE_NOTIFICATION: &str = "auth/status_update";
4632
4633#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4640#[derive(Clone, Debug, Serialize, Deserialize)]
4641#[serde(untagged)]
4642#[cfg_attr(feature = "schemars", schemars(inline))]
4643#[non_exhaustive]
4644pub enum AgentRequest {
4645 RequestPermissionRequest(Box<RequestPermissionRequest>),
4657 CreateElicitationRequest(Box<CreateElicitationRequest>),
4661 #[cfg(feature = "unstable_mcp_over_acp")]
4667 MessageMcpRequest(Box<MessageMcpRequest>),
4668 ExtMethodRequest(Box<ExtRequest>),
4676}
4677
4678impl AgentRequest {
4679 #[must_use]
4681 pub fn method(&self) -> &str {
4682 match self {
4683 Self::RequestPermissionRequest(_) => CLIENT_METHOD_NAMES.session_request_permission,
4684 Self::CreateElicitationRequest(_) => CLIENT_METHOD_NAMES.elicitation_create,
4685 #[cfg(feature = "unstable_mcp_over_acp")]
4686 Self::MessageMcpRequest(_) => CLIENT_METHOD_NAMES.mcp_message,
4687 Self::ExtMethodRequest(ext_request) => &ext_request.method,
4688 }
4689 }
4690}
4691
4692#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4699#[derive(Clone, Debug, Serialize, Deserialize)]
4700#[serde(untagged)]
4701#[cfg_attr(feature = "schemars", schemars(inline))]
4702#[non_exhaustive]
4703pub enum ClientResponse {
4704 RequestPermissionResponse(Box<RequestPermissionResponse>),
4706 CreateElicitationResponse(Box<CreateElicitationResponse>),
4708 #[cfg(feature = "unstable_mcp_over_acp")]
4710 MessageMcpResponse(Box<MessageMcpResponse>),
4711 ExtMethodResponse(Box<ExtResponse>),
4713}
4714
4715#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4722#[derive(Clone, Debug, Serialize, Deserialize)]
4723#[serde(untagged)]
4724#[cfg_attr(feature = "schemars", schemars(inline))]
4725#[non_exhaustive]
4726pub enum AgentNotification {
4727 UpdateSessionNotification(Box<UpdateSessionNotification>),
4740 CompleteElicitationNotification(Box<CompleteElicitationNotification>),
4744 #[cfg(feature = "unstable_auth_status")]
4752 AuthStatusUpdateNotification(Box<AuthStatusUpdateNotification>),
4753 ExtNotification(Box<ExtNotification>),
4761}
4762
4763impl AgentNotification {
4764 #[must_use]
4766 pub fn method(&self) -> &str {
4767 match self {
4768 Self::UpdateSessionNotification(_) => CLIENT_METHOD_NAMES.session_update,
4769 Self::CompleteElicitationNotification(_) => CLIENT_METHOD_NAMES.elicitation_complete,
4770 #[cfg(feature = "unstable_auth_status")]
4771 Self::AuthStatusUpdateNotification(_) => CLIENT_METHOD_NAMES.auth_status_update,
4772 Self::ExtNotification(ext_notification) => &ext_notification.method,
4773 }
4774 }
4775}
4776
4777#[cfg(test)]
4778mod tests {
4779
4780 #[test]
4781 fn background_list_round_trips_on_state_updates() {
4782 use serde_json::json;
4783 let idle = super::StateUpdate::Idle(super::IdleStateUpdate::new().background(vec![
4784 super::BackgroundWork::Terminal(super::BackgroundTerminal::new("term_003")),
4785 super::BackgroundWork::ToolCall(super::BackgroundToolCall::new("call_012")),
4786 ]));
4787 let wire = json!({
4788 "state": "idle",
4789 "background": [
4790 { "type": "terminal", "terminalId": "term_003" },
4791 { "type": "tool_call", "toolCallId": "call_012" }
4792 ]
4793 });
4794 assert_eq!(serde_json::to_value(&idle).unwrap(), wire);
4795 assert_eq!(
4796 serde_json::from_value::<super::StateUpdate>(wire).unwrap(),
4797 idle
4798 );
4799
4800 assert_eq!(idle.background().map(<[_]>::len), Some(2));
4801
4802 let empty = super::RunningStateUpdate::new().background(vec![]);
4803 assert_eq!(
4804 serde_json::to_value(&empty).unwrap(),
4805 json!({ "background": [] })
4806 );
4807 assert_eq!(
4808 super::StateUpdate::Running(empty).background(),
4809 Some(&[][..])
4810 );
4811 assert_eq!(
4812 super::StateUpdate::RequiresAction(super::RequiresActionStateUpdate::new())
4813 .background(),
4814 None
4815 );
4816 let custom: super::StateUpdate = serde_json::from_value(json!({
4817 "state": "_waiting",
4818 "background": [{ "type": "terminal", "terminalId": "term_003" }]
4819 }))
4820 .unwrap();
4821 assert_eq!(custom.background(), None);
4822 }
4823
4824 #[test]
4825 fn background_list_keeps_unknown_items_and_drops_malformed_lists() {
4826 use serde_json::json;
4827 let parsed: super::RunningStateUpdate = serde_json::from_value(json!({
4828 "background": [{ "type": "_cron", "schedule": "* * * * *" }]
4829 }))
4830 .unwrap();
4831 let Some([super::BackgroundWork::Other(other)]) = parsed.background.as_deref() else {
4832 panic!("expected one unknown item: {parsed:?}");
4833 };
4834 assert_eq!(other.kind, "_cron");
4835 assert_eq!(other.fields["schedule"], json!("* * * * *"));
4836
4837 for background in [
4838 json!(null),
4839 json!("oops"),
4840 json!([{ "type": "terminal" }]),
4841 json!([{ "type": "tool_call", "toolCallId": "call_1" }, { "type": "terminal", "terminalId": 7 }]),
4842 ] {
4843 let parsed: super::IdleStateUpdate =
4844 serde_json::from_value(json!({ "background": background })).unwrap();
4845 assert_eq!(parsed.background, None, "{background}");
4846 }
4847 }
4848
4849 #[test]
4850 fn replacement_lists_reject_non_arrays_instead_of_clearing() {
4851 use serde_json::json;
4852 for (update, key) in [
4853 ("config_option_update", "configOptions"),
4854 ("available_commands_update", "availableCommands"),
4855 ] {
4856 let empty = json!({ "sessionUpdate": update, key: [] });
4857 serde_json::from_value::<super::SessionUpdate>(empty).unwrap();
4858 for bad in [json!("oops"), json!(null), json!({})] {
4859 let wire = json!({ "sessionUpdate": update, key: bad });
4860 assert!(
4861 serde_json::from_value::<super::SessionUpdate>(wire).is_err(),
4862 "{update} {bad}"
4863 );
4864 }
4865 }
4866 let plan = |entries: serde_json::Value| {
4867 json!({ "sessionUpdate": "plan_update",
4868 "plan": { "type": "items", "planId": "p", "entries": entries } })
4869 };
4870 serde_json::from_value::<super::SessionUpdate>(plan(json!([]))).unwrap();
4871 assert!(serde_json::from_value::<super::SessionUpdate>(plan(json!("oops"))).is_err());
4872 let skipped =
4874 plan(json!([42, { "content": "a", "priority": "high", "status": "pending" }]));
4875 let super::SessionUpdate::PlanUpdate(update) =
4876 serde_json::from_value::<super::SessionUpdate>(skipped).unwrap()
4877 else {
4878 panic!("expected plan_update");
4879 };
4880 let crate::v2::PlanUpdateContent::Items(items) = update.plan else {
4881 panic!("expected items");
4882 };
4883 assert_eq!(items.entries.len(), 1);
4884 }
4885
4886 #[test]
4887 fn other_available_command_preserves_meta_verbatim() {
4888 for meta in [serde_json::json!({ "k": 1 }), serde_json::json!("bad")] {
4889 let wire = serde_json::json!({ "type": "_custom", "name": "c",
4890 "description": "d", "_meta": meta, "extra": true });
4891 let command: super::AvailableCommand = serde_json::from_value(wire.clone()).unwrap();
4892 assert_eq!(command.meta(), meta.as_object());
4893 assert_eq!(serde_json::to_value(&command).unwrap(), wire);
4894 }
4895 }
4896
4897 #[test]
4898 fn cancelled_permission_outcome_wire_format() {
4899 let outcome: RequestPermissionOutcome =
4900 serde_json::from_value(serde_json::json!({ "outcome": "cancelled" })).unwrap();
4901 assert_eq!(outcome, CancelledPermissionOutcome::new().into());
4902 assert_eq!(
4903 serde_json::to_value(&outcome).unwrap(),
4904 serde_json::json!({ "outcome": "cancelled" })
4905 );
4906
4907 let with_meta: RequestPermissionOutcome = CancelledPermissionOutcome::new()
4908 .meta(serde_json::Map::from_iter([(
4909 "k".to_string(),
4910 serde_json::json!(1),
4911 )]))
4912 .into();
4913 let json = serde_json::to_value(&with_meta).unwrap();
4914 assert_eq!(
4915 json,
4916 serde_json::json!({ "outcome": "cancelled", "_meta": { "k": 1 } })
4917 );
4918 assert_eq!(
4919 serde_json::from_value::<RequestPermissionOutcome>(json).unwrap(),
4920 with_meta
4921 );
4922 }
4923
4924 use super::*;
4925
4926 #[test]
4927 fn subagent_update_serializes_as_upsert() {
4928 use serde_json::json;
4929
4930 let announced =
4931 SessionUpdate::SubagentUpdate(SubagentUpdate::new("sess_child_1").capabilities(
4932 SubagentSessionCapabilities::new().cancel(SessionCancelCapabilities::new()),
4933 ));
4934 let wire = json!({
4935 "sessionUpdate": "subagent_update",
4936 "sessionId": "sess_child_1",
4937 "capabilities": { "cancel": {} }
4938 });
4939 assert_eq!(serde_json::to_value(&announced).unwrap(), wire);
4940 assert_eq!(
4941 serde_json::from_value::<SessionUpdate>(wire).unwrap(),
4942 announced
4943 );
4944
4945 let minimal = SubagentUpdate::new("sess_child_1");
4946 assert_eq!(
4947 serde_json::to_value(&minimal).unwrap(),
4948 json!({
4949 "sessionId": "sess_child_1"
4950 })
4951 );
4952 assert!(minimal.capabilities.is_undefined());
4953 assert!(minimal.state.is_undefined());
4954 assert!(minimal.meta.is_undefined());
4955
4956 let cleared_wire = json!({
4958 "sessionId": "sess_child_1",
4959 "capabilities": null,
4960 "state": null,
4961 "_meta": null
4962 });
4963 let cleared: SubagentUpdate = serde_json::from_value(cleared_wire.clone()).unwrap();
4964 assert!(cleared.capabilities.is_null());
4965 assert!(cleared.state.is_null());
4966 assert!(cleared.meta.is_null());
4967 assert_eq!(serde_json::to_value(cleared).unwrap(), cleared_wire);
4968
4969 let revoked: SubagentUpdate = serde_json::from_value(json!({
4970 "sessionId": "sess_child_1",
4971 "capabilities": {}
4972 }))
4973 .unwrap();
4974 assert_eq!(
4975 revoked.capabilities,
4976 MaybeUndefined::Value(SubagentSessionCapabilities::new())
4977 );
4978 assert!(
4979 matches!(revoked.capabilities, MaybeUndefined::Value(ref child) if child.cancel.is_none())
4980 );
4981
4982 assert!(
4983 serde_json::from_value::<SessionUpdate>(json!({
4984 "sessionUpdate": "subagent_update"
4985 }))
4986 .is_err()
4987 );
4988 }
4989
4990 #[test]
4991 fn subagent_cancel_capability_is_optional_object() {
4992 use serde_json::json;
4993
4994 for wire in [
4995 json!({}),
4996 json!({"cancel": null}),
4997 json!({"cancel": true}),
4998 json!({"cancel": false}),
4999 ] {
5000 let child: SubagentSessionCapabilities = serde_json::from_value(wire).unwrap();
5001 assert!(child.cancel.is_none());
5002 assert_eq!(serde_json::to_value(child).unwrap(), json!({}));
5003 }
5004 let enabled = SubagentSessionCapabilities::new().cancel(SessionCancelCapabilities::new());
5005 assert_eq!(
5006 serde_json::to_value(&enabled).unwrap(),
5007 json!({"cancel": {}})
5008 );
5009 assert_eq!(
5010 serde_json::from_value::<SubagentSessionCapabilities>(json!({"cancel": {}})).unwrap(),
5011 enabled
5012 );
5013 let meta: Meta = [("source".into(), json!("worker"))].into_iter().collect();
5014 let with_meta =
5015 SubagentSessionCapabilities::new().cancel(SessionCancelCapabilities::new().meta(meta));
5016 let wire = json!({"cancel": {"_meta": {"source": "worker"}}});
5017 assert_eq!(serde_json::to_value(&with_meta).unwrap(), wire);
5018 assert_eq!(
5019 serde_json::from_value::<SubagentSessionCapabilities>(wire).unwrap(),
5020 with_meta
5021 );
5022 assert!(enabled.cancel.is_some());
5023 assert!(enabled.cancel(None).cancel.is_none());
5024 let removed = SubagentUpdate::new("child").capabilities(SubagentSessionCapabilities::new());
5025 assert_eq!(
5026 serde_json::to_value(removed).unwrap(),
5027 json!({"sessionId": "child", "capabilities": {}})
5028 );
5029 }
5030
5031 #[test]
5032 fn subagent_display_metadata_uses_patch_semantics() {
5033 use serde_json::json;
5034
5035 let update = SubagentUpdate::new("child")
5036 .title("Test investigator".to_string())
5037 .description("Investigates platform-specific test failures.".to_string());
5038 let wire = json!({
5039 "sessionId": "child",
5040 "title": "Test investigator",
5041 "description": "Investigates platform-specific test failures."
5042 });
5043 assert_eq!(serde_json::to_value(&update).unwrap(), wire);
5044 assert_eq!(
5045 serde_json::from_value::<SubagentUpdate>(wire).unwrap(),
5046 update
5047 );
5048
5049 let minimal = SubagentUpdate::new("child");
5050 assert!(minimal.title.is_undefined());
5051 assert!(minimal.description.is_undefined());
5052 assert_eq!(
5053 serde_json::to_value(&minimal).unwrap(),
5054 json!({"sessionId": "child"})
5055 );
5056 let cleared_wire = json!({
5057 "sessionId": "child", "title": null, "description": null
5058 });
5059 let cleared: SubagentUpdate = serde_json::from_value(cleared_wire.clone()).unwrap();
5060 assert!(cleared.title.is_null());
5061 assert!(cleared.description.is_null());
5062 assert_eq!(serde_json::to_value(cleared).unwrap(), cleared_wire);
5063
5064 let title_only: SubagentUpdate = serde_json::from_value(json!({
5065 "sessionId": "child", "title": "Updated title"
5066 }))
5067 .unwrap();
5068 assert_eq!(
5069 title_only.title,
5070 MaybeUndefined::Value("Updated title".to_string())
5071 );
5072 assert!(title_only.description.is_undefined());
5073 let malformed: SubagentUpdate = serde_json::from_value(json!({
5074 "sessionId": "child", "title": false, "description": false
5075 }))
5076 .unwrap();
5077 assert_eq!(malformed, minimal);
5078 }
5079
5080 #[test]
5081 fn subagent_directories_use_strict_patch_semantics() {
5082 use serde_json::json;
5083
5084 let update = SubagentUpdate::new("child")
5085 .cwd("/home/user/project/.worktrees/investigator")
5086 .additional_directories(vec![]);
5087 let wire = json!({
5088 "sessionId": "child",
5089 "cwd": "/home/user/project/.worktrees/investigator",
5090 "additionalDirectories": []
5091 });
5092 assert_eq!(serde_json::to_value(&update).unwrap(), wire);
5093 assert_eq!(
5094 serde_json::from_value::<SubagentUpdate>(wire).unwrap(),
5095 update
5096 );
5097
5098 let inherited: SubagentUpdate =
5099 serde_json::from_value(json!({"sessionId": "child"})).unwrap();
5100 assert!(inherited.cwd.is_undefined());
5101 assert!(inherited.additional_directories.is_undefined());
5102
5103 let cleared_wire = json!({
5104 "sessionId": "child", "cwd": null, "additionalDirectories": null
5105 });
5106 let cleared: SubagentUpdate = serde_json::from_value(cleared_wire.clone()).unwrap();
5107 assert!(cleared.cwd.is_null());
5108 assert!(cleared.additional_directories.is_null());
5109 assert_eq!(serde_json::to_value(cleared).unwrap(), cleared_wire);
5110
5111 for malformed in [
5112 json!({"sessionId": "child", "cwd": false}),
5113 json!({"sessionId": "child", "additionalDirectories": "/tmp/wt"}),
5114 json!({"sessionId": "child", "additionalDirectories": ["/tmp/wt", false]}),
5115 ] {
5116 assert!(
5117 serde_json::from_value::<SubagentUpdate>(malformed.clone()).is_err(),
5118 "{malformed}"
5119 );
5120 }
5121 }
5122
5123 #[test]
5124 fn subagent_notification_keeps_parent_and_child_ids_nested() {
5125 use serde_json::json;
5126
5127 let notification = UpdateSessionNotification::new(
5128 "parent",
5129 SessionUpdate::SubagentUpdate(SubagentUpdate::new("child")),
5130 );
5131 let wire = json!({
5132 "sessionId": "parent",
5133 "update": {
5134 "sessionUpdate": "subagent_update",
5135 "sessionId": "child"
5136 }
5137 });
5138 assert_eq!(serde_json::to_value(¬ification).unwrap(), wire);
5139 assert_eq!(
5140 serde_json::from_value::<UpdateSessionNotification>(wire).unwrap(),
5141 notification
5142 );
5143 for malformed in [
5144 json!({"sessionId": "parent", "update": {"sessionUpdate": "subagent_update"}}),
5145 json!({"update": {"sessionUpdate": "subagent_update", "sessionId": "child"}}),
5146 ] {
5147 assert!(serde_json::from_value::<UpdateSessionNotification>(malformed).is_err());
5148 }
5149 }
5150
5151 #[test]
5152 fn subagent_mirrors_normal_child_state_notifications() {
5153 use serde_json::json;
5154
5155 let association = SubagentUpdate::new("sess_child");
5156 for state in [
5157 StateUpdate::Running(RunningStateUpdate::new()),
5158 StateUpdate::RequiresAction(RequiresActionStateUpdate::new()),
5159 StateUpdate::Unknown(UnknownStateUpdate::new()),
5160 StateUpdate::Running(RunningStateUpdate::new()),
5161 StateUpdate::Idle(IdleStateUpdate::new().stop_reason(StopReason::EndTurn)),
5162 StateUpdate::Running(RunningStateUpdate::new()),
5163 StateUpdate::Idle(IdleStateUpdate::new().stop_reason(StopReason::Cancelled)),
5164 ] {
5165 let child_notification = UpdateSessionNotification::new(
5166 association.session_id.clone(),
5167 SessionUpdate::StateUpdate(state.clone()),
5168 );
5169 let parent_notification = UpdateSessionNotification::new(
5170 "sess_parent",
5171 SessionUpdate::SubagentUpdate(association.clone().state(state)),
5172 );
5173 let child_wire = serde_json::to_value(&child_notification).unwrap();
5174 let parent_wire = serde_json::to_value(&parent_notification).unwrap();
5175 assert_eq!(child_wire["sessionId"], json!("sess_child"));
5176 assert_eq!(child_wire["update"]["sessionUpdate"], json!("state_update"));
5177 assert_eq!(parent_wire["sessionId"], json!("sess_parent"));
5178 assert_eq!(parent_wire["update"]["sessionId"], json!("sess_child"));
5179 let mut child_snapshot = child_wire["update"].clone();
5180 child_snapshot
5181 .as_object_mut()
5182 .unwrap()
5183 .remove("sessionUpdate");
5184 assert_eq!(parent_wire["update"]["state"], child_snapshot);
5185 assert_eq!(
5186 serde_json::from_value::<UpdateSessionNotification>(child_wire).unwrap(),
5187 child_notification
5188 );
5189 assert_eq!(
5190 serde_json::from_value::<UpdateSessionNotification>(parent_wire).unwrap(),
5191 parent_notification
5192 );
5193 }
5194 }
5195
5196 #[test]
5197 fn subagent_state_uses_whole_snapshot_patch_semantics() {
5198 use serde_json::json;
5199
5200 let minimal = SubagentUpdate::new("child");
5201 assert!(minimal.state.is_undefined());
5202 assert_eq!(
5203 serde_json::to_value(&minimal).unwrap(),
5204 json!({"sessionId": "child"})
5205 );
5206
5207 let cleared = minimal.clone().state(None::<StateUpdate>);
5208 assert!(cleared.state.is_null());
5209 assert_eq!(
5210 serde_json::to_value(&cleared).unwrap(),
5211 json!({"sessionId": "child", "state": null})
5212 );
5213 assert_eq!(
5214 serde_json::from_value::<SubagentUpdate>(json!({"sessionId": "child", "state": null}))
5215 .unwrap(),
5216 cleared
5217 );
5218
5219 for snapshot in [
5220 json!({"state": "running", "_meta": {"source": "worker"}}),
5221 json!({"state": "idle", "stopReason": "end_turn"}),
5222 json!({"state": "requires_action"}),
5223 json!({"state": "unknown"}),
5224 json!({"state": "_custom", "detail": {"phase": 2}}),
5225 ] {
5226 let state: StateUpdate = serde_json::from_value(snapshot.clone()).unwrap();
5227 let update = minimal.clone().state(state.clone());
5228 let wire = json!({"sessionId": "child", "state": snapshot});
5229 assert_eq!(serde_json::to_value(&update).unwrap(), wire);
5230 assert_eq!(
5231 serde_json::from_value::<SubagentUpdate>(wire).unwrap(),
5232 update
5233 );
5234 assert_eq!(update.state, MaybeUndefined::Value(state));
5235 }
5236
5237 let idle = SubagentUpdate::new("child").state(StateUpdate::Idle(
5240 IdleStateUpdate::new().stop_reason(StopReason::Cancelled),
5241 ));
5242 let running = idle.state(StateUpdate::Running(RunningStateUpdate::new()));
5243 assert_eq!(
5244 serde_json::to_value(running).unwrap(),
5245 json!({"sessionId": "child", "state": {"state": "running"}})
5246 );
5247 for invalid in [json!(false), json!(42), json!({}), json!({"state": 7})] {
5248 let parsed: SubagentUpdate =
5249 serde_json::from_value(json!({"sessionId": "child", "state": invalid})).unwrap();
5250 assert_eq!(parsed, minimal);
5251 }
5252 }
5253
5254 #[test]
5255 fn unknown_activity_is_a_known_state_update() {
5256 use serde_json::json;
5257
5258 let update = SessionUpdate::StateUpdate(StateUpdate::Unknown(
5259 UnknownStateUpdate::new().meta(
5260 [("source".into(), json!("worker"))]
5261 .into_iter()
5262 .collect::<Meta>(),
5263 ),
5264 ));
5265 let wire = json!({
5266 "sessionUpdate": "state_update",
5267 "state": "unknown",
5268 "_meta": { "source": "worker" }
5269 });
5270 assert_eq!(serde_json::to_value(&update).unwrap(), wire);
5271 assert_eq!(
5272 serde_json::from_value::<SessionUpdate>(wire).unwrap(),
5273 update
5274 );
5275
5276 for meta in [json!(null), json!(false)] {
5277 let state: StateUpdate = serde_json::from_value(json!({
5278 "state": "unknown",
5279 "_meta": meta
5280 }))
5281 .unwrap();
5282 assert_eq!(state, StateUpdate::Unknown(UnknownStateUpdate::new()));
5283 assert_eq!(
5284 serde_json::to_value(state).unwrap(),
5285 json!({"state": "unknown"})
5286 );
5287 }
5288 assert!(serde_json::from_value::<OtherStateUpdate>(json!({"state": "unknown"})).is_err());
5289 }
5290
5291 #[cfg(feature = "schemars")]
5292 #[test]
5293 fn subagent_schema_carries_optional_nullable_state_snapshot() {
5294 use serde_json::json;
5295
5296 let schema = serde_json::to_value(schemars::schema_for!(SubagentUpdate)).unwrap();
5297 let properties = schema["properties"].as_object().unwrap();
5298 assert!(properties.contains_key("sessionId"));
5299 assert!(properties.contains_key("title"));
5300 assert!(properties.contains_key("description"));
5301 assert!(properties.contains_key("capabilities"));
5302 assert!(properties.contains_key("state"));
5303 assert!(properties.contains_key("_meta"));
5304 assert!(!properties.contains_key("name"));
5305 assert!(!properties.contains_key("task"));
5306 assert_eq!(schema["required"], json!(["sessionId"]));
5307 assert_eq!(
5308 properties["state"]["x-deserialize-default-on-error"],
5309 json!(true)
5310 );
5311 let state_variants = properties["state"]["anyOf"].as_array().unwrap();
5312 assert!(state_variants.contains(&json!({"type": "null"})));
5313 assert!(
5314 state_variants
5315 .iter()
5316 .any(|variant| variant["$ref"] == "#/$defs/StateUpdate")
5317 );
5318 let child =
5319 serde_json::to_value(schemars::schema_for!(SubagentSessionCapabilities)).unwrap();
5320 let variants = child["properties"]["cancel"]["anyOf"]
5321 .as_array()
5322 .expect("cancel must allow the capability object or null");
5323 assert!(variants.contains(&json!({"type": "null"})));
5324 assert!(
5325 variants
5326 .iter()
5327 .any(|variant| variant["type"] == "object" || variant.get("$ref").is_some())
5328 );
5329 assert!(!variants.iter().any(|variant| variant["type"] == "boolean"));
5330 let cancel =
5331 serde_json::to_value(schemars::schema_for!(SessionCancelCapabilities)).unwrap();
5332 assert_eq!(cancel["type"], "object");
5333 assert!(
5334 !child["required"]
5335 .as_array()
5336 .is_some_and(|required| required.contains(&json!("cancel")))
5337 );
5338 }
5339
5340 #[test]
5341 fn notice_preserves_wire_shape_nullable_fields_and_open_severity() {
5342 use serde_json::json;
5343
5344 let mut meta = Meta::new();
5345 meta.insert("source".into(), json!("fallback"));
5346 let v2_notice = SessionUpdate::Notice(
5347 Notice::new(NoticeSeverity::Error, "Provider degraded")
5348 .description("Requests may take longer than usual.")
5349 .meta(meta.clone()),
5350 );
5351 let expected = json!({
5352 "sessionUpdate": "notice",
5353 "severity": "error",
5354 "title": "Provider degraded",
5355 "description": "Requests may take longer than usual.",
5356 "_meta": { "source": "fallback" }
5357 });
5358 assert_eq!(serde_json::to_value(&v2_notice).unwrap(), expected);
5359
5360 let v1_notice = crate::v1::SessionUpdate::Notice(
5361 crate::v1::Notice::new(crate::v1::NoticeSeverity::Error, "Provider degraded")
5362 .description("Requests may take longer than usual.")
5363 .meta(meta),
5364 );
5365 assert_eq!(
5366 serde_json::to_value(v2_notice).unwrap(),
5367 serde_json::to_value(v1_notice).unwrap()
5368 );
5369
5370 let SessionUpdate::Notice(notice) = serde_json::from_value(json!({
5371 "sessionUpdate": "notice",
5372 "severity": "critical",
5373 "title": "Provider degraded",
5374 "description": null,
5375 "_meta": null
5376 }))
5377 .unwrap() else {
5378 panic!("expected notice");
5379 };
5380
5381 assert_eq!(
5382 notice.severity,
5383 NoticeSeverity::Other("critical".to_string())
5384 );
5385 assert_eq!(notice.description, None);
5386 assert_eq!(notice.meta, None);
5387 assert_eq!(
5388 serde_json::to_value(SessionUpdate::Notice(notice)).unwrap(),
5389 json!({
5390 "sessionUpdate": "notice",
5391 "severity": "critical",
5392 "title": "Provider degraded"
5393 })
5394 );
5395 }
5396
5397 #[test]
5398 fn malformed_known_notice_is_not_hidden_as_unknown() {
5399 use serde_json::json;
5400
5401 for malformed in [
5402 json!({
5403 "sessionUpdate": "notice",
5404 "severity": "warning",
5405 "title": 42
5406 }),
5407 json!({
5408 "sessionUpdate": "notice",
5409 "severity": 42,
5410 "title": "MCP server unavailable"
5411 }),
5412 json!({
5413 "sessionUpdate": "notice",
5414 "severity": "warning"
5415 }),
5416 json!({
5417 "sessionUpdate": "notice",
5418 "severity": "warning",
5419 "title": null
5420 }),
5421 json!({
5422 "sessionUpdate": "notice",
5423 "title": "MCP server unavailable"
5424 }),
5425 json!({
5426 "sessionUpdate": "notice",
5427 "severity": null,
5428 "title": "MCP server unavailable"
5429 }),
5430 ] {
5431 assert!(serde_json::from_str::<SessionUpdate>(&malformed.to_string()).is_err());
5432 assert!(serde_json::from_value::<SessionUpdate>(malformed).is_err());
5433 }
5434 }
5435
5436 #[test]
5437 fn notice_tolerates_invalid_optional_display_fields_and_custom_severity() {
5438 use serde_json::json;
5439
5440 let wire = json!({
5441 "sessionUpdate": "notice",
5442 "severity": "_custom",
5443 "title": "Provider degraded",
5444 "description": 42,
5445 "_meta": false
5446 });
5447 let SessionUpdate::Notice(notice) = serde_json::from_value(wire.clone()).unwrap() else {
5448 panic!("expected notice");
5449 };
5450 assert_eq!(
5451 serde_json::from_str::<SessionUpdate>(&wire.to_string()).unwrap(),
5452 SessionUpdate::Notice(notice.clone())
5453 );
5454 assert_eq!(notice.severity, NoticeSeverity::Other("_custom".into()));
5455 assert_eq!(notice.description, None);
5456 assert_eq!(notice.meta, None);
5457 assert_eq!(
5458 serde_json::to_value(notice).unwrap(),
5459 json!({"severity": "_custom", "title": "Provider degraded"})
5460 );
5461 }
5462
5463 #[cfg(feature = "schemars")]
5464 #[test]
5465 fn notice_schema_preserves_required_fields_and_excludes_unknown_fallback() {
5466 use serde_json::json;
5467
5468 let schema = serde_json::to_value(schemars::schema_for!(Notice)).unwrap();
5469 assert_eq!(schema["required"], json!(["severity", "title"]));
5470 assert_eq!(schema["properties"]["title"]["minLength"], 1);
5471 for field in ["description", "_meta"] {
5472 assert!(
5473 schema["properties"][field]["type"]
5474 .as_array()
5475 .unwrap()
5476 .contains(&json!("null"))
5477 );
5478 }
5479 let fallback = serde_json::to_value(schemars::schema_for!(OtherSessionUpdate)).unwrap();
5480 assert!(
5481 fallback["not"]["anyOf"]
5482 .as_array()
5483 .unwrap()
5484 .iter()
5485 .any(|variant| variant["properties"]["sessionUpdate"]["const"] == "notice")
5486 );
5487 }
5488
5489 #[test]
5490 fn replay_complete_round_trips_with_and_without_meta() {
5491 use serde_json::json;
5492
5493 let bare = json!({ "sessionUpdate": "replay_complete" });
5494 assert_eq!(
5495 serde_json::to_value(SessionUpdate::ReplayComplete(ReplayComplete::new())).unwrap(),
5496 bare
5497 );
5498 assert_eq!(
5499 serde_json::from_value::<SessionUpdate>(bare).unwrap(),
5500 SessionUpdate::ReplayComplete(ReplayComplete::new())
5501 );
5502
5503 let mut meta = Meta::new();
5504 meta.insert("source".into(), json!("transcript"));
5505 let with_meta = json!({
5506 "sessionUpdate": "replay_complete",
5507 "_meta": { "source": "transcript" }
5508 });
5509 let update = SessionUpdate::ReplayComplete(ReplayComplete::new().meta(meta));
5510 assert_eq!(serde_json::to_value(&update).unwrap(), with_meta);
5511 assert_eq!(
5512 serde_json::from_value::<SessionUpdate>(with_meta).unwrap(),
5513 update
5514 );
5515 }
5516
5517 #[test]
5518 fn replay_complete_is_never_preserved_as_an_unknown_update() {
5519 use serde_json::json;
5520
5521 for wire in [
5525 json!({ "sessionUpdate": "replay_complete", "_meta": null }),
5526 json!({ "sessionUpdate": "replay_complete", "_meta": false }),
5527 json!({ "sessionUpdate": "replay_complete", "futureField": 1 }),
5528 ] {
5529 assert_eq!(
5530 serde_json::from_str::<SessionUpdate>(&wire.to_string()).unwrap(),
5531 SessionUpdate::ReplayComplete(ReplayComplete::new())
5532 );
5533 assert_eq!(
5534 serde_json::from_value::<SessionUpdate>(wire).unwrap(),
5535 SessionUpdate::ReplayComplete(ReplayComplete::new())
5536 );
5537 }
5538
5539 assert!(
5540 serde_json::from_value::<OtherSessionUpdate>(
5541 json!({ "sessionUpdate": "replay_complete" })
5542 )
5543 .is_err()
5544 );
5545 }
5546
5547 #[cfg(feature = "schemars")]
5548 #[test]
5549 fn replay_complete_schema_has_only_optional_meta_and_excludes_unknown_fallback() {
5550 use serde_json::json;
5551
5552 let schema = serde_json::to_value(schemars::schema_for!(ReplayComplete)).unwrap();
5553 assert!(schema.get("required").is_none());
5554 assert_eq!(
5555 schema["properties"]
5556 .as_object()
5557 .unwrap()
5558 .keys()
5559 .collect::<Vec<_>>(),
5560 ["_meta"]
5561 );
5562 assert_eq!(
5563 schema["properties"]["_meta"]["type"],
5564 json!(["object", "null"])
5565 );
5566 let fallback = serde_json::to_value(schemars::schema_for!(OtherSessionUpdate)).unwrap();
5567 assert!(
5568 fallback["not"]["anyOf"]
5569 .as_array()
5570 .unwrap()
5571 .iter()
5572 .any(|variant| variant["properties"]["sessionUpdate"]["const"]
5573 == "replay_complete")
5574 );
5575 }
5576
5577 #[cfg(feature = "unstable_prompt_suggestions")]
5578 #[test]
5579 fn prompt_suggestions_update_round_trips_prompt_content_and_meta() {
5580 use super::{ContentBlock, Meta, PromptSuggestion, PromptSuggestionsUpdate, SessionUpdate};
5581 use crate::v2::{ResourceLink, TextContent};
5582 use serde_json::json;
5583
5584 let mut meta = Meta::new();
5585 meta.insert("rank".into(), json!(1));
5586 let update = SessionUpdate::PromptSuggestionsUpdate(PromptSuggestionsUpdate::new(vec![
5587 PromptSuggestion::new(vec![ContentBlock::Text(TextContent::new(
5588 "Run the test suite and fix what breaks",
5589 ))])
5590 .meta(meta),
5591 PromptSuggestion::new(vec![
5592 ContentBlock::Text(TextContent::new("Add tests for ")),
5593 ContentBlock::ResourceLink(ResourceLink::new(
5594 "parser.rs",
5595 "file:///home/user/project/src/parser.rs",
5596 )),
5597 ]),
5598 ]));
5599 let wire = json!({
5600 "sessionUpdate": "prompt_suggestions_update",
5601 "suggestions": [
5602 {
5603 "prompt": [
5604 { "type": "text", "text": "Run the test suite and fix what breaks" }
5605 ],
5606 "_meta": { "rank": 1 }
5607 },
5608 {
5609 "prompt": [
5610 { "type": "text", "text": "Add tests for " },
5611 {
5612 "type": "resource_link",
5613 "name": "parser.rs",
5614 "uri": "file:///home/user/project/src/parser.rs"
5615 }
5616 ]
5617 }
5618 ]
5619 });
5620 assert_eq!(serde_json::to_value(&update).unwrap(), wire);
5621 assert_eq!(
5622 serde_json::from_value::<SessionUpdate>(wire).unwrap(),
5623 update
5624 );
5625 }
5626
5627 #[cfg(feature = "unstable_prompt_suggestions")]
5628 #[test]
5629 fn prompt_suggestions_update_with_an_empty_list_withdraws_suggestions() {
5630 use super::{PromptSuggestionsUpdate, SessionUpdate};
5631 use serde_json::json;
5632
5633 let update = SessionUpdate::PromptSuggestionsUpdate(PromptSuggestionsUpdate::new(vec![]));
5634 let wire = json!({
5635 "sessionUpdate": "prompt_suggestions_update",
5636 "suggestions": []
5637 });
5638 assert_eq!(serde_json::to_value(&update).unwrap(), wire);
5639 assert_eq!(
5640 serde_json::from_value::<SessionUpdate>(wire).unwrap(),
5641 update
5642 );
5643 }
5644
5645 #[cfg(feature = "unstable_prompt_suggestions")]
5646 #[test]
5647 fn prompt_suggestions_update_is_never_preserved_as_an_unknown_update() {
5648 use super::{OtherSessionUpdate, SessionUpdate};
5649 use serde_json::json;
5650
5651 for wire in [
5654 json!({ "sessionUpdate": "prompt_suggestions_update" }),
5655 json!({ "sessionUpdate": "prompt_suggestions_update", "suggestions": null }),
5656 json!({ "sessionUpdate": "prompt_suggestions_update", "suggestions": "none" }),
5657 json!({ "sessionUpdate": "prompt_suggestions_update", "suggestions": { "prompt": [] } }),
5658 ] {
5659 assert!(serde_json::from_str::<SessionUpdate>(&wire.to_string()).is_err());
5660 assert!(serde_json::from_value::<SessionUpdate>(wire).is_err());
5661 }
5662
5663 assert!(
5664 serde_json::from_value::<OtherSessionUpdate>(json!({
5665 "sessionUpdate": "prompt_suggestions_update",
5666 "suggestions": []
5667 }))
5668 .is_err()
5669 );
5670 }
5671
5672 #[cfg(feature = "unstable_prompt_suggestions")]
5673 #[test]
5674 fn prompt_suggestions_update_skips_whole_suggestions_it_cannot_parse() {
5675 use super::{ContentBlock, PromptSuggestion, PromptSuggestionsUpdate, SessionUpdate};
5676 use crate::v2::TextContent;
5677 use serde_json::json;
5678
5679 let text =
5680 |text: &str| PromptSuggestion::new(vec![ContentBlock::Text(TextContent::new(text))]);
5681
5682 let update: SessionUpdate = serde_json::from_value(json!({
5685 "sessionUpdate": "prompt_suggestions_update",
5686 "suggestions": [
5687 { "prompt": [{ "type": "text", "text": "Keep the first" }] },
5688 { "text": "A suggestion without a prompt" },
5689 { "prompt": "Not a list" },
5690 { "prompt": [{ "type": "text", "text": "Open " }, { "type": "text" }] },
5691 "not an object",
5692 { "prompt": [{ "type": "text", "text": "Keep the last" }], "_meta": false }
5693 ]
5694 }))
5695 .unwrap();
5696
5697 assert_eq!(
5698 update,
5699 SessionUpdate::PromptSuggestionsUpdate(PromptSuggestionsUpdate::new(vec![
5700 text("Keep the first"),
5701 text("Keep the last"),
5702 ]))
5703 );
5704 }
5705
5706 #[cfg(feature = "unstable_prompt_suggestions")]
5707 #[test]
5708 fn prompt_suggestions_update_preserves_custom_and_future_content_blocks() {
5709 use super::{ContentBlock, SessionUpdate};
5710 use serde_json::json;
5711
5712 let wire = json!({
5715 "sessionUpdate": "prompt_suggestions_update",
5716 "suggestions": [
5717 { "prompt": [{ "type": "_hologram", "data": "AAAA" }] }
5718 ]
5719 });
5720 let update: SessionUpdate = serde_json::from_value(wire.clone()).unwrap();
5721 let SessionUpdate::PromptSuggestionsUpdate(suggestions) = &update else {
5722 panic!("expected prompt_suggestions_update, got {update:?}");
5723 };
5724 assert!(matches!(
5725 suggestions.suggestions[0].prompt.as_slice(),
5726 [ContentBlock::Other(_)]
5727 ));
5728 assert_eq!(serde_json::to_value(&update).unwrap(), wire);
5729 }
5730
5731 #[cfg(feature = "unstable_prompt_suggestions")]
5732 #[test]
5733 fn prompt_suggestions_capability_advertises_support_and_content_types() {
5734 use super::{
5735 ClientCapabilities, ClientSessionCapabilities, PromptSuggestionsAudioCapabilities,
5736 PromptSuggestionsCapabilities, PromptSuggestionsEmbeddedContextCapabilities,
5737 PromptSuggestionsImageCapabilities,
5738 };
5739 use serde_json::json;
5740
5741 let capabilities = ClientCapabilities::new().session(
5742 ClientSessionCapabilities::new()
5743 .prompt_suggestions(PromptSuggestionsCapabilities::new()),
5744 );
5745 let value = serde_json::to_value(&capabilities).unwrap();
5746 assert_eq!(value, json!({ "session": { "promptSuggestions": {} } }));
5747 assert_eq!(
5748 serde_json::from_value::<ClientCapabilities>(value).unwrap(),
5749 capabilities
5750 );
5751
5752 let content_types = PromptSuggestionsCapabilities::new()
5753 .image(PromptSuggestionsImageCapabilities::new())
5754 .audio(PromptSuggestionsAudioCapabilities::new())
5755 .embedded_context(PromptSuggestionsEmbeddedContextCapabilities::new());
5756 let wire = json!({ "image": {}, "audio": {}, "embeddedContext": {} });
5757 assert_eq!(serde_json::to_value(&content_types).unwrap(), wire);
5758 assert_eq!(
5759 serde_json::from_value::<PromptSuggestionsCapabilities>(wire).unwrap(),
5760 content_types
5761 );
5762
5763 for unsupported in [
5765 json!({}),
5766 json!({ "session": null }),
5767 json!({ "session": {} }),
5768 json!({ "session": { "promptSuggestions": null } }),
5769 json!({ "session": { "promptSuggestions": false } }),
5770 json!({ "session": { "promptSuggestions": true } }),
5771 json!({ "session": { "promptSuggestions": "supported" } }),
5772 ] {
5773 let capabilities: ClientCapabilities = serde_json::from_value(unsupported).unwrap();
5774 assert!(
5775 capabilities
5776 .session
5777 .and_then(|session| session.prompt_suggestions)
5778 .is_none()
5779 );
5780 }
5781
5782 assert_eq!(
5785 serde_json::from_value::<PromptSuggestionsCapabilities>(json!({
5786 "image": true,
5787 "audio": null,
5788 "embeddedContext": {}
5789 }))
5790 .unwrap(),
5791 PromptSuggestionsCapabilities::new()
5792 .embedded_context(PromptSuggestionsEmbeddedContextCapabilities::new())
5793 );
5794 }
5795
5796 #[cfg(all(feature = "schemars", feature = "unstable_prompt_suggestions"))]
5797 #[test]
5798 fn prompt_suggestions_schema_requires_the_list_and_excludes_unknown_fallback() {
5799 use super::{
5800 ClientCapabilities, ClientSessionCapabilities, OtherSessionUpdate, PromptSuggestion,
5801 PromptSuggestionsCapabilities, PromptSuggestionsUpdate,
5802 };
5803 use serde_json::json;
5804
5805 let update = serde_json::to_value(schemars::schema_for!(PromptSuggestionsUpdate)).unwrap();
5806 assert_eq!(update["required"], json!(["suggestions"]));
5807 assert_eq!(update["properties"]["suggestions"]["type"], "array");
5808
5809 let suggestion = serde_json::to_value(schemars::schema_for!(PromptSuggestion)).unwrap();
5810 assert_eq!(suggestion["required"], json!(["prompt"]));
5811 assert_eq!(suggestion["properties"]["prompt"]["type"], "array");
5812 assert_eq!(suggestion["properties"]["prompt"]["minItems"], 1);
5813
5814 let fallback = serde_json::to_value(schemars::schema_for!(OtherSessionUpdate)).unwrap();
5815 assert!(
5816 fallback["not"]["anyOf"]
5817 .as_array()
5818 .unwrap()
5819 .iter()
5820 .any(|variant| variant["properties"]["sessionUpdate"]["const"]
5821 == "prompt_suggestions_update")
5822 );
5823
5824 for (schema, field) in [
5825 (
5826 serde_json::to_value(schemars::schema_for!(ClientCapabilities)).unwrap(),
5827 "session",
5828 ),
5829 (
5830 serde_json::to_value(schemars::schema_for!(ClientSessionCapabilities)).unwrap(),
5831 "promptSuggestions",
5832 ),
5833 ] {
5834 assert!(
5835 schema["properties"][field]["anyOf"]
5836 .as_array()
5837 .unwrap()
5838 .contains(&json!({"type": "null"}))
5839 );
5840 assert!(
5841 !schema["required"]
5842 .as_array()
5843 .is_some_and(|required| required.contains(&json!(field)))
5844 );
5845 }
5846
5847 let content_types =
5848 serde_json::to_value(schemars::schema_for!(PromptSuggestionsCapabilities)).unwrap();
5849 assert!(content_types.get("required").is_none());
5850 for field in ["image", "audio", "embeddedContext"] {
5851 assert!(
5852 content_types["properties"][field]["anyOf"]
5853 .as_array()
5854 .unwrap()
5855 .contains(&json!({"type": "null"}))
5856 );
5857 }
5858 }
5859
5860 #[test]
5861 fn compaction_updates_preserve_patch_and_open_status_semantics() {
5862 use serde_json::json;
5863
5864 assert_eq!(
5865 serde_json::to_value(SessionUpdate::CompactionUpdate(
5866 CompactionUpdate::new("cmp_001", CompactionStatus::Completed).summary(vec![
5867 ContentBlock::Text(crate::v2::TextContent::new("retained")),
5868 ]),
5869 ))
5870 .unwrap(),
5871 json!({
5872 "sessionUpdate": "compaction_update",
5873 "compactionId": "cmp_001",
5874 "status": "completed",
5875 "summary": [{ "type": "text", "text": "retained" }]
5876 })
5877 );
5878
5879 let SessionUpdate::CompactionUpdate(update) = serde_json::from_value(json!({
5880 "sessionUpdate": "compaction_update",
5881 "compactionId": "cmp_001",
5882 "status": "paused",
5883 "summary": null
5884 }))
5885 .unwrap() else {
5886 panic!("expected compaction update");
5887 };
5888 assert_eq!(update.status, CompactionStatus::Other("paused".into()));
5889 assert!(update.summary.is_null());
5890 assert!(update.error.is_undefined());
5891 }
5892
5893 #[test]
5894 fn malformed_known_compaction_update_is_not_hidden_as_unknown() {
5895 use serde_json::json;
5896
5897 assert!(
5898 serde_json::from_value::<SessionUpdate>(json!({
5899 "sessionUpdate": "compaction_update",
5900 "status": "completed"
5901 }))
5902 .is_err()
5903 );
5904 assert!(
5905 serde_json::from_value::<SessionUpdate>(json!({
5906 "sessionUpdate": "compaction_summary_chunk",
5907 "compactionId": "cmp_001"
5908 }))
5909 .is_err()
5910 );
5911 }
5912
5913 #[test]
5914 fn test_elicitation_capability_semantics() {
5915 use serde_json::json;
5916
5917 let unsupported: ClientCapabilities = serde_json::from_value(json!({})).unwrap();
5918 assert!(unsupported.elicitation.is_none());
5919
5920 let null: ClientCapabilities =
5921 serde_json::from_value(json!({ "elicitation": null })).unwrap();
5922 assert!(null.elicitation.is_none());
5923
5924 let malformed: ClientCapabilities =
5925 serde_json::from_value(json!({ "elicitation": false })).unwrap();
5926 assert!(malformed.elicitation.is_none());
5927
5928 let empty: ClientCapabilities =
5929 serde_json::from_value(json!({ "elicitation": {} })).unwrap();
5930 let empty = empty.elicitation.expect("present capability");
5931 assert!(!empty.supports_form());
5932 assert!(!empty.supports_url());
5933
5934 let form_only: ClientCapabilities = serde_json::from_value(json!({
5935 "elicitation": { "form": {} }
5936 }))
5937 .unwrap();
5938 let form_only = form_only.elicitation.expect("advertised capability");
5939 assert!(form_only.supports_form());
5940 assert!(!form_only.supports_url());
5941
5942 let url_only: ClientCapabilities = serde_json::from_value(json!({
5943 "elicitation": { "url": {} }
5944 }))
5945 .unwrap();
5946 let url_only = url_only.elicitation.expect("advertised capability");
5947 assert!(!url_only.supports_form());
5948 assert!(url_only.supports_url());
5949
5950 let both: ClientCapabilities = serde_json::from_value(json!({
5951 "elicitation": { "form": {}, "url": {} }
5952 }))
5953 .unwrap();
5954 let both = both.elicitation.expect("advertised capability");
5955 assert!(both.supports_form());
5956 assert!(both.supports_url());
5957 }
5958
5959 #[test]
5960 fn test_elicitation_method_routing_and_envelopes() {
5961 use serde_json::json;
5962
5963 assert_eq!(CLIENT_METHOD_NAMES.elicitation_create, "elicitation/create");
5964 assert_eq!(
5965 CLIENT_METHOD_NAMES.elicitation_complete,
5966 "elicitation/complete"
5967 );
5968
5969 let request =
5970 AgentRequest::CreateElicitationRequest(Box::new(CreateElicitationRequest::new(
5971 crate::v2::ElicitationFormMode::new(
5972 crate::v2::ElicitationSessionScope::new("sess_1"),
5973 crate::v2::ElicitationSchema::new(),
5974 ),
5975 "Choose a value",
5976 )));
5977 assert_eq!(request.method(), "elicitation/create");
5978 let method = Arc::from(request.method());
5979 let request = crate::v2::JsonRpcMessage::wrap(crate::v2::Request {
5980 id: crate::v2::RequestId::Number(7),
5981 method,
5982 params: Some(request),
5983 });
5984 assert_eq!(
5985 serde_json::to_value(request).unwrap(),
5986 json!({
5987 "jsonrpc": "2.0",
5988 "id": 7,
5989 "method": "elicitation/create",
5990 "params": {
5991 "mode": "form",
5992 "sessionId": "sess_1",
5993 "message": "Choose a value",
5994 "requestedSchema": { "type": "object", "properties": {} }
5995 }
5996 })
5997 );
5998
5999 let notification = AgentNotification::CompleteElicitationNotification(Box::new(
6000 CompleteElicitationNotification::new("elic_1"),
6001 ));
6002 assert_eq!(notification.method(), "elicitation/complete");
6003 let method = Arc::from(notification.method());
6004 let notification = crate::v2::JsonRpcMessage::wrap(crate::v2::Notification {
6005 method,
6006 params: Some(notification),
6007 });
6008 assert_eq!(
6009 serde_json::to_value(notification).unwrap(),
6010 json!({
6011 "jsonrpc": "2.0",
6012 "method": "elicitation/complete",
6013 "params": { "elicitationId": "elic_1" }
6014 })
6015 );
6016 }
6017
6018 #[test]
6019 fn test_client_capabilities_auth_defaults_on_malformed_value() {
6020 use serde_json::json;
6021
6022 let capabilities: ClientCapabilities = serde_json::from_value(json!({
6023 "auth": false
6024 }))
6025 .unwrap();
6026
6027 assert_eq!(capabilities.auth, None);
6028 }
6029
6030 #[test]
6031 fn test_serialization_behavior() {
6032 use serde_json::json;
6033
6034 assert_eq!(
6035 serde_json::from_value::<SessionInfoUpdate>(json!({})).unwrap(),
6036 SessionInfoUpdate {
6037 title: MaybeUndefined::Undefined,
6038 updated_at: MaybeUndefined::Undefined,
6039 meta: MaybeUndefined::Undefined
6040 }
6041 );
6042 assert_eq!(
6043 serde_json::from_value::<SessionInfoUpdate>(json!({"title": null, "updatedAt": null}))
6044 .unwrap(),
6045 SessionInfoUpdate {
6046 title: MaybeUndefined::Null,
6047 updated_at: MaybeUndefined::Null,
6048 meta: MaybeUndefined::Undefined
6049 }
6050 );
6051 assert_eq!(
6052 serde_json::from_value::<SessionInfoUpdate>(
6053 json!({"title": "title", "updatedAt": "timestamp"})
6054 )
6055 .unwrap(),
6056 SessionInfoUpdate {
6057 title: MaybeUndefined::Value("title".to_string()),
6058 updated_at: MaybeUndefined::Value("timestamp".to_string()),
6059 meta: MaybeUndefined::Undefined
6060 }
6061 );
6062
6063 let clear_meta =
6064 serde_json::from_value::<SessionInfoUpdate>(json!({"_meta": null})).unwrap();
6065 assert_eq!(clear_meta.meta, MaybeUndefined::Null);
6066
6067 let mut meta = Meta::new();
6068 meta.insert("source".to_string(), json!("session-info"));
6069
6070 assert_eq!(
6071 serde_json::from_value::<SessionInfoUpdate>(json!({"_meta": {
6072 "source": "session-info"
6073 }}))
6074 .unwrap()
6075 .meta,
6076 MaybeUndefined::Value(meta.clone())
6077 );
6078
6079 assert_eq!(
6080 serde_json::to_value(SessionInfoUpdate::new()).unwrap(),
6081 json!({})
6082 );
6083
6084 assert_eq!(
6085 serde_json::to_value(SessionInfoUpdate::new().meta(None::<Meta>)).unwrap(),
6086 json!({"_meta": null})
6087 );
6088
6089 assert_eq!(
6090 serde_json::to_value(SessionInfoUpdate::new().meta(meta)).unwrap(),
6091 json!({"_meta": {
6092 "source": "session-info"
6093 }})
6094 );
6095 assert_eq!(
6096 serde_json::to_value(SessionInfoUpdate::new().title("title")).unwrap(),
6097 json!({"title": "title"})
6098 );
6099 assert_eq!(
6100 serde_json::to_value(SessionInfoUpdate::new().title(None)).unwrap(),
6101 json!({"title": null})
6102 );
6103 assert_eq!(
6104 serde_json::to_value(
6105 SessionInfoUpdate::new()
6106 .title("title")
6107 .title(MaybeUndefined::Undefined)
6108 )
6109 .unwrap(),
6110 json!({})
6111 );
6112 }
6113
6114 #[test]
6115 fn test_content_chunk_message_id_serialization() {
6116 use serde_json::json;
6117
6118 assert_eq!(
6119 serde_json::to_value(SessionUpdate::AgentMessageChunk(ContentChunk::new(
6120 ContentBlock::Text(crate::v2::TextContent::new("Hello")),
6121 "msg_agent_c42b9",
6122 )))
6123 .unwrap(),
6124 json!({
6125 "sessionUpdate": "agent_message_chunk",
6126 "messageId": "msg_agent_c42b9",
6127 "content": {
6128 "type": "text",
6129 "text": "Hello"
6130 }
6131 })
6132 );
6133
6134 let err = serde_json::from_value::<ContentChunk>(json!({
6135 "content": {
6136 "type": "text",
6137 "text": "Hello"
6138 }
6139 }))
6140 .unwrap_err();
6141
6142 assert!(err.to_string().contains("messageId"), "{err}");
6143 }
6144
6145 #[test]
6146 fn test_tool_call_content_chunk_serialization() {
6147 use serde_json::json;
6148
6149 assert_eq!(
6150 serde_json::to_value(SessionUpdate::ToolCallContentChunk(
6151 ToolCallContentChunk::new(
6152 "call_001",
6153 crate::v2::ContentBlock::Text(crate::v2::TextContent::new("partial output")),
6154 )
6155 ))
6156 .unwrap(),
6157 json!({
6158 "sessionUpdate": "tool_call_content_chunk",
6159 "toolCallId": "call_001",
6160 "content": {
6161 "type": "content",
6162 "content": {
6163 "type": "text",
6164 "text": "partial output"
6165 }
6166 }
6167 })
6168 );
6169
6170 let err = serde_json::from_value::<ToolCallContentChunk>(json!({
6171 "content": {
6172 "type": "content",
6173 "content": {
6174 "type": "text",
6175 "text": "partial output"
6176 }
6177 }
6178 }))
6179 .unwrap_err();
6180
6181 assert!(err.to_string().contains("toolCallId"), "{err}");
6182 }
6183
6184 #[test]
6185 fn test_full_message_serialization() {
6186 use serde_json::json;
6187
6188 assert_eq!(
6189 serde_json::to_value(SessionUpdate::UserMessage(
6190 UserMessage::new("msg_user_8f7a1").content(vec![ContentBlock::Text(
6191 crate::v2::TextContent::new("Hello")
6192 )])
6193 ))
6194 .unwrap(),
6195 json!({
6196 "sessionUpdate": "user_message",
6197 "messageId": "msg_user_8f7a1",
6198 "content": [
6199 {
6200 "type": "text",
6201 "text": "Hello"
6202 }
6203 ]
6204 })
6205 );
6206
6207 assert_eq!(
6208 serde_json::to_value(SessionUpdate::AgentMessage(
6209 AgentMessage::new("msg_agent_c42b9").content(vec![ContentBlock::Text(
6210 crate::v2::TextContent::new("Hello")
6211 )])
6212 ))
6213 .unwrap(),
6214 json!({
6215 "sessionUpdate": "agent_message",
6216 "messageId": "msg_agent_c42b9",
6217 "content": [
6218 {
6219 "type": "text",
6220 "text": "Hello"
6221 }
6222 ]
6223 })
6224 );
6225
6226 assert_eq!(
6227 serde_json::to_value(SessionUpdate::AgentThought(
6228 AgentThought::new("msg_thought_a12").content(vec![ContentBlock::Text(
6229 crate::v2::TextContent::new("Need to inspect the call sites first.")
6230 )])
6231 ))
6232 .unwrap(),
6233 json!({
6234 "sessionUpdate": "agent_thought",
6235 "messageId": "msg_thought_a12",
6236 "content": [
6237 {
6238 "type": "text",
6239 "text": "Need to inspect the call sites first."
6240 }
6241 ]
6242 })
6243 );
6244 }
6245
6246 #[test]
6247 fn test_message_upsert_serialization() {
6248 use serde_json::json;
6249
6250 assert_eq!(
6251 serde_json::to_value(SessionUpdate::UserMessage(
6252 UserMessage::new("msg_empty").content(Vec::<ContentBlock>::new())
6253 ))
6254 .unwrap(),
6255 json!({
6256 "sessionUpdate": "user_message",
6257 "messageId": "msg_empty",
6258 "content": []
6259 })
6260 );
6261
6262 let empty = serde_json::from_value::<UserMessage>(json!({
6263 "messageId": "msg_empty",
6264 "content": []
6265 }))
6266 .unwrap();
6267 assert!(matches!(
6268 empty.content,
6269 MaybeUndefined::Value(ref content) if content.is_empty()
6270 ));
6271
6272 let patch = serde_json::from_value::<AgentMessage>(json!({
6273 "messageId": "msg_agent_c42b9"
6274 }))
6275 .unwrap();
6276 assert_eq!(patch.content, MaybeUndefined::Undefined);
6277 assert_eq!(patch.meta, MaybeUndefined::Undefined);
6278
6279 let malformed_meta = serde_json::from_value::<AgentMessage>(json!({
6280 "messageId": "msg_agent_c42b9",
6281 "_meta": false
6282 }))
6283 .unwrap();
6284 assert_eq!(malformed_meta.meta, MaybeUndefined::Undefined);
6285
6286 let patch = serde_json::from_value::<AgentThought>(json!({
6287 "messageId": "msg_thought_a12"
6288 }))
6289 .unwrap();
6290 assert_eq!(patch.content, MaybeUndefined::Undefined);
6291
6292 let clear = serde_json::from_value::<UserMessage>(json!({
6293 "messageId": "msg_user_8f7a1",
6294 "content": null
6295 }))
6296 .unwrap();
6297 assert_eq!(clear.content, MaybeUndefined::Null);
6298
6299 let clear_meta = serde_json::from_value::<UserMessage>(json!({
6300 "messageId": "msg_user_8f7a1",
6301 "_meta": null
6302 }))
6303 .unwrap();
6304 assert_eq!(clear_meta.meta, MaybeUndefined::Null);
6305
6306 let mut meta = Meta::new();
6307 meta.insert("source".to_string(), json!("replay"));
6308
6309 assert_eq!(
6310 serde_json::to_value(SessionUpdate::UserMessage(
6311 UserMessage::new("msg_user_8f7a1").meta(meta)
6312 ))
6313 .unwrap(),
6314 json!({
6315 "sessionUpdate": "user_message",
6316 "messageId": "msg_user_8f7a1",
6317 "_meta": {
6318 "source": "replay"
6319 }
6320 })
6321 );
6322
6323 assert_eq!(
6324 serde_json::to_value(SessionUpdate::UserMessage(
6325 UserMessage::new("msg_user_8f7a1").meta(None::<Meta>)
6326 ))
6327 .unwrap(),
6328 json!({
6329 "sessionUpdate": "user_message",
6330 "messageId": "msg_user_8f7a1",
6331 "_meta": null
6332 })
6333 );
6334 }
6335
6336 #[test]
6337 fn test_usage_update_serialization() {
6338 use serde_json::json;
6339
6340 assert_eq!(
6341 serde_json::to_value(SessionUpdate::UsageUpdate(UsageUpdate::new(
6342 53_000, 200_000
6343 )))
6344 .unwrap(),
6345 json!({
6346 "sessionUpdate": "usage_update",
6347 "used": 53000,
6348 "size": 200_000
6349 })
6350 );
6351
6352 assert_eq!(
6353 serde_json::to_value(SessionUpdate::UsageUpdate(
6354 UsageUpdate::new(53_000, 200_000).cost(Cost::new(0.045, "USD"))
6355 ))
6356 .unwrap(),
6357 json!({
6358 "sessionUpdate": "usage_update",
6359 "used": 53000,
6360 "size": 200_000,
6361 "cost": {
6362 "amount": 0.045,
6363 "currency": "USD"
6364 }
6365 })
6366 );
6367
6368 let SessionUpdate::UsageUpdate(update) = serde_json::from_value(json!({
6369 "sessionUpdate": "usage_update",
6370 "used": 53000,
6371 "size": 200_000,
6372 "cost": null
6373 }))
6374 .unwrap() else {
6375 panic!("expected usage update");
6376 };
6377
6378 assert_eq!(update.cost, MaybeUndefined::Null);
6379
6380 let SessionUpdate::UsageUpdate(update) = serde_json::from_value(json!({
6381 "sessionUpdate": "usage_update",
6382 "used": 53000,
6383 "size": 200_000
6384 }))
6385 .unwrap() else {
6386 panic!("expected usage update");
6387 };
6388
6389 assert_eq!(update.cost, MaybeUndefined::Undefined);
6390 }
6391
6392 #[test]
6393 fn error_stop_reason_carries_failure_beside_discriminator() {
6394 use crate::v2::{Error, ErrorStopReason};
6395 use serde_json::json;
6396
6397 let update =
6398 SessionUpdate::StateUpdate(StateUpdate::Idle(IdleStateUpdate::new().stop_reason(
6399 StopReason::from(ErrorStopReason::new().error(Error::auth_required())),
6400 )));
6401 let wire = json!({
6402 "sessionUpdate": "state_update",
6403 "state": "idle",
6404 "stopReason": "error",
6405 "error": { "code": -32000, "message": "Authentication required" }
6406 });
6407 assert_eq!(serde_json::to_value(&update).unwrap(), wire);
6408 assert_eq!(
6409 serde_json::from_value::<SessionUpdate>(wire).unwrap(),
6410 update
6411 );
6412
6413 let with_data =
6414 StateUpdate::Idle(IdleStateUpdate::new().stop_reason(StopReason::from(
6415 ErrorStopReason::new().error(
6416 Error::new(-32099, "Provider unavailable").data(json!({ "status": 503 })),
6417 ),
6418 )));
6419 let wire = json!({
6420 "state": "idle",
6421 "stopReason": "error",
6422 "error": {
6423 "code": -32099,
6424 "message": "Provider unavailable",
6425 "data": { "status": 503 }
6426 }
6427 });
6428 assert_eq!(serde_json::to_value(&with_data).unwrap(), wire);
6429 assert_eq!(
6430 serde_json::from_value::<StateUpdate>(wire).unwrap(),
6431 with_data
6432 );
6433
6434 let without_details = StateUpdate::Idle(
6437 IdleStateUpdate::new().stop_reason(StopReason::from(ErrorStopReason::new())),
6438 );
6439 for error in [
6440 None,
6441 Some(json!(null)),
6442 Some(json!("failed")),
6443 Some(json!({ "message": "missing code" })),
6444 ] {
6445 let mut wire = json!({ "state": "idle", "stopReason": "error" });
6446 if let Some(error) = error {
6447 wire["error"] = error;
6448 }
6449 assert_eq!(
6450 serde_json::from_value::<StateUpdate>(wire).unwrap(),
6451 without_details
6452 );
6453 }
6454 assert_eq!(
6455 serde_json::to_value(&without_details).unwrap(),
6456 json!({ "state": "idle", "stopReason": "error" })
6457 );
6458
6459 let parsed: StateUpdate = serde_json::from_value(json!({
6463 "state": "idle",
6464 "stopReason": "end_turn",
6465 "error": { "code": -32603, "message": "Internal error" }
6466 }))
6467 .unwrap();
6468 assert_eq!(
6469 parsed,
6470 StateUpdate::Idle(IdleStateUpdate::new().stop_reason(StopReason::EndTurn))
6471 );
6472 }
6473
6474 #[test]
6475 fn flattened_stop_reason_keeps_open_enum_tolerance() {
6476 use crate::v2::OtherStopReason;
6477 use serde_json::json;
6478
6479 let meta: Meta = [("source".into(), json!("test"))].into_iter().collect();
6480
6481 for stop_reason in [None, Some(json!(null)), Some(json!(true)), Some(json!({}))] {
6484 let mut wire = json!({ "state": "idle", "_meta": { "source": "test" } });
6485 if let Some(stop_reason) = stop_reason {
6486 wire["stopReason"] = stop_reason;
6487 }
6488 let StateUpdate::Idle(idle) = serde_json::from_value(wire).unwrap() else {
6489 panic!("expected idle state update");
6490 };
6491 assert_eq!(idle.stop_reason, None);
6492 assert_eq!(idle.meta, Some(meta.clone()));
6493 }
6494
6495 let wire = json!({
6498 "state": "idle",
6499 "stopReason": "_paused",
6500 "resumeAfter": 30,
6501 "_meta": { "source": "test" }
6502 });
6503 let parsed: StateUpdate = serde_json::from_value(wire.clone()).unwrap();
6504 let expected = StateUpdate::Idle(
6505 IdleStateUpdate::new()
6506 .stop_reason(StopReason::Other(OtherStopReason::new(
6507 "_paused",
6508 [("resumeAfter".into(), json!(30))].into_iter().collect(),
6509 )))
6510 .meta(meta),
6511 );
6512 assert_eq!(parsed, expected);
6513 assert_eq!(serde_json::to_value(&parsed).unwrap(), wire);
6514 }
6515
6516 #[test]
6517 fn known_stop_reasons_are_never_read_as_other() {
6518 use crate::v2::{ErrorStopReason, OtherStopReason};
6519 use serde_json::json;
6520
6521 let known = [
6522 StopReason::EndTurn,
6523 StopReason::MaxTokens,
6524 StopReason::MaxTurnRequests,
6525 StopReason::Refusal,
6526 StopReason::Cancelled,
6527 StopReason::Error(ErrorStopReason::new()),
6528 ];
6529 for stop_reason in &known {
6531 match stop_reason {
6532 StopReason::EndTurn
6533 | StopReason::MaxTokens
6534 | StopReason::MaxTurnRequests
6535 | StopReason::Refusal
6536 | StopReason::Cancelled
6537 | StopReason::Error(_)
6538 | StopReason::Other(_) => {}
6539 }
6540 }
6541
6542 for stop_reason in known {
6543 let update = StateUpdate::Idle(IdleStateUpdate::new().stop_reason(stop_reason));
6544 let wire = serde_json::to_value(&update).unwrap();
6545 assert_eq!(
6546 serde_json::from_value::<StateUpdate>(wire.clone()).unwrap(),
6547 update
6548 );
6549 assert!(
6550 serde_json::from_value::<OtherStopReason>(
6551 json!({ "stopReason": wire["stopReason"] })
6552 )
6553 .is_err(),
6554 "{} must not be accepted as a custom stop reason",
6555 wire["stopReason"]
6556 );
6557 }
6558 }
6559
6560 #[test]
6561 fn unknown_stop_reason_leaves_usage_on_the_idle_update() {
6562 use serde_json::json;
6563
6564 let usage = json!({ "totalTokens": 10, "inputTokens": 6, "outputTokens": 4 });
6565 let wire = json!({ "state": "idle", "stopReason": "_paused", "usage": usage });
6566 let StateUpdate::Idle(idle) = serde_json::from_value(wire.clone()).unwrap() else {
6567 panic!("expected idle state update");
6568 };
6569 let Some(StopReason::Other(other)) = &idle.stop_reason else {
6570 panic!("expected a custom stop reason");
6571 };
6572 assert!(other.fields.is_empty());
6573
6574 #[cfg(feature = "unstable_end_turn_token_usage")]
6575 {
6576 assert!(idle.usage.is_some());
6577 assert_eq!(serde_json::to_value(&idle).unwrap()["usage"], usage);
6578 }
6579 #[cfg(not(feature = "unstable_end_turn_token_usage"))]
6582 assert!(serde_json::to_value(&idle).unwrap().get("usage").is_none());
6583 }
6584
6585 #[test]
6586 fn test_state_update_serialization() {
6587 use serde_json::json;
6588
6589 assert_eq!(
6590 serde_json::to_value(SessionUpdate::StateUpdate(StateUpdate::Running(
6591 RunningStateUpdate::new()
6592 )))
6593 .unwrap(),
6594 json!({
6595 "sessionUpdate": "state_update",
6596 "state": "running"
6597 })
6598 );
6599
6600 assert_eq!(
6601 serde_json::to_value(SessionUpdate::StateUpdate(StateUpdate::Idle(
6602 IdleStateUpdate::new().stop_reason(StopReason::EndTurn)
6603 )))
6604 .unwrap(),
6605 json!({
6606 "sessionUpdate": "state_update",
6607 "state": "idle",
6608 "stopReason": "end_turn"
6609 })
6610 );
6611
6612 let SessionUpdate::StateUpdate(update) = serde_json::from_value(json!({
6613 "sessionUpdate": "state_update",
6614 "state": "requires_action"
6615 }))
6616 .unwrap() else {
6617 panic!("expected state update");
6618 };
6619
6620 assert!(matches!(update, StateUpdate::RequiresAction(_)));
6621
6622 let SessionUpdate::StateUpdate(StateUpdate::Idle(update)) = serde_json::from_value(json!({
6623 "sessionUpdate": "state_update",
6624 "state": "idle",
6625 "stopReason": null
6626 }))
6627 .unwrap() else {
6628 panic!("expected idle state update");
6629 };
6630
6631 assert_eq!(update.stop_reason, None);
6632
6633 let SessionUpdate::StateUpdate(StateUpdate::Other(update)) =
6634 serde_json::from_value(json!({
6635 "sessionUpdate": "state_update",
6636 "state": "_paused",
6637 "label": "Paused"
6638 }))
6639 .unwrap()
6640 else {
6641 panic!("expected unknown state update");
6642 };
6643
6644 assert_eq!(update.state, "_paused");
6645 assert_eq!(update.fields["label"], json!("Paused"));
6646 }
6647
6648 #[test]
6649 fn session_update_preserves_unknown_variant() {
6650 use serde_json::json;
6651
6652 let update: SessionUpdate = serde_json::from_value(json!({
6653 "sessionUpdate": "_status_badge",
6654 "label": "Indexing",
6655 "progress": 0.5
6656 }))
6657 .unwrap();
6658
6659 let SessionUpdate::Other(unknown) = update else {
6660 panic!("expected unknown session update");
6661 };
6662
6663 assert_eq!(unknown.session_update, "_status_badge");
6664 assert_eq!(unknown.fields.get("label"), Some(&json!("Indexing")));
6665 assert_eq!(unknown.fields.get("progress"), Some(&json!(0.5)));
6666
6667 assert_eq!(
6668 serde_json::to_value(SessionUpdate::Other(unknown)).unwrap(),
6669 json!({
6670 "sessionUpdate": "_status_badge",
6671 "label": "Indexing",
6672 "progress": 0.5
6673 })
6674 );
6675 }
6676
6677 #[test]
6678 fn terminal_session_updates_use_known_discriminators() {
6679 use serde_json::json;
6680
6681 assert_eq!(
6682 serde_json::to_value(SessionUpdate::TerminalUpdate(
6683 TerminalUpdate::new("term_1").command("cargo test")
6684 ))
6685 .unwrap(),
6686 json!({
6687 "sessionUpdate": "terminal_update",
6688 "terminalId": "term_1",
6689 "command": "cargo test"
6690 })
6691 );
6692 assert_eq!(
6693 serde_json::to_value(SessionUpdate::TerminalOutputChunk(
6694 TerminalOutputChunk::new("term_1", "dGVzdAo=")
6695 ))
6696 .unwrap(),
6697 json!({
6698 "sessionUpdate": "terminal_output_chunk",
6699 "terminalId": "term_1",
6700 "data": "dGVzdAo="
6701 })
6702 );
6703 }
6704
6705 #[test]
6706 fn session_update_does_not_hide_malformed_known_terminal_variants() {
6707 use serde_json::json;
6708
6709 assert!(
6710 serde_json::from_value::<SessionUpdate>(json!({
6711 "sessionUpdate": "terminal_update"
6712 }))
6713 .is_err()
6714 );
6715 assert!(
6716 serde_json::from_value::<SessionUpdate>(json!({
6717 "sessionUpdate": "terminal_output_chunk",
6718 "terminalId": "term_1"
6719 }))
6720 .is_err()
6721 );
6722 }
6723
6724 #[test]
6725 fn test_plan_update_serialization() {
6726 use serde_json::json;
6727
6728 let plan_update =
6729 SessionUpdate::PlanUpdate(PlanUpdate::new(crate::v2::PlanUpdateContent::items(
6730 "plan-1",
6731 vec![crate::v2::PlanEntry::new(
6732 "Step 1",
6733 crate::v2::PlanEntryPriority::High,
6734 crate::v2::PlanEntryStatus::Pending,
6735 )],
6736 )));
6737
6738 assert_eq!(
6739 serde_json::to_value(plan_update).unwrap(),
6740 json!({
6741 "sessionUpdate": "plan_update",
6742 "plan": {
6743 "type": "items",
6744 "planId": "plan-1",
6745 "entries": [
6746 {
6747 "content": "Step 1",
6748 "priority": "high",
6749 "status": "pending"
6750 }
6751 ]
6752 }
6753 })
6754 );
6755 }
6756
6757 #[cfg(feature = "unstable_plan_operations")]
6758 #[test]
6759 fn test_plan_removed_serialization() {
6760 use serde_json::json;
6761
6762 assert_eq!(
6763 serde_json::to_value(SessionUpdate::PlanRemoved(PlanRemoved::new("plan-1"))).unwrap(),
6764 json!({
6765 "sessionUpdate": "plan_removed",
6766 "planId": "plan-1"
6767 })
6768 );
6769 }
6770
6771 #[test]
6772 fn available_command_uses_type_discriminator() {
6773 use serde_json::json;
6774
6775 let command = AvailableCommand::Command(
6776 Command::new("web", "Search the web")
6777 .input(AvailableCommandInput::Text(TextCommandInput::new("Query"))),
6778 );
6779
6780 let json = serde_json::to_value(&command).unwrap();
6781 assert_eq!(
6782 json,
6783 json!({
6784 "type": "command",
6785 "name": "web",
6786 "description": "Search the web",
6787 "input": { "type": "text", "hint": "Query" }
6788 })
6789 );
6790
6791 let roundtripped: AvailableCommand = serde_json::from_value(json).unwrap();
6792 assert_eq!(roundtripped, command);
6793 assert_eq!(roundtripped.name(), "web");
6794 assert_eq!(roundtripped.description(), "Search the web");
6795 }
6796
6797 #[test]
6798 fn available_command_preserves_unknown_typed_variant() {
6799 use serde_json::json;
6800
6801 let payload = json!({
6802 "type": "_skill",
6803 "name": "pdf-processing",
6804 "description": "Extract text from PDFs",
6805 "uri": "skill://pdf-processing/SKILL.md",
6806 "_meta": { "example.com/source": "mcp" }
6807 });
6808 let command: AvailableCommand = serde_json::from_value(payload.clone()).unwrap();
6809
6810 assert_eq!(command.name(), "pdf-processing");
6811 assert_eq!(command.description(), "Extract text from PDFs");
6812 assert!(command.meta().is_some());
6813
6814 let AvailableCommand::Other(unknown) = &command else {
6815 panic!("expected unknown command");
6816 };
6817 assert_eq!(unknown.type_, "_skill");
6818 assert_eq!(
6819 unknown.fields.get("uri"),
6820 Some(&json!("skill://pdf-processing/SKILL.md"))
6821 );
6822 assert_eq!(serde_json::to_value(&command).unwrap(), payload);
6823 }
6824
6825 #[test]
6826 fn available_command_unknown_tolerates_invalid_meta() {
6827 use serde_json::json;
6828
6829 let command: AvailableCommand = serde_json::from_value(json!({
6830 "type": "_skill",
6831 "name": "pdf-processing",
6832 "description": "Extract text from PDFs",
6833 "_meta": "oops"
6834 }))
6835 .unwrap();
6836
6837 assert!(matches!(command, AvailableCommand::Other(_)));
6838 assert!(command.meta().is_none());
6839 }
6840
6841 #[test]
6842 fn available_command_unknown_does_not_hide_malformed_command_variant() {
6843 use serde_json::json;
6844
6845 assert!(
6847 serde_json::from_value::<AvailableCommand>(json!({
6848 "name": "test",
6849 "description": "Run project tests"
6850 }))
6851 .is_err()
6852 );
6853 assert!(
6854 serde_json::from_value::<AvailableCommand>(json!({
6855 "type": "command",
6856 "name": "test"
6857 }))
6858 .is_err()
6859 );
6860 assert!(
6861 serde_json::from_value::<OtherAvailableCommand>(json!({
6862 "type": "command",
6863 "name": "test",
6864 "description": "Run project tests"
6865 }))
6866 .is_err()
6867 );
6868 assert!(
6869 serde_json::from_value::<AvailableCommand>(json!({
6870 "type": "_skill",
6871 "name": "pdf-processing"
6872 }))
6873 .is_err()
6874 );
6875 }
6876
6877 #[cfg(feature = "unstable_agent_skills")]
6878 #[test]
6879 fn skill_command_uses_type_discriminator() {
6880 use serde_json::json;
6881
6882 let skill = AvailableCommand::Skill(
6883 Skill::new("pdf-processing", "Extract text and tables from PDF files").path(
6884 AbsolutePath::new("/home/alice/.agents/skills/pdf-processing/SKILL.md"),
6885 ),
6886 );
6887
6888 let wire = json!({
6889 "type": "skill",
6890 "name": "pdf-processing",
6891 "description": "Extract text and tables from PDF files",
6892 "path": "/home/alice/.agents/skills/pdf-processing/SKILL.md"
6893 });
6894 assert_eq!(serde_json::to_value(&skill).unwrap(), wire);
6895
6896 let roundtripped: AvailableCommand = serde_json::from_value(wire).unwrap();
6897 assert_eq!(roundtripped, skill);
6898 assert_eq!(roundtripped.name(), "pdf-processing");
6899 assert_eq!(
6900 roundtripped.description(),
6901 "Extract text and tables from PDF files"
6902 );
6903 assert!(roundtripped.meta().is_none());
6904
6905 assert_eq!(
6907 serde_json::to_value(AvailableCommand::Skill(Skill::new(
6908 "simplify",
6909 "Simplify the changed code"
6910 )))
6911 .unwrap(),
6912 json!({
6913 "type": "skill",
6914 "name": "simplify",
6915 "description": "Simplify the changed code"
6916 })
6917 );
6918 }
6919
6920 #[cfg(feature = "unstable_agent_skills")]
6921 #[test]
6922 fn skill_command_treats_invalid_display_fields_as_absent() {
6923 use serde_json::json;
6924
6925 let expected = AvailableCommand::Skill(Skill::new("pdf-processing", "Extract text"));
6926 for (field, value) in [
6927 ("path", json!(null)),
6928 ("path", json!(7)),
6929 ("path", json!({ "uri": "file:///SKILL.md" })),
6930 ("_meta", json!(null)),
6931 ("_meta", json!("oops")),
6932 ] {
6933 let mut wire = json!({
6934 "type": "skill",
6935 "name": "pdf-processing",
6936 "description": "Extract text"
6937 });
6938 wire[field] = value;
6939 assert_eq!(
6940 serde_json::from_value::<AvailableCommand>(wire).unwrap(),
6941 expected,
6942 "{field}"
6943 );
6944 }
6945 }
6946
6947 #[cfg(feature = "unstable_agent_skills")]
6948 #[test]
6949 fn skill_command_has_no_input_specification() {
6950 use serde_json::json;
6951
6952 let skill: AvailableCommand = serde_json::from_value(json!({
6954 "type": "skill",
6955 "name": "pdf-processing",
6956 "description": "Extract text",
6957 "input": { "type": "text", "hint": "file or instructions" }
6958 }))
6959 .unwrap();
6960 assert_eq!(
6961 skill,
6962 AvailableCommand::Skill(Skill::new("pdf-processing", "Extract text"))
6963 );
6964 assert!(serde_json::to_value(&skill).unwrap().get("input").is_none());
6965 }
6966
6967 #[cfg(feature = "unstable_agent_skills")]
6968 #[test]
6969 fn malformed_skill_command_is_skipped_and_never_preserved_as_unknown() {
6970 use serde_json::json;
6971
6972 for malformed in [
6973 json!({ "type": "skill", "name": "pdf-processing" }),
6974 json!({ "type": "skill", "description": "Extract text" }),
6975 json!({ "type": "skill", "name": 1, "description": "Extract text" }),
6976 ] {
6977 assert!(serde_json::from_value::<AvailableCommand>(malformed.clone()).is_err());
6978 assert!(serde_json::from_value::<OtherAvailableCommand>(malformed).is_err());
6979 }
6980
6981 let update: AvailableCommandsUpdate = serde_json::from_value(json!({
6983 "availableCommands": [
6984 { "type": "skill", "name": "pdf-processing", "description": "Extract text" },
6985 { "type": "skill", "name": "broken" },
6986 { "type": "command", "name": "test", "description": "Run project tests" }
6987 ]
6988 }))
6989 .unwrap();
6990 assert_eq!(
6991 update.available_commands,
6992 vec![
6993 AvailableCommand::Skill(Skill::new("pdf-processing", "Extract text")),
6994 AvailableCommand::Command(Command::new("test", "Run project tests")),
6995 ]
6996 );
6997 }
6998
6999 #[cfg(feature = "unstable_agent_skills")]
7000 #[test]
7001 fn skill_commands_capability_is_advertised_only_by_an_object() {
7002 use serde_json::json;
7003
7004 let capabilities = ClientCapabilities::new().session(
7005 ClientSessionCapabilities::new()
7006 .commands(CommandsCapabilities::new().skill(CommandsSkillCapabilities::new())),
7007 );
7008 let wire = json!({ "session": { "commands": { "skill": {} } } });
7009 assert_eq!(serde_json::to_value(&capabilities).unwrap(), wire);
7010 assert_eq!(
7011 serde_json::from_value::<ClientCapabilities>(wire).unwrap(),
7012 capabilities
7013 );
7014
7015 for unsupported in [
7017 json!({}),
7018 json!({ "session": null }),
7019 json!({ "session": {} }),
7020 json!({ "session": { "commands": null } }),
7021 json!({ "session": { "commands": {} } }),
7022 json!({ "session": { "commands": true } }),
7023 json!({ "session": { "commands": { "skill": null } } }),
7024 json!({ "session": { "commands": { "skill": true } } }),
7025 json!({ "session": { "commands": { "skill": "supported" } } }),
7026 ] {
7027 let capabilities: ClientCapabilities = serde_json::from_value(unsupported).unwrap();
7028 assert!(
7029 capabilities
7030 .session
7031 .and_then(|session| session.commands)
7032 .and_then(|commands| commands.skill)
7033 .is_none()
7034 );
7035 }
7036 }
7037
7038 #[cfg(all(
7039 feature = "unstable_agent_skills",
7040 feature = "unstable_prompt_suggestions"
7041 ))]
7042 #[test]
7043 fn client_session_capabilities_are_independent_of_each_other() {
7044 use serde_json::json;
7045
7046 let capabilities: ClientCapabilities = serde_json::from_value(json!({
7048 "session": {
7049 "promptSuggestions": true,
7050 "commands": { "skill": {} }
7051 }
7052 }))
7053 .unwrap();
7054 let session = capabilities.session.unwrap();
7055 assert!(session.prompt_suggestions.is_none());
7056 assert!(session.commands.unwrap().skill.is_some());
7057 }
7058
7059 #[cfg(all(feature = "schemars", feature = "unstable_agent_skills"))]
7060 #[test]
7061 fn skill_schemas_keep_acted_on_fields_strict() {
7062 use serde_json::json;
7063
7064 let skill = serde_json::to_value(schemars::schema_for!(Skill)).unwrap();
7065 assert_eq!(skill["required"], json!(["name", "description"]));
7066 for lenient in ["path", "_meta"] {
7067 assert_eq!(
7068 skill["properties"][lenient]["x-deserialize-default-on-error"], true,
7069 "{lenient}"
7070 );
7071 }
7072
7073 let reference =
7075 serde_json::to_value(schemars::schema_for!(crate::v2::SkillReference)).unwrap();
7076 assert_eq!(reference["required"], json!(["name"]));
7077 assert!(
7078 reference["properties"]["name"]
7079 .get("x-deserialize-default-on-error")
7080 .is_none()
7081 );
7082 }
7083
7084 #[test]
7085 fn available_command_input_preserves_unknown_typed_variant() {
7086 use serde_json::json;
7087
7088 let input: AvailableCommandInput = serde_json::from_value(json!({
7089 "type": "_choices",
7090 "hint": "Pick one",
7091 "options": ["fast", "careful"]
7092 }))
7093 .unwrap();
7094
7095 let AvailableCommandInput::Other(unknown) = input else {
7096 panic!("expected unknown command input");
7097 };
7098
7099 assert_eq!(unknown.type_, "_choices");
7100 assert_eq!(unknown.fields.get("hint"), Some(&json!("Pick one")));
7101 assert_eq!(
7102 unknown.fields.get("options"),
7103 Some(&json!(["fast", "careful"]))
7104 );
7105 assert_eq!(
7106 serde_json::to_value(AvailableCommandInput::Other(unknown)).unwrap(),
7107 json!({
7108 "type": "_choices",
7109 "hint": "Pick one",
7110 "options": ["fast", "careful"]
7111 })
7112 );
7113 }
7114
7115 #[test]
7116 fn available_command_input_text_uses_type_discriminator() {
7117 use serde_json::json;
7118
7119 let input = AvailableCommandInput::Text(TextCommandInput::new("Describe changes"));
7120
7121 let json = serde_json::to_value(&input).unwrap();
7122 assert_eq!(
7123 json,
7124 json!({
7125 "type": "text",
7126 "hint": "Describe changes"
7127 })
7128 );
7129
7130 let roundtripped: AvailableCommandInput = serde_json::from_value(json).unwrap();
7131 assert!(matches!(roundtripped, AvailableCommandInput::Text(_)));
7132 }
7133
7134 #[test]
7135 fn request_permission_subject_tool_call_uses_type_discriminator() {
7136 use serde_json::json;
7137
7138 let subject = RequestPermissionSubject::from(ToolCallUpdate::new("call_001"));
7139
7140 let json = serde_json::to_value(&subject).unwrap();
7141 assert_eq!(
7142 json,
7143 json!({
7144 "type": "tool_call",
7145 "toolCall": {
7146 "toolCallId": "call_001"
7147 }
7148 })
7149 );
7150
7151 let roundtripped: RequestPermissionSubject = serde_json::from_value(json).unwrap();
7152 assert!(matches!(
7153 roundtripped,
7154 RequestPermissionSubject::ToolCall(_)
7155 ));
7156 }
7157
7158 #[test]
7159 fn request_permission_subject_command_uses_type_discriminator() {
7160 use serde_json::json;
7161
7162 let mut meta = Meta::new();
7163 meta.insert("source".to_string(), json!("shell"));
7164 let subject = RequestPermissionSubject::from(
7165 CommandPermissionSubject::new("cargo test", "/workspace/project")
7166 .tool_call_id("call_001")
7167 .terminal_id("term_1")
7168 .meta(meta),
7169 );
7170
7171 let json = serde_json::to_value(&subject).unwrap();
7172 assert_eq!(
7173 json,
7174 json!({
7175 "type": "command",
7176 "command": "cargo test",
7177 "cwd": "/workspace/project",
7178 "toolCallId": "call_001",
7179 "terminalId": "term_1",
7180 "_meta": {
7181 "source": "shell"
7182 }
7183 })
7184 );
7185
7186 let roundtripped: RequestPermissionSubject = serde_json::from_value(json).unwrap();
7187 assert!(matches!(roundtripped, RequestPermissionSubject::Command(_)));
7188 }
7189
7190 #[test]
7191 fn command_permission_subject_treats_optional_association_nulls_as_omitted() {
7192 use serde_json::json;
7193
7194 let subject: RequestPermissionSubject = serde_json::from_value(json!({
7195 "type": "command",
7196 "command": "cargo test",
7197 "cwd": "/workspace/project",
7198 "toolCallId": null,
7199 "terminalId": null,
7200 "_meta": null
7201 }))
7202 .unwrap();
7203
7204 let RequestPermissionSubject::Command(subject) = subject else {
7205 panic!("expected command permission subject");
7206 };
7207 assert_eq!(subject.cwd, AbsolutePath::new("/workspace/project"));
7208 assert_eq!(subject.tool_call_id, None);
7209 assert_eq!(subject.terminal_id, None);
7210 assert_eq!(subject.meta, None);
7211 assert_eq!(
7212 serde_json::to_value(RequestPermissionSubject::Command(subject)).unwrap(),
7213 json!({
7214 "type": "command",
7215 "command": "cargo test",
7216 "cwd": "/workspace/project"
7217 })
7218 );
7219 }
7220
7221 #[test]
7222 fn request_permission_subject_preserves_unknown_variant() {
7223 use serde_json::json;
7224
7225 let subject: RequestPermissionSubject = serde_json::from_value(json!({
7226 "type": "_review",
7227 "reason": "needs-review",
7228 "retryAfterSeconds": 30
7229 }))
7230 .unwrap();
7231
7232 let RequestPermissionSubject::Other(unknown) = subject else {
7233 panic!("expected unknown permission subject");
7234 };
7235
7236 assert_eq!(unknown.type_, "_review");
7237 assert_eq!(unknown.fields.get("reason"), Some(&json!("needs-review")));
7238 assert_eq!(unknown.fields.get("retryAfterSeconds"), Some(&json!(30)));
7239 assert_eq!(
7240 serde_json::to_value(RequestPermissionSubject::Other(unknown)).unwrap(),
7241 json!({
7242 "type": "_review",
7243 "reason": "needs-review",
7244 "retryAfterSeconds": 30
7245 })
7246 );
7247 }
7248
7249 #[test]
7250 fn request_permission_subject_unknown_does_not_hide_malformed_known_variant() {
7251 use serde_json::json;
7252
7253 assert!(
7254 serde_json::from_value::<RequestPermissionSubject>(json!({
7255 "type": "tool_call"
7256 }))
7257 .is_err()
7258 );
7259 assert!(
7260 serde_json::from_value::<RequestPermissionSubject>(json!({
7261 "type": 1
7262 }))
7263 .is_err()
7264 );
7265 assert!(
7266 serde_json::from_value::<RequestPermissionSubject>(json!({
7267 "type": "command",
7268 "cwd": "/workspace/project"
7269 }))
7270 .is_err()
7271 );
7272 assert!(
7273 serde_json::from_value::<RequestPermissionSubject>(json!({
7274 "type": "command",
7275 "command": "cargo test"
7276 }))
7277 .is_err()
7278 );
7279 assert!(
7280 serde_json::from_value::<RequestPermissionSubject>(json!({
7281 "type": "command",
7282 "command": "cargo test",
7283 "cwd": null
7284 }))
7285 .is_err()
7286 );
7287 }
7288
7289 #[test]
7290 fn request_permission_title_and_description_are_separate_from_tool_call_content() {
7291 use serde_json::json;
7292
7293 let request =
7294 RequestPermissionRequest::new("sess_abc123def456", "Approve file edit?", Vec::new())
7295 .description("Allow this tool to edit src/main.rs?")
7296 .subject(RequestPermissionSubject::from(ToolCallUpdate::new(
7297 "call_001",
7298 )));
7299
7300 assert_eq!(
7301 serde_json::to_value(request).unwrap(),
7302 json!({
7303 "sessionId": "sess_abc123def456",
7304 "title": "Approve file edit?",
7305 "description": "Allow this tool to edit src/main.rs?",
7306 "subject": {
7307 "type": "tool_call",
7308 "toolCall": {
7309 "toolCallId": "call_001"
7310 }
7311 },
7312 "options": []
7313 })
7314 );
7315 }
7316
7317 #[test]
7318 fn request_permission_requires_title_and_allows_missing_subject() {
7319 use serde_json::json;
7320
7321 let request = RequestPermissionRequest::new(
7322 "sess_abc123def456",
7323 "Approve elevated permissions?",
7324 Vec::new(),
7325 );
7326
7327 assert_eq!(
7328 serde_json::to_value(request).unwrap(),
7329 json!({
7330 "sessionId": "sess_abc123def456",
7331 "title": "Approve elevated permissions?",
7332 "options": []
7333 })
7334 );
7335
7336 let missing_subject: RequestPermissionRequest = serde_json::from_value(json!({
7337 "sessionId": "sess_abc123def456",
7338 "title": "Approve elevated permissions?",
7339 "options": []
7340 }))
7341 .unwrap();
7342 assert!(missing_subject.subject.is_none());
7343
7344 let null_subject: RequestPermissionRequest = serde_json::from_value(json!({
7345 "sessionId": "sess_abc123def456",
7346 "title": "Approve elevated permissions?",
7347 "subject": null,
7348 "options": []
7349 }))
7350 .unwrap();
7351 assert!(null_subject.subject.is_none());
7352
7353 assert!(
7354 serde_json::from_value::<RequestPermissionRequest>(json!({
7355 "sessionId": "sess_abc123def456",
7356 "options": []
7357 }))
7358 .is_err()
7359 );
7360 }
7361
7362 #[test]
7363 fn request_permission_outcome_preserves_unknown_variant() {
7364 use serde_json::json;
7365
7366 let outcome: RequestPermissionOutcome = serde_json::from_value(json!({
7367 "outcome": "_defer",
7368 "reason": "needs-review",
7369 "retryAfterSeconds": 30
7370 }))
7371 .unwrap();
7372
7373 let RequestPermissionOutcome::Other(unknown) = outcome else {
7374 panic!("expected unknown permission outcome");
7375 };
7376
7377 assert_eq!(unknown.outcome, "_defer");
7378 assert_eq!(unknown.fields.get("reason"), Some(&json!("needs-review")));
7379 assert_eq!(unknown.fields.get("retryAfterSeconds"), Some(&json!(30)));
7380 assert_eq!(
7381 serde_json::to_value(RequestPermissionOutcome::Other(unknown)).unwrap(),
7382 json!({
7383 "outcome": "_defer",
7384 "reason": "needs-review",
7385 "retryAfterSeconds": 30
7386 })
7387 );
7388 }
7389
7390 #[test]
7391 fn request_permission_outcome_unknown_does_not_hide_malformed_known_variant() {
7392 use serde_json::json;
7393
7394 assert!(
7395 serde_json::from_value::<RequestPermissionOutcome>(json!({
7396 "outcome": "selected"
7397 }))
7398 .is_err()
7399 );
7400 assert!(
7401 serde_json::from_value::<RequestPermissionOutcome>(json!({
7402 "outcome": 1
7403 }))
7404 .is_err()
7405 );
7406 }
7407
7408 #[test]
7409 fn available_command_input_unknown_does_not_hide_malformed_text_variant() {
7410 use serde_json::json;
7411
7412 assert!(serde_json::from_value::<AvailableCommandInput>(json!({})).is_err());
7413 assert!(
7414 serde_json::from_value::<AvailableCommandInput>(json!({
7415 "hint": "Pick one"
7416 }))
7417 .is_err()
7418 );
7419 assert!(
7420 serde_json::from_value::<AvailableCommandInput>(json!({
7421 "type": 1,
7422 "hint": "Pick one"
7423 }))
7424 .is_err()
7425 );
7426 assert!(
7427 serde_json::from_value::<OtherAvailableCommandInput>(json!({
7428 "type": "text",
7429 "hint": "Pick one"
7430 }))
7431 .is_err()
7432 );
7433 }
7434
7435 #[cfg(feature = "unstable_mcp_over_acp")]
7436 #[test]
7437 fn test_agent_mcp_request_method_names() {
7438 use serde_json::json;
7439
7440 let params: serde_json::Map<String, serde_json::Value> =
7441 [("cursor".to_string(), json!("abc"))].into_iter().collect();
7442
7443 assert_eq!(CLIENT_METHOD_NAMES.mcp_message, "mcp/message");
7444 assert_eq!(
7445 AgentRequest::MessageMcpRequest(Box::new(MessageMcpRequest::new(
7446 "server-1",
7447 "req-1",
7448 "tools/list"
7449 )))
7450 .method(),
7451 "mcp/message"
7452 );
7453 assert_eq!(
7454 serde_json::to_value(
7455 MessageMcpRequest::new("server-1", "req-1", "tools/list").params(params)
7456 )
7457 .unwrap(),
7458 json!({
7459 "serverId": "server-1",
7460 "requestId": "req-1",
7461 "method": "tools/list",
7462 "params": { "cursor": "abc" }
7463 })
7464 );
7465
7466 let request_with_null_params: MessageMcpRequest = serde_json::from_value(json!({
7467 "serverId": "server-1",
7468 "requestId": "req-1",
7469 "method": "tools/list",
7470 "params": null,
7471 "_meta": null
7472 }))
7473 .unwrap();
7474 assert_eq!(request_with_null_params.params, None);
7475 assert_eq!(request_with_null_params.meta, None);
7476 for key in ["serverId", "requestId", "method"] {
7477 let mut value =
7478 json!({"serverId":"server-1", "requestId":"req-1", "method":"tools/list"});
7479 value.as_object_mut().unwrap().remove(key);
7480 assert!(serde_json::from_value::<MessageMcpRequest>(value).is_err());
7481 }
7482 for key in ["serverId", "requestId", "method"] {
7483 let mut value =
7484 json!({"serverId":"server-1", "requestId":"req-1", "method":"tools/list"});
7485 value[key] = serde_json::Value::Null;
7486 assert!(serde_json::from_value::<MessageMcpRequest>(value).is_err());
7487 }
7488 }
7489
7490 #[test]
7491 fn test_auth_capabilities_serialize_terminal_support_as_object() {
7492 use serde_json::json;
7493
7494 let capabilities = ClientAuthCapabilities::new().terminal(TerminalAuthCapabilities::new());
7495
7496 assert_eq!(
7497 serde_json::to_value(&capabilities).unwrap(),
7498 json!({
7499 "terminal": {}
7500 })
7501 );
7502
7503 let deserialized: ClientAuthCapabilities = serde_json::from_value(json!({
7504 "terminal": false
7505 }))
7506 .unwrap();
7507 assert!(deserialized.terminal.is_none());
7508 }
7509
7510 #[test]
7511 fn request_permission_request_rejects_malformed_options() {
7512 use serde_json::json;
7513
7514 assert!(
7515 serde_json::from_value::<RequestPermissionRequest>(json!({
7516 "sessionId": "sess-1",
7517 "title": "Run tool?",
7518 "options": "not-an-array"
7519 }))
7520 .is_err()
7521 );
7522 assert!(
7523 serde_json::from_value::<RequestPermissionRequest>(json!({
7524 "sessionId": "sess-1",
7525 "title": "Run tool?",
7526 "options": [{"optionId": "allow"}]
7527 }))
7528 .is_err()
7529 );
7530 }
7531
7532 #[cfg(feature = "unstable_plan_operations")]
7533 #[test]
7534 fn malformed_plan_removed_is_not_hidden_as_unknown_update() {
7535 use serde_json::json;
7536
7537 assert!(
7538 serde_json::from_value::<SessionUpdate>(json!({
7539 "sessionUpdate": "plan_removed"
7540 }))
7541 .is_err()
7542 );
7543 }
7544}