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 #[cfg(feature = "unstable_session_cursors")]
183 CursorUpdate(CursorUpdate),
184 SubagentUpdate(SubagentUpdate),
187 SessionMessage(SessionMessage),
190 SessionMessageChunk(SessionMessageChunk),
192 #[serde(untagged)]
202 Other(OtherSessionUpdate),
203}
204
205#[serde_as]
210#[skip_serializing_none]
211#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
212#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
213#[serde(rename_all = "camelCase")]
214#[non_exhaustive]
215pub struct SessionMessageChunk {
216 pub message_id: MessageId,
218 pub content: ContentBlock,
220 #[serde_as(deserialize_as = "DefaultOnError")]
227 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
228 #[serde(default, rename = "_meta")]
229 pub meta: Option<Meta>,
230}
231
232impl SessionMessageChunk {
233 #[must_use]
235 pub fn new(message_id: impl Into<MessageId>, content: ContentBlock) -> Self {
236 Self {
237 message_id: message_id.into(),
238 content,
239 meta: None,
240 }
241 }
242
243 #[must_use]
245 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
246 self.meta = meta.into_option();
247 self
248 }
249}
250
251#[serde_as]
253#[skip_serializing_none]
254#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
255#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
256#[serde(rename_all = "camelCase")]
257#[non_exhaustive]
258pub struct SessionMessage {
259 pub message_id: MessageId,
261 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
265 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
266 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
267 pub sender_session_id: MaybeUndefined<SessionId>,
268 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
272 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
273 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
274 pub recipient_session_id: MaybeUndefined<SessionId>,
275 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
281 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
282 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
283 pub sender_message_id: MaybeUndefined<MessageId>,
284 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
290 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
291 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
292 pub recipient_message_id: MaybeUndefined<MessageId>,
293 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<VecSkipError<_>>>")]
296 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
297 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
298 pub content: MaybeUndefined<Vec<ContentBlock>>,
299 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
308 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
309 #[serde(
310 default,
311 rename = "_meta",
312 skip_serializing_if = "MaybeUndefined::is_undefined"
313 )]
314 pub meta: MaybeUndefined<Meta>,
315}
316
317impl SessionMessage {
318 #[must_use]
320 pub fn new(message_id: impl Into<MessageId>) -> Self {
321 Self {
322 message_id: message_id.into(),
323 sender_session_id: MaybeUndefined::Undefined,
324 recipient_session_id: MaybeUndefined::Undefined,
325 sender_message_id: MaybeUndefined::Undefined,
326 recipient_message_id: MaybeUndefined::Undefined,
327 content: MaybeUndefined::Undefined,
328 meta: MaybeUndefined::Undefined,
329 }
330 }
331
332 #[must_use]
334 pub fn sender_session_id(
335 mut self,
336 sender_session_id: impl IntoMaybeUndefined<SessionId>,
337 ) -> Self {
338 self.sender_session_id = sender_session_id.into_maybe_undefined();
339 self
340 }
341
342 #[must_use]
344 pub fn recipient_session_id(
345 mut self,
346 recipient_session_id: impl IntoMaybeUndefined<SessionId>,
347 ) -> Self {
348 self.recipient_session_id = recipient_session_id.into_maybe_undefined();
349 self
350 }
351
352 #[must_use]
354 pub fn sender_message_id(
355 mut self,
356 sender_message_id: impl IntoMaybeUndefined<MessageId>,
357 ) -> Self {
358 self.sender_message_id = sender_message_id.into_maybe_undefined();
359 self
360 }
361
362 #[must_use]
364 pub fn recipient_message_id(
365 mut self,
366 recipient_message_id: impl IntoMaybeUndefined<MessageId>,
367 ) -> Self {
368 self.recipient_message_id = recipient_message_id.into_maybe_undefined();
369 self
370 }
371
372 #[must_use]
374 pub fn content(mut self, content: impl IntoMaybeUndefined<Vec<ContentBlock>>) -> Self {
375 self.content = content.into_maybe_undefined();
376 self
377 }
378
379 #[must_use]
384 pub fn meta(mut self, meta: impl IntoMaybeUndefined<Meta>) -> Self {
385 self.meta = meta.into_maybe_undefined();
386 self
387 }
388}
389
390#[cfg(test)]
391mod session_message_tests {
392 use super::*;
393 use serde_json::{Value, json};
394
395 #[test]
396 fn transcript_envelopes_and_multimodal_content() {
397 for (transcript, sender, recipient, id) in [
398 ("parent", "parent", "child", "sent-1"),
399 ("child", "parent", "child", "received-9"),
400 ("child", "child", "parent", "sent-2"),
401 ] {
402 let wire = json!({"sessionId": transcript, "update": {
403 "sessionUpdate": "session_message", "messageId": id,
404 "senderSessionId": sender, "recipientSessionId": recipient, "content": [
405 {"type": "text", "text": "hello"},
406 {"type": "image", "data": "aGVsbG8=", "mimeType": "image/png"}
407 ]
408 }});
409 let decoded: UpdateSessionNotification = serde_json::from_value(wire.clone()).unwrap();
410 assert_eq!(serde_json::to_value(decoded).unwrap(), wire);
411 }
412 }
413
414 #[test]
415 fn chunks_and_upserts_share_transcript_local_identity() {
416 for (transcript, id) in [("parent", "sent-1"), ("child", "received-9")] {
417 let wire = json!({"sessionId": transcript, "update": {
418 "sessionUpdate": "session_message_chunk", "messageId": id,
419 "content": {"type": "text", "text": "hello"}
420 }});
421 let decoded: UpdateSessionNotification = serde_json::from_value(wire.clone()).unwrap();
422 assert_eq!(serde_json::to_value(decoded).unwrap(), wire);
423 let upsert = SessionMessage::new(id)
424 .sender_session_id(SessionId::new("parent"))
425 .recipient_session_id(SessionId::new("child"))
426 .content(vec![]);
427 let chunk = SessionMessageChunk::new(
428 id,
429 ContentBlock::Text(crate::v2::TextContent::new("hello")),
430 );
431 assert_eq!(chunk.message_id, upsert.message_id);
432 assert_eq!(
433 serde_json::to_value(SessionUpdate::SessionMessageChunk(chunk)).unwrap(),
434 wire["update"]
435 );
436 assert_eq!(serde_json::to_value(upsert).unwrap()["content"], json!([]));
437 }
438 let with_identity = json!({"sessionUpdate": "session_message_chunk", "messageId": "m1",
440 "senderSessionId": "parent", "recipientSessionId": "child",
441 "senderMessageId": "sent-1", "recipientMessageId": "received-1",
442 "content": {"type": "text", "text": "hello"}});
443 let decoded: SessionUpdate = serde_json::from_value(with_identity).unwrap();
444 assert_eq!(
445 serde_json::to_value(decoded).unwrap(),
446 json!({"sessionUpdate": "session_message_chunk", "messageId": "m1",
447 "content": {"type": "text", "text": "hello"}})
448 );
449 }
450
451 #[test]
452 fn required_ids_and_chunk_content_with_upsert_patch_semantics() {
453 for (kind, content) in [
454 ("session_message", json!([])),
455 (
456 "session_message_chunk",
457 json!({"type": "text", "text": "hello"}),
458 ),
459 ] {
460 let mut base = json!({"sessionUpdate": kind, "messageId": "m1", "content": content});
461 if kind == "session_message" {
462 base["senderSessionId"] = json!("parent");
463 base["recipientSessionId"] = json!("child");
464 }
465 {
466 let key = "messageId";
467 let mut missing = base.clone();
468 missing.as_object_mut().unwrap().remove(key);
469 assert!(
470 serde_json::from_value::<SessionUpdate>(missing).is_err(),
471 "{kind} {key}"
472 );
473 let mut null = base.clone();
474 null[key] = Value::Null;
475 assert!(
476 serde_json::from_value::<SessionUpdate>(null).is_err(),
477 "{kind} {key}"
478 );
479 let mut non_string = base.clone();
480 non_string[key] = json!(42);
481 assert!(
482 serde_json::from_value::<SessionUpdate>(non_string).is_err(),
483 "{kind} {key}"
484 );
485 }
486 if kind == "session_message_chunk" {
487 for content in [None, Some(Value::Null), Some(json!([]))] {
488 let mut invalid = base.clone();
489 invalid.as_object_mut().unwrap().remove("content");
490 if let Some(content) = content {
491 invalid["content"] = content;
492 }
493 assert!(serde_json::from_value::<SessionUpdate>(invalid).is_err());
494 }
495 } else {
496 for content in [None, Some(Value::Null), Some(json!([])), Some(json!({}))] {
497 let mut wire = base.clone();
498 wire.as_object_mut().unwrap().remove("content");
499 if let Some(content) = content {
500 wire["content"] = content;
501 }
502 let decoded: SessionUpdate = serde_json::from_value(wire.clone()).unwrap();
503 let encoded = serde_json::to_value(decoded).unwrap();
504 if wire["content"].is_object() {
505 wire.as_object_mut().unwrap().remove("content");
506 }
507 assert_eq!(encoded, wire);
508 }
509 }
510 for meta in [None, Some(Value::Null), Some(json!({"tag": "value"}))] {
511 let mut wire = base.clone();
512 if let Some(meta) = meta {
513 wire["_meta"] = meta;
514 }
515 let decoded: SessionUpdate = serde_json::from_value(wire.clone()).unwrap();
516 let encoded = serde_json::to_value(decoded).unwrap();
517 if kind == "session_message" {
518 assert_eq!(encoded, wire);
519 } else if wire["_meta"].is_null() {
520 assert_eq!(encoded, base);
521 } else {
522 assert_eq!(encoded, wire);
523 }
524 }
525 }
526 let metadata_only = json!({"sessionUpdate": "session_message",
527 "messageId": "m1", "senderSessionId": "parent",
528 "recipientSessionId": "child", "_meta": {"tag": "value"}});
529 let decoded: SessionUpdate = serde_json::from_value(metadata_only.clone()).unwrap();
530 assert_eq!(serde_json::to_value(decoded).unwrap(), metadata_only);
531 let cleared = SessionMessage::new("m1")
532 .sender_session_id(SessionId::new("parent"))
533 .recipient_session_id(SessionId::new("child"))
534 .content(None)
535 .meta(None);
536 assert_eq!(
537 serde_json::to_value(cleared).unwrap(),
538 json!({"messageId": "m1", "senderSessionId": "parent",
539 "recipientSessionId": "child", "content": null, "_meta": null})
540 );
541 }
542
543 #[cfg(feature = "schemars")]
544 #[test]
545 fn schemas_require_ids_and_chunk_content_but_not_upsert_content() {
546 let upsert = serde_json::to_value(schemars::schema_for!(SessionMessage)).unwrap();
547 let required = upsert["required"].as_array().unwrap();
548 assert_eq!(required, &vec![json!("messageId")]);
549 let chunk = serde_json::to_value(schemars::schema_for!(SessionMessageChunk)).unwrap();
550 let required = chunk["required"].as_array().unwrap();
551 assert_eq!(required.len(), 2);
552 assert!(required.contains(&json!("messageId")));
553 assert!(required.contains(&json!("content")));
554 }
555
556 #[test]
557 fn endpoints_can_arrive_late_or_be_omitted_from_later_events() {
558 let block = ContentBlock::Text(crate::v2::TextContent::new("hello"));
559 let minimal = SessionMessage::new("m1");
560 let first = SessionMessageChunk::new("m1", block.clone());
561 assert_eq!(
562 serde_json::to_value(&minimal).unwrap(),
563 json!({"messageId": "m1"})
564 );
565 assert_eq!(
566 serde_json::to_value(&first).unwrap(),
567 json!({"messageId": "m1", "content": {"type": "text", "text": "hello"}})
568 );
569 let enriched = SessionMessage::new("m1")
570 .sender_session_id(SessionId::new("parent"))
571 .recipient_session_id(SessionId::new("child"));
572 assert_eq!(
573 enriched.sender_session_id,
574 MaybeUndefined::Value(SessionId::new("parent"))
575 );
576 assert_eq!(
577 enriched.recipient_session_id,
578 MaybeUndefined::Value(SessionId::new("child"))
579 );
580 let later = SessionMessage::new("m1").sender_session_id(SessionId::new("parent"));
581 assert_eq!(
582 later.sender_session_id,
583 MaybeUndefined::Value(SessionId::new("parent"))
584 );
585 assert_eq!(later.recipient_session_id, MaybeUndefined::Undefined);
586 let more = SessionMessageChunk::new("m1", block);
587 for update in [
588 SessionUpdate::SessionMessage(minimal),
589 SessionUpdate::SessionMessageChunk(first),
590 SessionUpdate::SessionMessage(enriched),
591 SessionUpdate::SessionMessage(later),
592 SessionUpdate::SessionMessageChunk(more),
593 ] {
594 let wire = serde_json::to_value(&update).unwrap();
595 let decoded: SessionUpdate = serde_json::from_value(wire.clone()).unwrap();
596 assert_eq!(serde_json::to_value(decoded).unwrap(), wire);
597 }
598 }
599
600 #[test]
601 fn null_endpoints_clear_invalid_are_absent_but_message_id_is_required() {
602 let mut base = json!({"sessionUpdate": "session_message", "messageId": "m1",
603 "senderSessionId": null, "recipientSessionId": 42});
604 let decoded: SessionUpdate = serde_json::from_value(base.clone()).unwrap();
605 let encoded = serde_json::to_value(decoded).unwrap();
606 base.as_object_mut().unwrap().remove("recipientSessionId");
607 assert_eq!(encoded, base);
608 for bad in [Value::Null, json!(42)] {
609 let mut invalid = base.clone();
610 invalid["messageId"] = bad;
611 assert!(serde_json::from_value::<SessionUpdate>(invalid).is_err());
612 }
613 }
614
615 #[test]
616 fn message_references_link_views_and_can_arrive_late() {
617 let block = ContentBlock::Text(crate::v2::TextContent::new("hello"));
618 let incoming = SessionMessage::new("received-1")
619 .sender_session_id(SessionId::new("parent"))
620 .recipient_session_id(SessionId::new("child"))
621 .sender_message_id(MessageId::new("sent-1"))
622 .content(vec![block]);
623 let outgoing =
625 SessionMessage::new("sent-1").recipient_message_id(MessageId::new("received-1"));
626 for (update, wire) in [
627 (
628 SessionUpdate::SessionMessage(incoming),
629 json!({"sessionUpdate": "session_message", "messageId": "received-1",
630 "senderSessionId": "parent", "recipientSessionId": "child",
631 "senderMessageId": "sent-1", "content": [{"type": "text", "text": "hello"}]}),
632 ),
633 (
634 SessionUpdate::SessionMessage(outgoing),
635 json!({"sessionUpdate": "session_message", "messageId": "sent-1",
636 "recipientMessageId": "received-1"}),
637 ),
638 ] {
639 assert_eq!(serde_json::to_value(&update).unwrap(), wire);
640 let decoded: SessionUpdate = serde_json::from_value(wire.clone()).unwrap();
641 assert_eq!(decoded, update);
642 }
643
644 let mut wire = json!({"sessionUpdate": "session_message", "messageId": "m1",
645 "senderMessageId": null, "recipientMessageId": 42});
646 let decoded: SessionUpdate = serde_json::from_value(wire.clone()).unwrap();
647 wire.as_object_mut().unwrap().remove("recipientMessageId");
648 assert_eq!(
649 serde_json::to_value(decoded).unwrap(),
650 wire,
651 "null clears a reference and a malformed one is not supplied"
652 );
653 }
654}
655
656#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
658#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
659#[serde(rename_all = "snake_case")]
660#[non_exhaustive]
661pub enum NoticeSeverity {
662 Info,
664 Warning,
666 Error,
668 #[serde(untagged)]
673 Other(String),
674}
675
676#[serde_as]
684#[skip_serializing_none]
685#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
686#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
687#[serde(rename_all = "camelCase")]
688#[non_exhaustive]
689pub struct Notice {
690 pub severity: NoticeSeverity,
692 #[cfg_attr(feature = "schemars", schemars(length(min = 1)))]
694 pub title: String,
695 #[serde_as(deserialize_as = "DefaultOnError")]
699 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
700 #[serde(default)]
701 pub description: Option<String>,
702 #[serde_as(deserialize_as = "DefaultOnError")]
708 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
709 #[serde(default, rename = "_meta")]
710 pub meta: Option<Meta>,
711}
712
713impl Notice {
714 #[must_use]
716 pub fn new(severity: NoticeSeverity, title: impl Into<String>) -> Self {
717 Self {
718 severity,
719 title: title.into(),
720 description: None,
721 meta: None,
722 }
723 }
724
725 #[must_use]
727 pub fn description(mut self, description: impl IntoOption<String>) -> Self {
728 self.description = description.into_option();
729 self
730 }
731
732 #[must_use]
734 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
735 self.meta = meta.into_option();
736 self
737 }
738}
739
740#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
742#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
743#[serde(transparent)]
744#[from(forward)]
745#[non_exhaustive]
746pub struct CompactionId(pub Arc<str>);
747
748impl CompactionId {
749 #[must_use]
751 pub fn new(id: impl Into<Self>) -> Self {
752 id.into()
753 }
754}
755
756#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
758#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
759#[serde(rename_all = "snake_case")]
760#[non_exhaustive]
761pub enum CompactionStatus {
762 #[default]
764 InProgress,
765 Completed,
767 Failed,
769 Cancelled,
771 #[serde(untagged)]
776 Other(String),
777}
778
779#[serde_as]
787#[skip_serializing_none]
788#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
789#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
790#[serde(rename_all = "camelCase")]
791#[non_exhaustive]
792pub struct CompactionUpdate {
793 pub compaction_id: CompactionId,
795 pub status: CompactionStatus,
797 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<VecSkipError<_>>>")]
799 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
800 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
801 pub summary: MaybeUndefined<Vec<ContentBlock>>,
802 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
804 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
805 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
806 pub error: MaybeUndefined<String>,
807 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
816 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
817 #[serde(
818 rename = "_meta",
819 default,
820 skip_serializing_if = "MaybeUndefined::is_undefined"
821 )]
822 pub meta: MaybeUndefined<Meta>,
823}
824
825impl CompactionUpdate {
826 #[must_use]
828 pub fn new(compaction_id: impl Into<CompactionId>, status: CompactionStatus) -> Self {
829 Self {
830 compaction_id: compaction_id.into(),
831 status,
832 summary: MaybeUndefined::Undefined,
833 error: MaybeUndefined::Undefined,
834 meta: MaybeUndefined::Undefined,
835 }
836 }
837
838 #[must_use]
840 pub fn summary(mut self, summary: impl IntoMaybeUndefined<Vec<ContentBlock>>) -> Self {
841 self.summary = summary.into_maybe_undefined();
842 self
843 }
844
845 #[must_use]
847 pub fn error(mut self, error: impl IntoMaybeUndefined<String>) -> Self {
848 self.error = error.into_maybe_undefined();
849 self
850 }
851
852 #[must_use]
857 pub fn meta(mut self, meta: impl IntoMaybeUndefined<Meta>) -> Self {
858 self.meta = meta.into_maybe_undefined();
859 self
860 }
861}
862
863#[serde_as]
866#[skip_serializing_none]
867#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
868#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
869#[serde(rename_all = "camelCase")]
870#[non_exhaustive]
871pub struct CompactionSummaryChunk {
872 pub compaction_id: CompactionId,
874 pub content: ContentBlock,
876 #[serde_as(deserialize_as = "DefaultOnError")]
883 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
884 #[serde(default, rename = "_meta")]
885 pub meta: Option<Meta>,
886}
887
888impl CompactionSummaryChunk {
889 #[must_use]
891 pub fn new(compaction_id: impl Into<CompactionId>, content: ContentBlock) -> Self {
892 Self {
893 compaction_id: compaction_id.into(),
894 content,
895 meta: None,
896 }
897 }
898
899 #[must_use]
901 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
902 self.meta = meta.into_option();
903 self
904 }
905}
906
907#[cfg(feature = "unstable_session_cursors")]
920#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
921#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
922#[serde(transparent)]
923#[from(forward)]
924#[non_exhaustive]
925pub struct CursorId(pub Arc<str>);
926
927#[cfg(feature = "unstable_session_cursors")]
928impl CursorId {
929 #[must_use]
931 pub fn new(id: impl Into<Self>) -> Self {
932 id.into()
933 }
934}
935
936#[cfg(feature = "unstable_session_cursors")]
952#[serde_as]
953#[skip_serializing_none]
954#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
955#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
956#[serde(rename_all = "camelCase")]
957#[non_exhaustive]
958pub struct CursorUpdate {
959 pub cursor_id: CursorId,
961 #[serde_as(deserialize_as = "DefaultOnError")]
966 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
967 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
968 pub capabilities: MaybeUndefined<CursorCapabilities>,
969 #[serde(default)]
975 pub anchor: Option<CursorAnchor>,
976 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
985 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
986 #[serde(
987 rename = "_meta",
988 default,
989 skip_serializing_if = "MaybeUndefined::is_undefined"
990 )]
991 pub meta: MaybeUndefined<Meta>,
992}
993
994#[cfg(feature = "unstable_session_cursors")]
995impl CursorUpdate {
996 #[must_use]
998 pub fn new(cursor_id: impl Into<CursorId>) -> Self {
999 Self {
1000 cursor_id: cursor_id.into(),
1001 capabilities: MaybeUndefined::Undefined,
1002 anchor: None,
1003 meta: MaybeUndefined::Undefined,
1004 }
1005 }
1006
1007 #[must_use]
1009 pub fn capabilities(
1010 mut self,
1011 capabilities: impl IntoMaybeUndefined<CursorCapabilities>,
1012 ) -> Self {
1013 self.capabilities = capabilities.into_maybe_undefined();
1014 self
1015 }
1016
1017 #[must_use]
1019 pub fn anchor(mut self, anchor: impl IntoOption<CursorAnchor>) -> Self {
1020 self.anchor = anchor.into_option();
1021 self
1022 }
1023
1024 #[must_use]
1029 pub fn meta(mut self, meta: impl IntoMaybeUndefined<Meta>) -> Self {
1030 self.meta = meta.into_maybe_undefined();
1031 self
1032 }
1033}
1034
1035#[cfg(feature = "unstable_session_cursors")]
1046#[serde_as]
1047#[skip_serializing_none]
1048#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1049#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1050#[serde(rename_all = "camelCase")]
1051#[non_exhaustive]
1052pub struct CursorCapabilities {
1053 #[cfg(feature = "unstable_session_fork")]
1058 #[serde_as(deserialize_as = "DefaultOnError")]
1059 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1060 #[serde(default)]
1061 pub fork: Option<CursorForkCapabilities>,
1062 #[serde_as(deserialize_as = "DefaultOnError")]
1068 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1069 #[serde(default)]
1070 #[serde(rename = "_meta")]
1071 pub meta: Option<Meta>,
1072}
1073
1074#[cfg(feature = "unstable_session_cursors")]
1075impl CursorCapabilities {
1076 #[must_use]
1078 pub fn new() -> Self {
1079 Self::default()
1080 }
1081
1082 #[cfg(feature = "unstable_session_fork")]
1084 #[must_use]
1085 pub fn fork(mut self, fork: impl IntoOption<CursorForkCapabilities>) -> Self {
1086 self.fork = fork.into_option();
1087 self
1088 }
1089
1090 #[must_use]
1096 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1097 self.meta = meta.into_option();
1098 self
1099 }
1100}
1101
1102#[cfg(all(
1110 feature = "unstable_session_cursors",
1111 feature = "unstable_session_fork"
1112))]
1113#[serde_as]
1114#[skip_serializing_none]
1115#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1116#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1117#[non_exhaustive]
1118pub struct CursorForkCapabilities {
1119 #[serde_as(deserialize_as = "DefaultOnError")]
1125 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1126 #[serde(default)]
1127 #[serde(rename = "_meta")]
1128 pub meta: Option<Meta>,
1129}
1130
1131#[cfg(all(
1132 feature = "unstable_session_cursors",
1133 feature = "unstable_session_fork"
1134))]
1135impl CursorForkCapabilities {
1136 #[must_use]
1138 pub fn new() -> Self {
1139 Self::default()
1140 }
1141
1142 #[must_use]
1148 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1149 self.meta = meta.into_option();
1150 self
1151 }
1152}
1153
1154#[cfg(feature = "unstable_session_cursors")]
1166#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1167#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1168#[serde(tag = "type", rename_all = "snake_case")]
1169#[non_exhaustive]
1170pub enum CursorAnchor {
1171 UserMessage(CursorMessageAnchor),
1173 AgentMessage(CursorMessageAnchor),
1175 AgentThought(CursorMessageAnchor),
1177 SessionMessage(CursorMessageAnchor),
1179 ToolCall(CursorToolCallAnchor),
1181 Compaction(CursorCompactionAnchor),
1183 #[serde(untagged)]
1192 Other(OtherCursorAnchor),
1193}
1194
1195#[cfg(feature = "unstable_session_cursors")]
1201#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1202#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1203#[serde(rename_all = "snake_case")]
1204#[non_exhaustive]
1205pub enum CursorAnchorPosition {
1206 Before,
1209 After,
1212 #[serde(untagged)]
1218 Other(String),
1219}
1220
1221#[cfg(feature = "unstable_session_cursors")]
1227#[serde_as]
1228#[skip_serializing_none]
1229#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1230#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1231#[serde(rename_all = "camelCase")]
1232#[non_exhaustive]
1233pub struct CursorMessageAnchor {
1234 pub message_id: MessageId,
1236 pub position: CursorAnchorPosition,
1238 #[serde_as(deserialize_as = "DefaultOnError")]
1244 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1245 #[serde(default)]
1246 #[serde(rename = "_meta")]
1247 pub meta: Option<Meta>,
1248}
1249
1250#[cfg(feature = "unstable_session_cursors")]
1251impl CursorMessageAnchor {
1252 #[must_use]
1254 pub fn new(message_id: impl Into<MessageId>, position: CursorAnchorPosition) -> Self {
1255 Self {
1256 message_id: message_id.into(),
1257 position,
1258 meta: None,
1259 }
1260 }
1261
1262 #[must_use]
1268 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1269 self.meta = meta.into_option();
1270 self
1271 }
1272}
1273
1274#[cfg(feature = "unstable_session_cursors")]
1280#[serde_as]
1281#[skip_serializing_none]
1282#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1283#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1284#[serde(rename_all = "camelCase")]
1285#[non_exhaustive]
1286pub struct CursorToolCallAnchor {
1287 pub tool_call_id: ToolCallId,
1289 pub position: CursorAnchorPosition,
1291 #[serde_as(deserialize_as = "DefaultOnError")]
1297 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1298 #[serde(default)]
1299 #[serde(rename = "_meta")]
1300 pub meta: Option<Meta>,
1301}
1302
1303#[cfg(feature = "unstable_session_cursors")]
1304impl CursorToolCallAnchor {
1305 #[must_use]
1307 pub fn new(tool_call_id: impl Into<ToolCallId>, position: CursorAnchorPosition) -> Self {
1308 Self {
1309 tool_call_id: tool_call_id.into(),
1310 position,
1311 meta: None,
1312 }
1313 }
1314
1315 #[must_use]
1321 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1322 self.meta = meta.into_option();
1323 self
1324 }
1325}
1326
1327#[cfg(feature = "unstable_session_cursors")]
1333#[serde_as]
1334#[skip_serializing_none]
1335#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1336#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1337#[serde(rename_all = "camelCase")]
1338#[non_exhaustive]
1339pub struct CursorCompactionAnchor {
1340 pub compaction_id: CompactionId,
1342 pub position: CursorAnchorPosition,
1344 #[serde_as(deserialize_as = "DefaultOnError")]
1350 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1351 #[serde(default)]
1352 #[serde(rename = "_meta")]
1353 pub meta: Option<Meta>,
1354}
1355
1356#[cfg(feature = "unstable_session_cursors")]
1357impl CursorCompactionAnchor {
1358 #[must_use]
1360 pub fn new(compaction_id: impl Into<CompactionId>, position: CursorAnchorPosition) -> Self {
1361 Self {
1362 compaction_id: compaction_id.into(),
1363 position,
1364 meta: None,
1365 }
1366 }
1367
1368 #[must_use]
1374 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1375 self.meta = meta.into_option();
1376 self
1377 }
1378}
1379
1380#[cfg(feature = "unstable_session_cursors")]
1389#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1390#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
1391#[cfg_attr(feature = "schemars", schemars(inline))]
1392#[cfg_attr(feature = "schemars", schemars(transform = other_cursor_anchor_schema))]
1393#[serde(rename_all = "camelCase")]
1394#[non_exhaustive]
1395pub struct OtherCursorAnchor {
1396 #[serde(rename = "type")]
1402 pub type_: String,
1403 #[serde(flatten)]
1406 pub fields: BTreeMap<String, serde_json::Value>,
1407}
1408
1409#[cfg(feature = "unstable_session_cursors")]
1410impl OtherCursorAnchor {
1411 #[must_use]
1413 pub fn new(type_: impl Into<String>, mut fields: BTreeMap<String, serde_json::Value>) -> Self {
1414 fields.remove("type");
1415 Self {
1416 type_: type_.into(),
1417 fields,
1418 }
1419 }
1420}
1421
1422#[cfg(feature = "unstable_session_cursors")]
1423impl<'de> Deserialize<'de> for OtherCursorAnchor {
1424 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1425 where
1426 D: serde::Deserializer<'de>,
1427 {
1428 let mut fields = BTreeMap::<String, serde_json::Value>::deserialize(deserializer)?;
1429 let type_ = fields
1430 .remove("type")
1431 .ok_or_else(|| serde::de::Error::missing_field("type"))?;
1432 let serde_json::Value::String(type_) = type_ else {
1433 return Err(serde::de::Error::custom("`type` must be a string"));
1434 };
1435
1436 if KNOWN_CURSOR_ANCHOR_TYPES.contains(&type_.as_str()) {
1437 return Err(serde::de::Error::custom(format!(
1438 "known cursor anchor `{type_}` did not match its schema"
1439 )));
1440 }
1441
1442 Ok(Self { type_, fields })
1443 }
1444}
1445
1446#[cfg(feature = "unstable_session_cursors")]
1447const KNOWN_CURSOR_ANCHOR_TYPES: &[&str] = &[
1448 "user_message",
1449 "agent_message",
1450 "agent_thought",
1451 "session_message",
1452 "tool_call",
1453 "compaction",
1454];
1455
1456#[cfg(all(feature = "unstable_session_cursors", feature = "schemars"))]
1457fn other_cursor_anchor_schema(schema: &mut Schema) {
1458 super::schema_util::reject_known_string_discriminators(
1459 schema,
1460 "type",
1461 KNOWN_CURSOR_ANCHOR_TYPES,
1462 );
1463}
1464
1465#[serde_as]
1479#[skip_serializing_none]
1480#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1481#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq, Eq)]
1482#[serde(rename_all = "camelCase")]
1483#[non_exhaustive]
1484pub struct ReplayComplete {
1485 #[serde_as(deserialize_as = "DefaultOnError")]
1491 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1492 #[serde(default, rename = "_meta")]
1493 pub meta: Option<Meta>,
1494}
1495
1496impl ReplayComplete {
1497 #[must_use]
1499 pub fn new() -> Self {
1500 Self::default()
1501 }
1502
1503 #[must_use]
1505 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1506 self.meta = meta.into_option();
1507 self
1508 }
1509}
1510
1511#[serde_as]
1546#[skip_serializing_none]
1547#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1548#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1549#[serde(rename_all = "camelCase")]
1550#[non_exhaustive]
1551pub struct SubagentUpdate {
1552 pub session_id: SessionId,
1554 #[serde_as(deserialize_as = "DefaultOnError")]
1559 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1560 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
1561 pub title: MaybeUndefined<String>,
1562 #[serde_as(deserialize_as = "DefaultOnError")]
1567 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1568 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
1569 pub description: MaybeUndefined<String>,
1570 #[serde_as(deserialize_as = "DefaultOnError")]
1575 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1576 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
1577 pub capabilities: MaybeUndefined<SubagentSessionCapabilities>,
1578 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
1584 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1585 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
1586 pub state: MaybeUndefined<StateUpdate>,
1587 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
1593 pub cwd: MaybeUndefined<AbsolutePath>,
1594 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
1601 pub additional_directories: MaybeUndefined<Vec<AbsolutePath>>,
1602 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
1611 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1612 #[serde(
1613 rename = "_meta",
1614 default,
1615 skip_serializing_if = "MaybeUndefined::is_undefined"
1616 )]
1617 pub meta: MaybeUndefined<Meta>,
1618}
1619
1620impl SubagentUpdate {
1621 #[must_use]
1623 pub fn new(session_id: impl Into<SessionId>) -> Self {
1624 Self {
1625 session_id: session_id.into(),
1626 title: MaybeUndefined::Undefined,
1627 description: MaybeUndefined::Undefined,
1628 capabilities: MaybeUndefined::Undefined,
1629 state: MaybeUndefined::Undefined,
1630 cwd: MaybeUndefined::Undefined,
1631 additional_directories: MaybeUndefined::Undefined,
1632 meta: MaybeUndefined::Undefined,
1633 }
1634 }
1635
1636 #[must_use]
1638 pub fn title(mut self, title: impl IntoMaybeUndefined<String>) -> Self {
1639 self.title = title.into_maybe_undefined();
1640 self
1641 }
1642
1643 #[must_use]
1645 pub fn description(mut self, description: impl IntoMaybeUndefined<String>) -> Self {
1646 self.description = description.into_maybe_undefined();
1647 self
1648 }
1649
1650 #[must_use]
1652 pub fn capabilities(
1653 mut self,
1654 capabilities: impl IntoMaybeUndefined<SubagentSessionCapabilities>,
1655 ) -> Self {
1656 self.capabilities = capabilities.into_maybe_undefined();
1657 self
1658 }
1659
1660 #[must_use]
1662 pub fn state(mut self, state: impl IntoMaybeUndefined<StateUpdate>) -> Self {
1663 self.state = state.into_maybe_undefined();
1664 self
1665 }
1666
1667 #[must_use]
1671 pub fn cwd(mut self, cwd: impl IntoMaybeUndefined<AbsolutePath>) -> Self {
1672 self.cwd = cwd.into_maybe_undefined();
1673 self
1674 }
1675
1676 #[must_use]
1680 pub fn additional_directories(
1681 mut self,
1682 additional_directories: impl IntoMaybeUndefined<Vec<AbsolutePath>>,
1683 ) -> Self {
1684 self.additional_directories = additional_directories.into_maybe_undefined();
1685 self
1686 }
1687
1688 #[must_use]
1693 pub fn meta(mut self, meta: impl IntoMaybeUndefined<Meta>) -> Self {
1694 self.meta = meta.into_maybe_undefined();
1695 self
1696 }
1697}
1698
1699#[serde_as]
1706#[skip_serializing_none]
1707#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1708#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1709#[serde(rename_all = "camelCase")]
1710#[non_exhaustive]
1711pub struct SubagentSessionCapabilities {
1712 #[serde_as(deserialize_as = "DefaultOnError")]
1716 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1717 #[serde(default)]
1718 pub cancel: Option<SessionCancelCapabilities>,
1719 #[serde_as(deserialize_as = "DefaultOnError")]
1725 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1726 #[serde(default)]
1727 #[serde(rename = "_meta")]
1728 pub meta: Option<Meta>,
1729}
1730
1731impl SubagentSessionCapabilities {
1732 #[must_use]
1734 pub fn new() -> Self {
1735 Self::default()
1736 }
1737
1738 #[must_use]
1740 pub fn cancel(mut self, cancel: impl IntoOption<SessionCancelCapabilities>) -> Self {
1741 self.cancel = cancel.into_option();
1742 self
1743 }
1744
1745 #[must_use]
1749 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1750 self.meta = meta.into_option();
1751 self
1752 }
1753}
1754
1755#[serde_as]
1759#[skip_serializing_none]
1760#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1761#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1762#[non_exhaustive]
1763pub struct SessionCancelCapabilities {
1764 #[serde_as(deserialize_as = "DefaultOnError")]
1770 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1771 #[serde(default)]
1772 #[serde(rename = "_meta")]
1773 pub meta: Option<Meta>,
1774}
1775
1776impl SessionCancelCapabilities {
1777 #[must_use]
1779 pub fn new() -> Self {
1780 Self::default()
1781 }
1782
1783 #[must_use]
1789 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1790 self.meta = meta.into_option();
1791 self
1792 }
1793}
1794
1795#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1801#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
1802#[cfg_attr(feature = "schemars", schemars(inline))]
1803#[cfg_attr(feature = "schemars", schemars(transform = other_session_update_schema))]
1804#[serde(rename_all = "camelCase")]
1805#[non_exhaustive]
1806pub struct OtherSessionUpdate {
1807 #[serde(rename = "sessionUpdate")]
1813 pub session_update: String,
1814 #[serde(flatten)]
1816 pub fields: BTreeMap<String, serde_json::Value>,
1817}
1818
1819impl OtherSessionUpdate {
1820 #[must_use]
1822 pub fn new(
1823 session_update: impl Into<String>,
1824 mut fields: BTreeMap<String, serde_json::Value>,
1825 ) -> Self {
1826 fields.remove("sessionUpdate");
1827 Self {
1828 session_update: session_update.into(),
1829 fields,
1830 }
1831 }
1832}
1833
1834impl<'de> Deserialize<'de> for OtherSessionUpdate {
1835 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1836 where
1837 D: serde::Deserializer<'de>,
1838 {
1839 let mut fields = BTreeMap::<String, serde_json::Value>::deserialize(deserializer)?;
1840 let session_update = fields
1841 .remove("sessionUpdate")
1842 .ok_or_else(|| serde::de::Error::missing_field("sessionUpdate"))?;
1843 let serde_json::Value::String(session_update) = session_update else {
1844 return Err(serde::de::Error::custom("`sessionUpdate` must be a string"));
1845 };
1846
1847 if is_known_session_update(&session_update) {
1848 return Err(serde::de::Error::custom(format!(
1849 "known session update `{session_update}` did not match its schema"
1850 )));
1851 }
1852
1853 Ok(Self {
1854 session_update,
1855 fields,
1856 })
1857 }
1858}
1859
1860fn is_known_session_update(session_update: &str) -> bool {
1861 if session_update == "notice" {
1862 return true;
1863 }
1864 if matches!(
1865 session_update,
1866 "compaction_update" | "compaction_summary_chunk" | "replay_complete"
1867 ) {
1868 return true;
1869 }
1870 #[cfg(feature = "unstable_plan_operations")]
1871 if session_update == "plan_removed" {
1872 return true;
1873 }
1874 #[cfg(feature = "unstable_prompt_suggestions")]
1875 if session_update == "prompt_suggestions_update" {
1876 return true;
1877 }
1878 #[cfg(feature = "unstable_session_cursors")]
1879 if session_update == "cursor_update" {
1880 return true;
1881 }
1882 if matches!(
1883 session_update,
1884 "subagent_update" | "session_message" | "session_message_chunk"
1885 ) {
1886 return true;
1887 }
1888 matches!(
1889 session_update,
1890 "user_message_chunk"
1891 | "user_message"
1892 | "agent_message_chunk"
1893 | "agent_message"
1894 | "agent_thought_chunk"
1895 | "agent_thought"
1896 | "state_update"
1897 | "tool_call_content_chunk"
1898 | "tool_call_update"
1899 | "terminal_update"
1900 | "terminal_output_chunk"
1901 | "plan_update"
1902 | "available_commands_update"
1903 | "config_option_update"
1904 | "session_info_update"
1905 | "usage_update"
1906 )
1907}
1908
1909#[cfg(feature = "schemars")]
1910fn other_session_update_schema(schema: &mut Schema) {
1911 super::schema_util::reject_known_string_discriminators(
1912 schema,
1913 "sessionUpdate",
1914 &[
1915 "user_message_chunk",
1916 "user_message",
1917 "agent_message_chunk",
1918 "agent_message",
1919 "agent_thought_chunk",
1920 "agent_thought",
1921 "state_update",
1922 "tool_call_content_chunk",
1923 "tool_call_update",
1924 "terminal_update",
1925 "terminal_output_chunk",
1926 "plan_update",
1927 "available_commands_update",
1928 "config_option_update",
1929 "session_info_update",
1930 #[cfg(feature = "unstable_plan_operations")]
1931 "plan_removed",
1932 "usage_update",
1933 "notice",
1934 "compaction_update",
1935 "compaction_summary_chunk",
1936 "replay_complete",
1937 #[cfg(feature = "unstable_prompt_suggestions")]
1938 "prompt_suggestions_update",
1939 #[cfg(feature = "unstable_session_cursors")]
1940 "cursor_update",
1941 "subagent_update",
1942 "session_message",
1943 "session_message_chunk",
1944 ],
1945 );
1946}
1947
1948#[serde_as]
1950#[skip_serializing_none]
1951#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1952#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1953#[serde(rename_all = "camelCase")]
1954#[non_exhaustive]
1955pub struct ConfigOptionUpdate {
1956 #[serde_as(deserialize_as = "VecSkipError<_>")]
1958 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-skip-invalid-items" = true)))]
1959 pub config_options: Vec<SessionConfigOption>,
1960 #[serde_as(deserialize_as = "DefaultOnError")]
1966 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1967 #[serde(default)]
1968 #[serde(rename = "_meta")]
1969 pub meta: Option<Meta>,
1970}
1971
1972impl ConfigOptionUpdate {
1973 #[must_use]
1975 pub fn new(config_options: Vec<SessionConfigOption>) -> Self {
1976 Self {
1977 config_options,
1978 meta: None,
1979 }
1980 }
1981
1982 #[must_use]
1988 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1989 self.meta = meta.into_option();
1990 self
1991 }
1992}
1993
1994#[serde_as]
2003#[skip_serializing_none]
2004#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2005#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2006#[serde(rename_all = "camelCase")]
2007#[non_exhaustive]
2008pub struct SessionInfoUpdate {
2009 #[serde_as(deserialize_as = "DefaultOnError")]
2011 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2012 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
2013 pub title: MaybeUndefined<String>,
2014 #[serde_as(deserialize_as = "DefaultOnError")]
2016 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "format" = "date-time")))]
2017 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
2018 pub updated_at: MaybeUndefined<String>,
2019 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
2028 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2029 #[serde(
2030 rename = "_meta",
2031 default,
2032 skip_serializing_if = "MaybeUndefined::is_undefined"
2033 )]
2034 pub meta: MaybeUndefined<Meta>,
2035}
2036
2037impl SessionInfoUpdate {
2038 #[must_use]
2040 pub fn new() -> Self {
2041 Self::default()
2042 }
2043
2044 #[must_use]
2046 pub fn title(mut self, title: impl IntoMaybeUndefined<String>) -> Self {
2047 self.title = title.into_maybe_undefined();
2048 self
2049 }
2050
2051 #[must_use]
2053 pub fn updated_at(mut self, updated_at: impl IntoMaybeUndefined<String>) -> Self {
2054 self.updated_at = updated_at.into_maybe_undefined();
2055 self
2056 }
2057
2058 #[must_use]
2063 pub fn meta(mut self, meta: impl IntoMaybeUndefined<Meta>) -> Self {
2064 self.meta = meta.into_maybe_undefined();
2065 self
2066 }
2067}
2068
2069#[serde_as]
2071#[skip_serializing_none]
2072#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2073#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
2074#[serde(rename_all = "camelCase")]
2075#[non_exhaustive]
2076pub struct UsageUpdate {
2077 pub used: u64,
2079 pub size: u64,
2081 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
2085 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2086 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
2087 pub cost: MaybeUndefined<Cost>,
2088 #[serde_as(deserialize_as = "DefaultOnError")]
2094 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2095 #[serde(default)]
2096 #[serde(rename = "_meta")]
2097 pub meta: Option<Meta>,
2098}
2099
2100impl UsageUpdate {
2101 #[must_use]
2103 pub fn new(used: u64, size: u64) -> Self {
2104 Self {
2105 used,
2106 size,
2107 cost: MaybeUndefined::Undefined,
2108 meta: None,
2109 }
2110 }
2111
2112 #[must_use]
2114 pub fn cost(mut self, cost: impl IntoMaybeUndefined<Cost>) -> Self {
2115 self.cost = cost.into_maybe_undefined();
2116 self
2117 }
2118
2119 #[must_use]
2125 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2126 self.meta = meta.into_option();
2127 self
2128 }
2129}
2130
2131#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2172#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2173#[serde(tag = "state", rename_all = "snake_case")]
2174#[non_exhaustive]
2175pub enum StateUpdate {
2176 Running(RunningStateUpdate),
2178 Idle(IdleStateUpdate),
2180 RequiresAction(RequiresActionStateUpdate),
2182 Unknown(UnknownStateUpdate),
2185 #[serde(untagged)]
2197 Other(OtherStateUpdate),
2198}
2199
2200impl StateUpdate {
2201 #[must_use]
2209 pub fn background(&self) -> Option<&[BackgroundWork]> {
2210 match self {
2211 Self::Running(state) => state.background.as_deref(),
2212 Self::Idle(state) => state.background.as_deref(),
2213 Self::RequiresAction(state) => state.background.as_deref(),
2214 Self::Unknown(state) => state.background.as_deref(),
2215 Self::Other(_) => None,
2216 }
2217 }
2218}
2219
2220#[serde_as]
2222#[skip_serializing_none]
2223#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2224#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2225#[serde(rename_all = "camelCase")]
2226#[non_exhaustive]
2227pub struct RunningStateUpdate {
2228 #[serde_as(deserialize_as = "DefaultOnError")]
2237 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2238 #[serde(default)]
2239 pub background: Option<Vec<BackgroundWork>>,
2240 #[serde_as(deserialize_as = "DefaultOnError")]
2246 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2247 #[serde(default)]
2248 #[serde(rename = "_meta")]
2249 pub meta: Option<Meta>,
2250}
2251
2252impl RunningStateUpdate {
2253 #[must_use]
2255 pub fn new() -> Self {
2256 Self::default()
2257 }
2258
2259 #[must_use]
2261 pub fn background(mut self, background: impl IntoOption<Vec<BackgroundWork>>) -> Self {
2262 self.background = background.into_option();
2263 self
2264 }
2265
2266 #[must_use]
2272 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2273 self.meta = meta.into_option();
2274 self
2275 }
2276}
2277
2278#[serde_as]
2287#[skip_serializing_none]
2288#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2289#[cfg_attr(feature = "schemars", schemars(transform = idle_state_update_schema))]
2290#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2291#[serde(rename_all = "camelCase")]
2292#[non_exhaustive]
2293pub struct IdleStateUpdate {
2294 #[serde(flatten)]
2296 pub stop_reason: Option<StopReason>,
2297 #[cfg(feature = "unstable_end_turn_token_usage")]
2306 #[serde_as(deserialize_as = "DefaultOnError")]
2307 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2308 #[serde(default)]
2309 pub usage: Option<Box<Usage>>,
2310 #[serde_as(deserialize_as = "DefaultOnError")]
2319 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2320 #[serde(default)]
2321 pub background: Option<Vec<BackgroundWork>>,
2322 #[serde_as(deserialize_as = "DefaultOnError")]
2328 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2329 #[serde(default)]
2330 #[serde(rename = "_meta")]
2331 pub meta: Option<Meta>,
2332}
2333
2334impl IdleStateUpdate {
2335 #[must_use]
2337 pub fn new() -> Self {
2338 Self::default()
2339 }
2340
2341 #[must_use]
2343 pub fn stop_reason(mut self, stop_reason: impl IntoOption<StopReason>) -> Self {
2344 self.stop_reason = stop_reason.into_option();
2345 self
2346 }
2347
2348 #[cfg(feature = "unstable_end_turn_token_usage")]
2354 #[must_use]
2355 pub fn usage(mut self, usage: impl IntoOption<Usage>) -> Self {
2356 self.usage = usage.into_option().map(Box::new);
2357 self
2358 }
2359
2360 #[must_use]
2362 pub fn background(mut self, background: impl IntoOption<Vec<BackgroundWork>>) -> Self {
2363 self.background = background.into_option();
2364 self
2365 }
2366
2367 #[must_use]
2373 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2374 self.meta = meta.into_option();
2375 self
2376 }
2377}
2378
2379#[cfg(feature = "schemars")]
2388fn idle_state_update_schema(schema: &mut Schema) {
2389 if let Some(properties) = schema
2390 .get_mut("properties")
2391 .and_then(serde_json::Value::as_object_mut)
2392 {
2393 properties.insert(
2394 "stopReason".into(),
2395 serde_json::json!({
2396 "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)",
2397 "type": ["string", "null"],
2398 "x-deserialize-default-on-error": true
2399 }),
2400 );
2401 }
2402 let Some(variants) = schema
2403 .get_mut("anyOf")
2404 .and_then(serde_json::Value::as_array_mut)
2405 else {
2406 return;
2407 };
2408 for variant in variants {
2409 if variant.as_object().is_some_and(serde_json::Map::is_empty) {
2410 *variant = serde_json::json!({
2411 "title": "none",
2412 "description": "No stop reason: `stopReason` is omitted or `null`.",
2413 "type": "object",
2414 "properties": {
2415 "stopReason": { "type": "null" }
2416 }
2417 });
2418 }
2419 }
2420}
2421
2422#[serde_as]
2431#[skip_serializing_none]
2432#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2433#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2434#[serde(rename_all = "camelCase")]
2435#[non_exhaustive]
2436pub struct RequiresActionStateUpdate {
2437 #[serde_as(deserialize_as = "DefaultOnError")]
2446 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2447 #[serde(default)]
2448 pub background: Option<Vec<BackgroundWork>>,
2449 #[serde_as(deserialize_as = "DefaultOnError")]
2455 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2456 #[serde(default)]
2457 #[serde(rename = "_meta")]
2458 pub meta: Option<Meta>,
2459}
2460
2461impl RequiresActionStateUpdate {
2462 #[must_use]
2464 pub fn new() -> Self {
2465 Self::default()
2466 }
2467
2468 #[must_use]
2470 pub fn background(mut self, background: impl IntoOption<Vec<BackgroundWork>>) -> Self {
2471 self.background = background.into_option();
2472 self
2473 }
2474
2475 #[must_use]
2481 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2482 self.meta = meta.into_option();
2483 self
2484 }
2485}
2486
2487#[serde_as]
2500#[skip_serializing_none]
2501#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2502#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2503#[serde(rename_all = "camelCase")]
2504#[non_exhaustive]
2505pub struct UnknownStateUpdate {
2506 #[serde_as(deserialize_as = "DefaultOnError")]
2515 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2516 #[serde(default)]
2517 pub background: Option<Vec<BackgroundWork>>,
2518 #[serde_as(deserialize_as = "DefaultOnError")]
2524 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2525 #[serde(default, rename = "_meta")]
2526 pub meta: Option<Meta>,
2527}
2528
2529impl UnknownStateUpdate {
2530 #[must_use]
2532 pub fn new() -> Self {
2533 Self::default()
2534 }
2535
2536 #[must_use]
2538 pub fn background(mut self, background: impl IntoOption<Vec<BackgroundWork>>) -> Self {
2539 self.background = background.into_option();
2540 self
2541 }
2542
2543 #[must_use]
2545 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2546 self.meta = meta.into_option();
2547 self
2548 }
2549}
2550
2551#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2556#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
2557#[cfg_attr(feature = "schemars", schemars(inline))]
2558#[cfg_attr(feature = "schemars", schemars(transform = other_state_update_schema))]
2559#[serde(rename_all = "camelCase")]
2560#[non_exhaustive]
2561pub struct OtherStateUpdate {
2562 #[serde(rename = "state")]
2568 pub state: String,
2569 #[serde(flatten)]
2571 pub fields: BTreeMap<String, serde_json::Value>,
2572}
2573
2574impl OtherStateUpdate {
2575 #[must_use]
2577 pub fn new(state: impl Into<String>, mut fields: BTreeMap<String, serde_json::Value>) -> Self {
2578 fields.remove("state");
2579 Self {
2580 state: state.into(),
2581 fields,
2582 }
2583 }
2584}
2585
2586impl<'de> Deserialize<'de> for OtherStateUpdate {
2587 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2588 where
2589 D: serde::Deserializer<'de>,
2590 {
2591 let mut fields = BTreeMap::<String, serde_json::Value>::deserialize(deserializer)?;
2592 let state = fields
2593 .remove("state")
2594 .ok_or_else(|| serde::de::Error::missing_field("state"))?;
2595 let serde_json::Value::String(state) = state else {
2596 return Err(serde::de::Error::custom("`state` must be a string"));
2597 };
2598
2599 if is_known_state_update(&state) {
2600 return Err(serde::de::Error::custom(format!(
2601 "known state update `{state}` did not match its schema"
2602 )));
2603 }
2604
2605 Ok(Self { state, fields })
2606 }
2607}
2608
2609const KNOWN_STATE_UPDATE_STATES: &[&str] = &["running", "idle", "requires_action", "unknown"];
2610
2611fn is_known_state_update(state: &str) -> bool {
2612 KNOWN_STATE_UPDATE_STATES.contains(&state)
2613}
2614
2615#[cfg(feature = "schemars")]
2616fn other_state_update_schema(schema: &mut Schema) {
2617 super::schema_util::reject_known_string_discriminators(
2618 schema,
2619 "state",
2620 KNOWN_STATE_UPDATE_STATES,
2621 );
2622}
2623
2624#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2633#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2634#[serde(tag = "type", rename_all = "snake_case")]
2635#[non_exhaustive]
2636pub enum BackgroundWork {
2637 Terminal(BackgroundTerminal),
2640 ToolCall(BackgroundToolCall),
2644 Subagent(BackgroundSubagent),
2647 #[serde(untagged)]
2656 Other(OtherBackgroundWork),
2657}
2658
2659#[serde_as]
2661#[skip_serializing_none]
2662#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2663#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2664#[serde(rename_all = "camelCase")]
2665#[non_exhaustive]
2666pub struct BackgroundTerminal {
2667 pub terminal_id: TerminalId,
2669 #[serde_as(deserialize_as = "DefaultOnError")]
2675 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2676 #[serde(default)]
2677 #[serde(rename = "_meta")]
2678 pub meta: Option<Meta>,
2679}
2680
2681impl BackgroundTerminal {
2682 #[must_use]
2684 pub fn new(terminal_id: impl Into<TerminalId>) -> Self {
2685 Self {
2686 terminal_id: terminal_id.into(),
2687 meta: None,
2688 }
2689 }
2690
2691 #[must_use]
2697 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2698 self.meta = meta.into_option();
2699 self
2700 }
2701}
2702
2703#[serde_as]
2705#[skip_serializing_none]
2706#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2707#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2708#[serde(rename_all = "camelCase")]
2709#[non_exhaustive]
2710pub struct BackgroundToolCall {
2711 pub tool_call_id: ToolCallId,
2713 #[serde_as(deserialize_as = "DefaultOnError")]
2719 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2720 #[serde(default)]
2721 #[serde(rename = "_meta")]
2722 pub meta: Option<Meta>,
2723}
2724
2725impl BackgroundToolCall {
2726 #[must_use]
2728 pub fn new(tool_call_id: impl Into<ToolCallId>) -> Self {
2729 Self {
2730 tool_call_id: tool_call_id.into(),
2731 meta: None,
2732 }
2733 }
2734
2735 #[must_use]
2741 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2742 self.meta = meta.into_option();
2743 self
2744 }
2745}
2746
2747#[serde_as]
2749#[skip_serializing_none]
2750#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2751#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2752#[serde(rename_all = "camelCase")]
2753#[non_exhaustive]
2754pub struct BackgroundSubagent {
2755 pub session_id: SessionId,
2757 #[serde_as(deserialize_as = "DefaultOnError")]
2763 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2764 #[serde(default)]
2765 #[serde(rename = "_meta")]
2766 pub meta: Option<Meta>,
2767}
2768
2769impl BackgroundSubagent {
2770 #[must_use]
2772 pub fn new(session_id: impl Into<SessionId>) -> Self {
2773 Self {
2774 session_id: session_id.into(),
2775 meta: None,
2776 }
2777 }
2778
2779 #[must_use]
2785 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2786 self.meta = meta.into_option();
2787 self
2788 }
2789}
2790
2791#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2796#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
2797#[cfg_attr(feature = "schemars", schemars(inline))]
2798#[cfg_attr(feature = "schemars", schemars(transform = other_background_work_schema))]
2799#[serde(rename_all = "camelCase")]
2800#[non_exhaustive]
2801pub struct OtherBackgroundWork {
2802 #[serde(rename = "type")]
2808 pub kind: String,
2809 #[serde(flatten)]
2811 pub fields: BTreeMap<String, serde_json::Value>,
2812}
2813
2814impl OtherBackgroundWork {
2815 #[must_use]
2817 pub fn new(kind: impl Into<String>, mut fields: BTreeMap<String, serde_json::Value>) -> Self {
2818 fields.remove("type");
2819 Self {
2820 kind: kind.into(),
2821 fields,
2822 }
2823 }
2824}
2825
2826impl<'de> Deserialize<'de> for OtherBackgroundWork {
2827 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2828 where
2829 D: serde::Deserializer<'de>,
2830 {
2831 let mut fields = BTreeMap::<String, serde_json::Value>::deserialize(deserializer)?;
2832 let kind = fields
2833 .remove("type")
2834 .ok_or_else(|| serde::de::Error::missing_field("type"))?;
2835 let serde_json::Value::String(kind) = kind else {
2836 return Err(serde::de::Error::custom("`type` must be a string"));
2837 };
2838
2839 if KNOWN_BACKGROUND_WORK_TYPES.contains(&kind.as_str()) {
2840 return Err(serde::de::Error::custom(format!(
2841 "known background work `{kind}` did not match its schema"
2842 )));
2843 }
2844
2845 Ok(Self { kind, fields })
2846 }
2847}
2848
2849const KNOWN_BACKGROUND_WORK_TYPES: &[&str] = &["terminal", "tool_call", "subagent"];
2850
2851#[cfg(feature = "schemars")]
2852fn other_background_work_schema(schema: &mut Schema) {
2853 super::schema_util::reject_known_string_discriminators(
2854 schema,
2855 "type",
2856 KNOWN_BACKGROUND_WORK_TYPES,
2857 );
2858}
2859
2860#[serde_as]
2862#[skip_serializing_none]
2863#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2864#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
2865#[serde(rename_all = "camelCase")]
2866#[non_exhaustive]
2867pub struct Cost {
2868 pub amount: f64,
2870 pub currency: String,
2873 #[serde_as(deserialize_as = "DefaultOnError")]
2879 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2880 #[serde(default)]
2881 #[serde(rename = "_meta")]
2882 pub meta: Option<Meta>,
2883}
2884
2885impl Cost {
2886 #[must_use]
2888 pub fn new(amount: f64, currency: impl Into<String>) -> Self {
2889 Self {
2890 amount,
2891 currency: currency.into(),
2892 meta: None,
2893 }
2894 }
2895
2896 #[must_use]
2902 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2903 self.meta = meta.into_option();
2904 self
2905 }
2906}
2907
2908#[serde_as]
2910#[skip_serializing_none]
2911#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2912#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2913#[serde(rename_all = "camelCase")]
2914#[non_exhaustive]
2915pub struct ContentChunk {
2916 pub message_id: MessageId,
2921 pub content: ContentBlock,
2923 #[serde_as(deserialize_as = "DefaultOnError")]
2930 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2931 #[serde(default)]
2932 #[serde(rename = "_meta")]
2933 pub meta: Option<Meta>,
2934}
2935
2936impl ContentChunk {
2937 #[must_use]
2939 pub fn new(content: ContentBlock, message_id: impl Into<MessageId>) -> Self {
2940 Self {
2941 content,
2942 message_id: message_id.into(),
2943 meta: None,
2944 }
2945 }
2946
2947 #[must_use]
2953 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2954 self.meta = meta.into_option();
2955 self
2956 }
2957}
2958
2959#[serde_as]
2973#[skip_serializing_none]
2974#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2975#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2976#[serde(rename_all = "camelCase")]
2977#[non_exhaustive]
2978pub struct UserMessage {
2979 pub message_id: MessageId,
2981 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<VecSkipError<_>>>")]
2983 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
2984 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
2985 pub content: MaybeUndefined<Vec<ContentBlock>>,
2986 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
2995 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2996 #[serde(
2997 rename = "_meta",
2998 default,
2999 skip_serializing_if = "MaybeUndefined::is_undefined"
3000 )]
3001 pub meta: MaybeUndefined<Meta>,
3002}
3003
3004impl UserMessage {
3005 #[must_use]
3007 pub fn new(message_id: impl Into<MessageId>) -> Self {
3008 Self {
3009 message_id: message_id.into(),
3010 content: MaybeUndefined::Undefined,
3011 meta: MaybeUndefined::Undefined,
3012 }
3013 }
3014
3015 #[must_use]
3017 pub fn content(mut self, content: impl IntoMaybeUndefined<Vec<ContentBlock>>) -> Self {
3018 self.content = content.into_maybe_undefined();
3019 self
3020 }
3021
3022 #[must_use]
3027 pub fn meta(mut self, meta: impl IntoMaybeUndefined<Meta>) -> Self {
3028 self.meta = meta.into_maybe_undefined();
3029 self
3030 }
3031}
3032
3033#[serde_as]
3047#[skip_serializing_none]
3048#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3049#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3050#[serde(rename_all = "camelCase")]
3051#[non_exhaustive]
3052pub struct AgentMessage {
3053 pub message_id: MessageId,
3055 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<VecSkipError<_>>>")]
3057 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
3058 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
3059 pub content: MaybeUndefined<Vec<ContentBlock>>,
3060 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
3069 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3070 #[serde(
3071 rename = "_meta",
3072 default,
3073 skip_serializing_if = "MaybeUndefined::is_undefined"
3074 )]
3075 pub meta: MaybeUndefined<Meta>,
3076}
3077
3078impl AgentMessage {
3079 #[must_use]
3081 pub fn new(message_id: impl Into<MessageId>) -> Self {
3082 Self {
3083 message_id: message_id.into(),
3084 content: MaybeUndefined::Undefined,
3085 meta: MaybeUndefined::Undefined,
3086 }
3087 }
3088
3089 #[must_use]
3091 pub fn content(mut self, content: impl IntoMaybeUndefined<Vec<ContentBlock>>) -> Self {
3092 self.content = content.into_maybe_undefined();
3093 self
3094 }
3095
3096 #[must_use]
3101 pub fn meta(mut self, meta: impl IntoMaybeUndefined<Meta>) -> Self {
3102 self.meta = meta.into_maybe_undefined();
3103 self
3104 }
3105}
3106
3107#[serde_as]
3121#[skip_serializing_none]
3122#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3123#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3124#[serde(rename_all = "camelCase")]
3125#[non_exhaustive]
3126pub struct AgentThought {
3127 pub message_id: MessageId,
3129 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<VecSkipError<_>>>")]
3131 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
3132 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
3133 pub content: MaybeUndefined<Vec<ContentBlock>>,
3134 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
3143 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3144 #[serde(
3145 rename = "_meta",
3146 default,
3147 skip_serializing_if = "MaybeUndefined::is_undefined"
3148 )]
3149 pub meta: MaybeUndefined<Meta>,
3150}
3151
3152impl AgentThought {
3153 #[must_use]
3155 pub fn new(message_id: impl Into<MessageId>) -> Self {
3156 Self {
3157 message_id: message_id.into(),
3158 content: MaybeUndefined::Undefined,
3159 meta: MaybeUndefined::Undefined,
3160 }
3161 }
3162
3163 #[must_use]
3165 pub fn content(mut self, content: impl IntoMaybeUndefined<Vec<ContentBlock>>) -> Self {
3166 self.content = content.into_maybe_undefined();
3167 self
3168 }
3169
3170 #[must_use]
3175 pub fn meta(mut self, meta: impl IntoMaybeUndefined<Meta>) -> Self {
3176 self.meta = meta.into_maybe_undefined();
3177 self
3178 }
3179}
3180
3181#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3187#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
3188#[serde(transparent)]
3189#[from(forward)]
3190#[non_exhaustive]
3191pub struct MessageId(pub Arc<str>);
3192
3193impl MessageId {
3194 #[must_use]
3196 pub fn new(id: impl Into<Self>) -> Self {
3197 id.into()
3198 }
3199}
3200
3201#[cfg(feature = "unstable_prompt_suggestions")]
3218#[serde_as]
3219#[skip_serializing_none]
3220#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3221#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3222#[serde(rename_all = "camelCase")]
3223#[non_exhaustive]
3224pub struct PromptSuggestionsUpdate {
3225 #[serde_as(deserialize_as = "VecSkipError<_>")]
3231 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-skip-invalid-items" = true)))]
3232 pub suggestions: Vec<PromptSuggestion>,
3233 #[serde_as(deserialize_as = "DefaultOnError")]
3239 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3240 #[serde(default)]
3241 #[serde(rename = "_meta")]
3242 pub meta: Option<Meta>,
3243}
3244
3245#[cfg(feature = "unstable_prompt_suggestions")]
3246impl PromptSuggestionsUpdate {
3247 #[must_use]
3251 pub fn new(suggestions: Vec<PromptSuggestion>) -> Self {
3252 Self {
3253 suggestions,
3254 meta: None,
3255 }
3256 }
3257
3258 #[must_use]
3264 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3265 self.meta = meta.into_option();
3266 self
3267 }
3268}
3269
3270#[cfg(feature = "unstable_prompt_suggestions")]
3276#[serde_as]
3277#[skip_serializing_none]
3278#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3279#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3280#[serde(rename_all = "camelCase")]
3281#[non_exhaustive]
3282pub struct PromptSuggestion {
3283 #[cfg_attr(feature = "schemars", schemars(length(min = 1)))]
3295 pub prompt: Vec<ContentBlock>,
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
3308#[cfg(feature = "unstable_prompt_suggestions")]
3309impl PromptSuggestion {
3310 #[must_use]
3312 pub fn new(prompt: Vec<ContentBlock>) -> Self {
3313 Self { prompt, meta: None }
3314 }
3315
3316 #[must_use]
3322 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3323 self.meta = meta.into_option();
3324 self
3325 }
3326}
3327
3328#[serde_as]
3330#[skip_serializing_none]
3331#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3332#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3333#[serde(rename_all = "camelCase")]
3334#[non_exhaustive]
3335pub struct AvailableCommandsUpdate {
3336 #[serde_as(deserialize_as = "VecSkipError<_>")]
3338 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-skip-invalid-items" = true)))]
3339 pub available_commands: Vec<AvailableCommand>,
3340 #[serde_as(deserialize_as = "DefaultOnError")]
3346 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3347 #[serde(default)]
3348 #[serde(rename = "_meta")]
3349 pub meta: Option<Meta>,
3350}
3351
3352impl AvailableCommandsUpdate {
3353 #[must_use]
3355 pub fn new(available_commands: Vec<AvailableCommand>) -> Self {
3356 Self {
3357 available_commands,
3358 meta: None,
3359 }
3360 }
3361
3362 #[must_use]
3368 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3369 self.meta = meta.into_option();
3370 self
3371 }
3372}
3373
3374#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3378#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3379#[serde(tag = "type", rename_all = "snake_case")]
3380#[non_exhaustive]
3381pub enum AvailableCommand {
3382 Command(Command),
3384 #[cfg(feature = "unstable_agent_skills")]
3393 Skill(Skill),
3394 #[serde(untagged)]
3405 Other(OtherAvailableCommand),
3406}
3407
3408impl AvailableCommand {
3409 #[must_use]
3411 pub fn name(&self) -> &str {
3412 match self {
3413 Self::Command(c) => &c.name,
3414 #[cfg(feature = "unstable_agent_skills")]
3415 Self::Skill(c) => &c.name,
3416 Self::Other(c) => &c.name,
3417 }
3418 }
3419
3420 #[must_use]
3422 pub fn description(&self) -> &str {
3423 match self {
3424 Self::Command(c) => &c.description,
3425 #[cfg(feature = "unstable_agent_skills")]
3426 Self::Skill(c) => &c.description,
3427 Self::Other(c) => &c.description,
3428 }
3429 }
3430
3431 #[must_use]
3437 pub fn meta(&self) -> Option<&Meta> {
3438 match self {
3439 Self::Command(c) => c.meta.as_ref(),
3440 #[cfg(feature = "unstable_agent_skills")]
3441 Self::Skill(c) => c.meta.as_ref(),
3442 Self::Other(c) => c.fields.get("_meta").and_then(serde_json::Value::as_object),
3443 }
3444 }
3445}
3446
3447#[serde_as]
3449#[skip_serializing_none]
3450#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3451#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
3452#[cfg_attr(feature = "schemars", schemars(inline))]
3453#[cfg_attr(feature = "schemars", schemars(transform = other_available_command_schema))]
3454#[serde(rename_all = "camelCase")]
3455#[non_exhaustive]
3456pub struct OtherAvailableCommand {
3457 #[serde(rename = "type")]
3463 pub type_: String,
3464 pub name: String,
3466 pub description: String,
3468 #[serde(flatten)]
3471 pub fields: BTreeMap<String, serde_json::Value>,
3472}
3473
3474impl OtherAvailableCommand {
3475 #[must_use]
3477 pub fn new(
3478 type_: impl Into<String>,
3479 name: impl Into<String>,
3480 description: impl Into<String>,
3481 mut fields: BTreeMap<String, serde_json::Value>,
3482 ) -> Self {
3483 fields.remove("type");
3484 fields.remove("name");
3485 fields.remove("description");
3486 Self {
3487 type_: type_.into(),
3488 name: name.into(),
3489 description: description.into(),
3490 fields,
3491 }
3492 }
3493}
3494
3495impl<'de> Deserialize<'de> for OtherAvailableCommand {
3496 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
3497 where
3498 D: serde::Deserializer<'de>,
3499 {
3500 #[derive(Deserialize)]
3501 struct RawOtherAvailableCommand {
3502 #[serde(rename = "type")]
3503 type_: String,
3504 name: String,
3505 description: String,
3506 #[serde(flatten)]
3507 fields: BTreeMap<String, serde_json::Value>,
3508 }
3509
3510 let raw = RawOtherAvailableCommand::deserialize(deserializer)?;
3511 if is_known_available_command_type(&raw.type_) {
3512 return Err(serde::de::Error::custom(format!(
3513 "known available command type `{}` did not match its schema",
3514 raw.type_
3515 )));
3516 }
3517
3518 Ok(Self {
3519 type_: raw.type_,
3520 name: raw.name,
3521 description: raw.description,
3522 fields: raw.fields,
3523 })
3524 }
3525}
3526
3527const KNOWN_AVAILABLE_COMMAND_TYPES: &[&str] = &[
3528 "command",
3529 #[cfg(feature = "unstable_agent_skills")]
3530 "skill",
3531];
3532
3533fn is_known_available_command_type(type_: &str) -> bool {
3534 KNOWN_AVAILABLE_COMMAND_TYPES.contains(&type_)
3535}
3536
3537#[cfg(feature = "schemars")]
3538fn other_available_command_schema(schema: &mut Schema) {
3539 super::schema_util::reject_known_string_discriminators(
3540 schema,
3541 "type",
3542 KNOWN_AVAILABLE_COMMAND_TYPES,
3543 );
3544}
3545
3546#[serde_as]
3550#[skip_serializing_none]
3551#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3552#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3553#[serde(rename_all = "camelCase")]
3554#[non_exhaustive]
3555pub struct Command {
3556 pub name: String,
3560 pub description: String,
3562 #[serde_as(deserialize_as = "DefaultOnError")]
3566 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3567 #[serde(default)]
3568 pub input: Option<AvailableCommandInput>,
3569 #[serde_as(deserialize_as = "DefaultOnError")]
3575 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3576 #[serde(default)]
3577 #[serde(rename = "_meta")]
3578 pub meta: Option<Meta>,
3579}
3580
3581impl Command {
3582 #[must_use]
3584 pub fn new(name: impl Into<String>, description: impl Into<String>) -> Self {
3585 Self {
3586 name: name.into(),
3587 description: description.into(),
3588 input: None,
3589 meta: None,
3590 }
3591 }
3592
3593 #[must_use]
3595 pub fn input(mut self, input: impl IntoOption<AvailableCommandInput>) -> Self {
3596 self.input = input.into_option();
3597 self
3598 }
3599
3600 #[must_use]
3606 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3607 self.meta = meta.into_option();
3608 self
3609 }
3610}
3611
3612#[cfg(feature = "unstable_agent_skills")]
3628#[serde_as]
3629#[skip_serializing_none]
3630#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3631#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3632#[serde(rename_all = "camelCase")]
3633#[non_exhaustive]
3634pub struct Skill {
3635 pub name: String,
3641 pub description: String,
3643 #[serde_as(deserialize_as = "DefaultOnError")]
3649 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3650 #[serde(default)]
3651 pub path: Option<AbsolutePath>,
3652 #[serde_as(deserialize_as = "DefaultOnError")]
3658 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3659 #[serde(default)]
3660 #[serde(rename = "_meta")]
3661 pub meta: Option<Meta>,
3662}
3663
3664#[cfg(feature = "unstable_agent_skills")]
3665impl Skill {
3666 #[must_use]
3668 pub fn new(name: impl Into<String>, description: impl Into<String>) -> Self {
3669 Self {
3670 name: name.into(),
3671 description: description.into(),
3672 path: None,
3673 meta: None,
3674 }
3675 }
3676
3677 #[must_use]
3680 pub fn path(mut self, path: impl IntoOption<AbsolutePath>) -> Self {
3681 self.path = path.into_option();
3682 self
3683 }
3684
3685 #[must_use]
3691 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3692 self.meta = meta.into_option();
3693 self
3694 }
3695}
3696
3697#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3699#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3700#[serde(tag = "type", rename_all = "snake_case")]
3701#[non_exhaustive]
3702pub enum AvailableCommandInput {
3703 #[serde(rename = "text")]
3705 Text(TextCommandInput),
3706 #[serde(untagged)]
3717 Other(OtherAvailableCommandInput),
3718}
3719
3720#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3722#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
3723#[cfg_attr(feature = "schemars", schemars(inline))]
3724#[cfg_attr(feature = "schemars", schemars(transform = other_available_command_input_schema))]
3725#[serde(rename_all = "camelCase")]
3726#[non_exhaustive]
3727pub struct OtherAvailableCommandInput {
3728 #[serde(rename = "type")]
3734 pub type_: String,
3735 #[serde(flatten)]
3737 pub fields: BTreeMap<String, serde_json::Value>,
3738}
3739
3740impl OtherAvailableCommandInput {
3741 #[must_use]
3743 pub fn new(type_: impl Into<String>, mut fields: BTreeMap<String, serde_json::Value>) -> Self {
3744 fields.remove("type");
3745 Self {
3746 type_: type_.into(),
3747 fields,
3748 }
3749 }
3750}
3751
3752impl<'de> Deserialize<'de> for OtherAvailableCommandInput {
3753 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
3754 where
3755 D: serde::Deserializer<'de>,
3756 {
3757 let mut fields = BTreeMap::<String, serde_json::Value>::deserialize(deserializer)?;
3758 let type_ = fields
3759 .remove("type")
3760 .ok_or_else(|| serde::de::Error::missing_field("type"))?;
3761 let serde_json::Value::String(type_) = type_ else {
3762 return Err(serde::de::Error::custom("`type` must be a string"));
3763 };
3764
3765 if is_known_available_command_input_type(&type_) {
3766 return Err(serde::de::Error::custom(format!(
3767 "known available command input type `{type_}` did not match its schema"
3768 )));
3769 }
3770
3771 Ok(Self { type_, fields })
3772 }
3773}
3774
3775const KNOWN_AVAILABLE_COMMAND_INPUT_TYPES: &[&str] = &["text"];
3776
3777fn is_known_available_command_input_type(type_: &str) -> bool {
3778 KNOWN_AVAILABLE_COMMAND_INPUT_TYPES.contains(&type_)
3779}
3780
3781#[cfg(feature = "schemars")]
3782fn other_available_command_input_schema(schema: &mut Schema) {
3783 super::schema_util::reject_known_string_discriminators(
3784 schema,
3785 "type",
3786 KNOWN_AVAILABLE_COMMAND_INPUT_TYPES,
3787 );
3788}
3789
3790#[serde_as]
3792#[skip_serializing_none]
3793#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3794#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3795#[serde(rename_all = "camelCase")]
3796#[non_exhaustive]
3797pub struct TextCommandInput {
3798 pub hint: String,
3800 #[serde_as(deserialize_as = "DefaultOnError")]
3806 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3807 #[serde(default)]
3808 #[serde(rename = "_meta")]
3809 pub meta: Option<Meta>,
3810}
3811
3812impl TextCommandInput {
3813 #[must_use]
3815 pub fn new(hint: impl Into<String>) -> Self {
3816 Self {
3817 hint: hint.into(),
3818 meta: None,
3819 }
3820 }
3821
3822 #[must_use]
3828 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3829 self.meta = meta.into_option();
3830 self
3831 }
3832}
3833
3834#[serde_as]
3842#[skip_serializing_none]
3843#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3844#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3845#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = SESSION_REQUEST_PERMISSION_METHOD_NAME)))]
3846#[serde(rename_all = "camelCase")]
3847#[non_exhaustive]
3848pub struct RequestPermissionRequest {
3849 pub session_id: SessionId,
3851 pub title: String,
3856 #[serde_as(deserialize_as = "DefaultOnError")]
3862 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3863 #[serde(default)]
3864 pub description: Option<String>,
3865 #[serde(default)]
3869 pub subject: Option<RequestPermissionSubject>,
3870 #[cfg_attr(feature = "schemars", schemars(length(min = 1)))]
3873 pub options: Vec<PermissionOption>,
3874 #[serde_as(deserialize_as = "DefaultOnError")]
3880 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3881 #[serde(default)]
3882 #[serde(rename = "_meta")]
3883 pub meta: Option<Meta>,
3884}
3885
3886impl RequestPermissionRequest {
3887 #[must_use]
3889 pub fn new(
3890 session_id: impl Into<SessionId>,
3891 title: impl Into<String>,
3892 options: Vec<PermissionOption>,
3893 ) -> Self {
3894 Self {
3895 session_id: session_id.into(),
3896 title: title.into(),
3897 description: None,
3898 subject: None,
3899 options,
3900 meta: None,
3901 }
3902 }
3903
3904 #[must_use]
3906 pub fn description(mut self, description: impl IntoOption<String>) -> Self {
3907 self.description = description.into_option();
3908 self
3909 }
3910
3911 #[must_use]
3913 pub fn subject(mut self, subject: impl IntoOption<RequestPermissionSubject>) -> Self {
3914 self.subject = subject.into_option();
3915 self
3916 }
3917
3918 #[must_use]
3924 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3925 self.meta = meta.into_option();
3926 self
3927 }
3928}
3929
3930#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3932#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3933#[serde(tag = "type", rename_all = "snake_case")]
3934#[non_exhaustive]
3935pub enum RequestPermissionSubject {
3936 ToolCall(Box<ToolCallPermissionSubject>),
3938 Command(CommandPermissionSubject),
3940 #[serde(untagged)]
3951 Other(OtherRequestPermissionSubject),
3952}
3953
3954impl From<ToolCallPermissionSubject> for RequestPermissionSubject {
3955 fn from(subject: ToolCallPermissionSubject) -> Self {
3956 Self::ToolCall(Box::new(subject))
3957 }
3958}
3959
3960impl From<ToolCallUpdate> for RequestPermissionSubject {
3961 fn from(tool_call: ToolCallUpdate) -> Self {
3962 ToolCallPermissionSubject::new(tool_call).into()
3963 }
3964}
3965
3966impl From<CommandPermissionSubject> for RequestPermissionSubject {
3967 fn from(subject: CommandPermissionSubject) -> Self {
3968 Self::Command(subject)
3969 }
3970}
3971
3972#[serde_as]
3974#[skip_serializing_none]
3975#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3976#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3977#[serde(rename_all = "camelCase")]
3978#[non_exhaustive]
3979pub struct ToolCallPermissionSubject {
3980 pub tool_call: ToolCallUpdate,
3986 #[serde_as(deserialize_as = "DefaultOnError")]
3992 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3993 #[serde(default)]
3994 #[serde(rename = "_meta")]
3995 pub meta: Option<Meta>,
3996}
3997
3998impl ToolCallPermissionSubject {
3999 #[must_use]
4001 pub fn new(tool_call: ToolCallUpdate) -> Self {
4002 Self {
4003 tool_call,
4004 meta: None,
4005 }
4006 }
4007
4008 #[must_use]
4014 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4015 self.meta = meta.into_option();
4016 self
4017 }
4018}
4019
4020#[serde_as]
4022#[skip_serializing_none]
4023#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4024#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4025#[serde(rename_all = "camelCase")]
4026#[non_exhaustive]
4027pub struct CommandPermissionSubject {
4028 pub command: String,
4030 pub cwd: AbsolutePath,
4032 #[serde_as(deserialize_as = "DefaultOnError")]
4034 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4035 #[serde(default)]
4036 pub tool_call_id: Option<ToolCallId>,
4037 #[serde_as(deserialize_as = "DefaultOnError")]
4039 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4040 #[serde(default)]
4041 pub terminal_id: Option<TerminalId>,
4042 #[serde_as(deserialize_as = "DefaultOnError")]
4048 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4049 #[serde(default)]
4050 #[serde(rename = "_meta")]
4051 pub meta: Option<Meta>,
4052}
4053
4054impl CommandPermissionSubject {
4055 #[must_use]
4057 pub fn new(command: impl Into<String>, cwd: impl Into<AbsolutePath>) -> Self {
4058 Self {
4059 command: command.into(),
4060 cwd: cwd.into(),
4061 tool_call_id: None,
4062 terminal_id: None,
4063 meta: None,
4064 }
4065 }
4066
4067 #[must_use]
4069 pub fn tool_call_id(mut self, tool_call_id: impl IntoOption<ToolCallId>) -> Self {
4070 self.tool_call_id = tool_call_id.into_option();
4071 self
4072 }
4073
4074 #[must_use]
4076 pub fn terminal_id(mut self, terminal_id: impl IntoOption<TerminalId>) -> Self {
4077 self.terminal_id = terminal_id.into_option();
4078 self
4079 }
4080
4081 #[must_use]
4083 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4084 self.meta = meta.into_option();
4085 self
4086 }
4087}
4088
4089#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4091#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
4092#[cfg_attr(feature = "schemars", schemars(inline))]
4093#[cfg_attr(feature = "schemars", schemars(transform = other_request_permission_subject_schema))]
4094#[serde(rename_all = "camelCase")]
4095#[non_exhaustive]
4096pub struct OtherRequestPermissionSubject {
4097 #[serde(rename = "type")]
4103 pub type_: String,
4104 #[serde(flatten)]
4106 pub fields: BTreeMap<String, serde_json::Value>,
4107}
4108
4109impl OtherRequestPermissionSubject {
4110 #[must_use]
4112 pub fn new(type_: impl Into<String>, mut fields: BTreeMap<String, serde_json::Value>) -> Self {
4113 fields.remove("type");
4114 Self {
4115 type_: type_.into(),
4116 fields,
4117 }
4118 }
4119}
4120
4121impl<'de> Deserialize<'de> for OtherRequestPermissionSubject {
4122 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
4123 where
4124 D: serde::Deserializer<'de>,
4125 {
4126 let mut fields = BTreeMap::<String, serde_json::Value>::deserialize(deserializer)?;
4127 let type_ = fields
4128 .remove("type")
4129 .ok_or_else(|| serde::de::Error::missing_field("type"))?;
4130 let serde_json::Value::String(type_) = type_ else {
4131 return Err(serde::de::Error::custom("`type` must be a string"));
4132 };
4133
4134 if is_known_request_permission_subject_type(&type_) {
4135 return Err(serde::de::Error::custom(format!(
4136 "known request permission subject `{type_}` did not match its schema"
4137 )));
4138 }
4139
4140 Ok(Self { type_, fields })
4141 }
4142}
4143
4144fn is_known_request_permission_subject_type(type_: &str) -> bool {
4145 matches!(type_, "tool_call" | "command")
4146}
4147
4148#[cfg(feature = "schemars")]
4149fn other_request_permission_subject_schema(schema: &mut Schema) {
4150 super::schema_util::reject_known_string_discriminators(
4151 schema,
4152 "type",
4153 &["tool_call", "command"],
4154 );
4155}
4156
4157#[serde_as]
4159#[skip_serializing_none]
4160#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4161#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4162#[serde(rename_all = "camelCase")]
4163#[non_exhaustive]
4164pub struct PermissionOption {
4165 pub option_id: PermissionOptionId,
4167 pub name: String,
4169 pub kind: PermissionOptionKind,
4171 #[serde_as(deserialize_as = "DefaultOnError")]
4177 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4178 #[serde(default)]
4179 #[serde(rename = "_meta")]
4180 pub meta: Option<Meta>,
4181}
4182
4183impl PermissionOption {
4184 #[must_use]
4186 pub fn new(
4187 option_id: impl Into<PermissionOptionId>,
4188 name: impl Into<String>,
4189 kind: PermissionOptionKind,
4190 ) -> Self {
4191 Self {
4192 option_id: option_id.into(),
4193 name: name.into(),
4194 kind,
4195 meta: None,
4196 }
4197 }
4198
4199 #[must_use]
4205 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4206 self.meta = meta.into_option();
4207 self
4208 }
4209}
4210
4211#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4213#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
4214#[serde(transparent)]
4215#[from(forward)]
4216#[non_exhaustive]
4217pub struct PermissionOptionId(pub Arc<str>);
4218
4219impl PermissionOptionId {
4220 #[must_use]
4222 pub fn new(id: impl Into<Self>) -> Self {
4223 id.into()
4224 }
4225}
4226
4227#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4231#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4232#[serde(rename_all = "snake_case")]
4233#[non_exhaustive]
4234pub enum PermissionOptionKind {
4235 AllowOnce,
4237 AllowAlways,
4239 RejectOnce,
4241 RejectAlways,
4243 #[serde(untagged)]
4249 Other(String),
4250}
4251
4252#[serde_as]
4254#[skip_serializing_none]
4255#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4256#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4257#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = SESSION_REQUEST_PERMISSION_METHOD_NAME)))]
4258#[serde(rename_all = "camelCase")]
4259#[non_exhaustive]
4260pub struct RequestPermissionResponse {
4261 pub outcome: RequestPermissionOutcome,
4263 #[serde_as(deserialize_as = "DefaultOnError")]
4269 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4270 #[serde(default)]
4271 #[serde(rename = "_meta")]
4272 pub meta: Option<Meta>,
4273}
4274
4275impl RequestPermissionResponse {
4276 #[must_use]
4278 pub fn new(outcome: RequestPermissionOutcome) -> Self {
4279 Self {
4280 outcome,
4281 meta: None,
4282 }
4283 }
4284
4285 #[must_use]
4291 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4292 self.meta = meta.into_option();
4293 self
4294 }
4295}
4296
4297#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4299#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4300#[serde(tag = "outcome", rename_all = "snake_case")]
4301#[non_exhaustive]
4302pub enum RequestPermissionOutcome {
4303 Cancelled(CancelledPermissionOutcome),
4314 #[serde(rename_all = "camelCase")]
4319 Selected(SelectedPermissionOutcome),
4320 #[serde(untagged)]
4331 Other(OtherRequestPermissionOutcome),
4332}
4333
4334#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4340#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
4341#[cfg_attr(feature = "schemars", schemars(inline))]
4342#[cfg_attr(feature = "schemars", schemars(transform = other_request_permission_outcome_schema))]
4343#[serde(rename_all = "camelCase")]
4344#[non_exhaustive]
4345pub struct OtherRequestPermissionOutcome {
4346 pub outcome: String,
4352 #[serde(flatten)]
4354 pub fields: BTreeMap<String, serde_json::Value>,
4355}
4356
4357impl OtherRequestPermissionOutcome {
4358 #[must_use]
4360 pub fn new(
4361 outcome: impl Into<String>,
4362 mut fields: BTreeMap<String, serde_json::Value>,
4363 ) -> Self {
4364 fields.remove("outcome");
4365 Self {
4366 outcome: outcome.into(),
4367 fields,
4368 }
4369 }
4370}
4371
4372impl<'de> Deserialize<'de> for OtherRequestPermissionOutcome {
4373 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
4374 where
4375 D: serde::Deserializer<'de>,
4376 {
4377 let mut fields = BTreeMap::<String, serde_json::Value>::deserialize(deserializer)?;
4378 let outcome = fields
4379 .remove("outcome")
4380 .ok_or_else(|| serde::de::Error::missing_field("outcome"))?;
4381 let serde_json::Value::String(outcome) = outcome else {
4382 return Err(serde::de::Error::custom("`outcome` must be a string"));
4383 };
4384
4385 if is_known_request_permission_outcome(&outcome) {
4386 return Err(serde::de::Error::custom(format!(
4387 "known request permission outcome `{outcome}` did not match its schema"
4388 )));
4389 }
4390
4391 Ok(Self { outcome, fields })
4392 }
4393}
4394
4395fn is_known_request_permission_outcome(outcome: &str) -> bool {
4396 matches!(outcome, "cancelled" | "selected")
4397}
4398
4399#[cfg(feature = "schemars")]
4400fn other_request_permission_outcome_schema(schema: &mut Schema) {
4401 super::schema_util::reject_known_string_discriminators(
4402 schema,
4403 "outcome",
4404 &["cancelled", "selected"],
4405 );
4406}
4407
4408#[serde_as]
4410#[skip_serializing_none]
4411#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4412#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4413#[serde(rename_all = "camelCase")]
4414#[non_exhaustive]
4415pub struct CancelledPermissionOutcome {
4416 #[serde_as(deserialize_as = "DefaultOnError")]
4422 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4423 #[serde(default)]
4424 #[serde(rename = "_meta")]
4425 pub meta: Option<Meta>,
4426}
4427
4428impl CancelledPermissionOutcome {
4429 #[must_use]
4431 pub fn new() -> Self {
4432 Self::default()
4433 }
4434
4435 #[must_use]
4441 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4442 self.meta = meta.into_option();
4443 self
4444 }
4445}
4446
4447impl From<CancelledPermissionOutcome> for RequestPermissionOutcome {
4448 fn from(outcome: CancelledPermissionOutcome) -> Self {
4449 Self::Cancelled(outcome)
4450 }
4451}
4452
4453#[serde_as]
4455#[skip_serializing_none]
4456#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4457#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4458#[serde(rename_all = "camelCase")]
4459#[non_exhaustive]
4460pub struct SelectedPermissionOutcome {
4461 pub option_id: PermissionOptionId,
4463 #[serde_as(deserialize_as = "DefaultOnError")]
4469 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4470 #[serde(default)]
4471 #[serde(rename = "_meta")]
4472 pub meta: Option<Meta>,
4473}
4474
4475impl SelectedPermissionOutcome {
4476 #[must_use]
4478 pub fn new(option_id: impl Into<PermissionOptionId>) -> Self {
4479 Self {
4480 option_id: option_id.into(),
4481 meta: None,
4482 }
4483 }
4484
4485 #[must_use]
4491 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4492 self.meta = meta.into_option();
4493 self
4494 }
4495}
4496
4497#[serde_as]
4506#[skip_serializing_none]
4507#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4508#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4509#[serde(rename_all = "camelCase")]
4510#[non_exhaustive]
4511pub struct ClientCapabilities {
4512 #[serde_as(deserialize_as = "DefaultOnError")]
4519 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4520 #[serde(default)]
4521 pub auth: Option<ClientAuthCapabilities>,
4522 #[serde_as(deserialize_as = "DefaultOnError")]
4528 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4529 #[serde(default)]
4530 pub elicitation: Option<ElicitationCapabilities>,
4531 #[cfg(any(
4541 feature = "unstable_prompt_suggestions",
4542 feature = "unstable_agent_skills"
4543 ))]
4544 #[serde_as(deserialize_as = "DefaultOnError")]
4545 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4546 #[serde(default)]
4547 pub session: Option<ClientSessionCapabilities>,
4548
4549 #[serde_as(deserialize_as = "DefaultOnError")]
4555 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4556 #[serde(default)]
4557 #[serde(rename = "_meta")]
4558 pub meta: Option<Meta>,
4559}
4560
4561impl ClientCapabilities {
4562 #[must_use]
4564 pub fn new() -> Self {
4565 Self::default()
4566 }
4567
4568 #[must_use]
4572 pub fn auth(mut self, auth: impl IntoOption<ClientAuthCapabilities>) -> Self {
4573 self.auth = auth.into_option();
4574 self
4575 }
4576
4577 #[must_use]
4580 pub fn elicitation(mut self, elicitation: impl IntoOption<ElicitationCapabilities>) -> Self {
4581 self.elicitation = elicitation.into_option();
4582 self
4583 }
4584
4585 #[cfg(any(
4591 feature = "unstable_prompt_suggestions",
4592 feature = "unstable_agent_skills"
4593 ))]
4594 #[must_use]
4595 pub fn session(mut self, session: impl IntoOption<ClientSessionCapabilities>) -> Self {
4596 self.session = session.into_option();
4597 self
4598 }
4599
4600 #[must_use]
4606 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4607 self.meta = meta.into_option();
4608 self
4609 }
4610}
4611
4612#[cfg(any(
4622 feature = "unstable_prompt_suggestions",
4623 feature = "unstable_agent_skills"
4624))]
4625#[serde_as]
4626#[skip_serializing_none]
4627#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4628#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4629#[serde(rename_all = "camelCase")]
4630#[non_exhaustive]
4631pub struct ClientSessionCapabilities {
4632 #[cfg(feature = "unstable_prompt_suggestions")]
4638 #[serde_as(deserialize_as = "DefaultOnError")]
4639 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4640 #[serde(default)]
4641 pub prompt_suggestions: Option<PromptSuggestionsCapabilities>,
4642 #[cfg(feature = "unstable_agent_skills")]
4647 #[serde_as(deserialize_as = "DefaultOnError")]
4648 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4649 #[serde(default)]
4650 pub commands: Option<CommandsCapabilities>,
4651 #[serde_as(deserialize_as = "DefaultOnError")]
4657 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4658 #[serde(default)]
4659 #[serde(rename = "_meta")]
4660 pub meta: Option<Meta>,
4661}
4662
4663#[cfg(any(
4664 feature = "unstable_prompt_suggestions",
4665 feature = "unstable_agent_skills"
4666))]
4667impl ClientSessionCapabilities {
4668 #[must_use]
4670 pub fn new() -> Self {
4671 Self::default()
4672 }
4673
4674 #[cfg(feature = "unstable_prompt_suggestions")]
4676 #[must_use]
4677 pub fn prompt_suggestions(
4678 mut self,
4679 prompt_suggestions: impl IntoOption<PromptSuggestionsCapabilities>,
4680 ) -> Self {
4681 self.prompt_suggestions = prompt_suggestions.into_option();
4682 self
4683 }
4684
4685 #[cfg(feature = "unstable_agent_skills")]
4687 #[must_use]
4688 pub fn commands(mut self, commands: impl IntoOption<CommandsCapabilities>) -> Self {
4689 self.commands = commands.into_option();
4690 self
4691 }
4692
4693 #[must_use]
4699 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4700 self.meta = meta.into_option();
4701 self
4702 }
4703}
4704
4705#[cfg(feature = "unstable_agent_skills")]
4715#[serde_as]
4716#[skip_serializing_none]
4717#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4718#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4719#[serde(rename_all = "camelCase")]
4720#[non_exhaustive]
4721pub struct CommandsCapabilities {
4722 #[serde_as(deserialize_as = "DefaultOnError")]
4728 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4729 #[serde(default)]
4730 pub skill: Option<CommandsSkillCapabilities>,
4731 #[serde_as(deserialize_as = "DefaultOnError")]
4737 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4738 #[serde(default)]
4739 #[serde(rename = "_meta")]
4740 pub meta: Option<Meta>,
4741}
4742
4743#[cfg(feature = "unstable_agent_skills")]
4744impl CommandsCapabilities {
4745 #[must_use]
4747 pub fn new() -> Self {
4748 Self::default()
4749 }
4750
4751 #[must_use]
4753 pub fn skill(mut self, skill: impl IntoOption<CommandsSkillCapabilities>) -> Self {
4754 self.skill = skill.into_option();
4755 self
4756 }
4757
4758 #[must_use]
4764 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4765 self.meta = meta.into_option();
4766 self
4767 }
4768}
4769
4770#[cfg(feature = "unstable_agent_skills")]
4779#[serde_as]
4780#[skip_serializing_none]
4781#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4782#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4783#[non_exhaustive]
4784pub struct CommandsSkillCapabilities {
4785 #[serde_as(deserialize_as = "DefaultOnError")]
4791 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4792 #[serde(default)]
4793 #[serde(rename = "_meta")]
4794 pub meta: Option<Meta>,
4795}
4796
4797#[cfg(feature = "unstable_agent_skills")]
4798impl CommandsSkillCapabilities {
4799 #[must_use]
4801 pub fn new() -> Self {
4802 Self::default()
4803 }
4804
4805 #[must_use]
4811 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4812 self.meta = meta.into_option();
4813 self
4814 }
4815}
4816
4817#[cfg(feature = "unstable_prompt_suggestions")]
4828#[serde_as]
4829#[skip_serializing_none]
4830#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4831#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4832#[serde(rename_all = "camelCase")]
4833#[non_exhaustive]
4834pub struct PromptSuggestionsCapabilities {
4835 #[serde_as(deserialize_as = "DefaultOnError")]
4840 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4841 #[serde(default)]
4842 pub image: Option<PromptSuggestionsImageCapabilities>,
4843 #[serde_as(deserialize_as = "DefaultOnError")]
4848 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4849 #[serde(default)]
4850 pub audio: Option<PromptSuggestionsAudioCapabilities>,
4851 #[serde_as(deserialize_as = "DefaultOnError")]
4857 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4858 #[serde(default)]
4859 pub embedded_context: Option<PromptSuggestionsEmbeddedContextCapabilities>,
4860 #[serde_as(deserialize_as = "DefaultOnError")]
4866 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4867 #[serde(default)]
4868 #[serde(rename = "_meta")]
4869 pub meta: Option<Meta>,
4870}
4871
4872#[cfg(feature = "unstable_prompt_suggestions")]
4873impl PromptSuggestionsCapabilities {
4874 #[must_use]
4876 pub fn new() -> Self {
4877 Self::default()
4878 }
4879
4880 #[must_use]
4882 pub fn image(mut self, image: impl IntoOption<PromptSuggestionsImageCapabilities>) -> Self {
4883 self.image = image.into_option();
4884 self
4885 }
4886
4887 #[must_use]
4889 pub fn audio(mut self, audio: impl IntoOption<PromptSuggestionsAudioCapabilities>) -> Self {
4890 self.audio = audio.into_option();
4891 self
4892 }
4893
4894 #[must_use]
4896 pub fn embedded_context(
4897 mut self,
4898 embedded_context: impl IntoOption<PromptSuggestionsEmbeddedContextCapabilities>,
4899 ) -> Self {
4900 self.embedded_context = embedded_context.into_option();
4901 self
4902 }
4903
4904 #[must_use]
4910 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4911 self.meta = meta.into_option();
4912 self
4913 }
4914}
4915
4916#[cfg(feature = "unstable_prompt_suggestions")]
4924#[serde_as]
4925#[skip_serializing_none]
4926#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4927#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4928#[non_exhaustive]
4929pub struct PromptSuggestionsImageCapabilities {
4930 #[serde_as(deserialize_as = "DefaultOnError")]
4936 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4937 #[serde(default)]
4938 #[serde(rename = "_meta")]
4939 pub meta: Option<Meta>,
4940}
4941
4942#[cfg(feature = "unstable_prompt_suggestions")]
4943impl PromptSuggestionsImageCapabilities {
4944 #[must_use]
4946 pub fn new() -> Self {
4947 Self::default()
4948 }
4949
4950 #[must_use]
4956 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4957 self.meta = meta.into_option();
4958 self
4959 }
4960}
4961
4962#[cfg(feature = "unstable_prompt_suggestions")]
4970#[serde_as]
4971#[skip_serializing_none]
4972#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4973#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4974#[non_exhaustive]
4975pub struct PromptSuggestionsAudioCapabilities {
4976 #[serde_as(deserialize_as = "DefaultOnError")]
4982 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4983 #[serde(default)]
4984 #[serde(rename = "_meta")]
4985 pub meta: Option<Meta>,
4986}
4987
4988#[cfg(feature = "unstable_prompt_suggestions")]
4989impl PromptSuggestionsAudioCapabilities {
4990 #[must_use]
4992 pub fn new() -> Self {
4993 Self::default()
4994 }
4995
4996 #[must_use]
5002 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5003 self.meta = meta.into_option();
5004 self
5005 }
5006}
5007
5008#[cfg(feature = "unstable_prompt_suggestions")]
5017#[serde_as]
5018#[skip_serializing_none]
5019#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5020#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5021#[non_exhaustive]
5022pub struct PromptSuggestionsEmbeddedContextCapabilities {
5023 #[serde_as(deserialize_as = "DefaultOnError")]
5029 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5030 #[serde(default)]
5031 #[serde(rename = "_meta")]
5032 pub meta: Option<Meta>,
5033}
5034
5035#[cfg(feature = "unstable_prompt_suggestions")]
5036impl PromptSuggestionsEmbeddedContextCapabilities {
5037 #[must_use]
5039 pub fn new() -> Self {
5040 Self::default()
5041 }
5042
5043 #[must_use]
5049 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5050 self.meta = meta.into_option();
5051 self
5052 }
5053}
5054
5055#[serde_as]
5061#[skip_serializing_none]
5062#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5063#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5064#[serde(rename_all = "camelCase")]
5065#[non_exhaustive]
5066pub struct ClientAuthCapabilities {
5067 #[serde_as(deserialize_as = "DefaultOnError")]
5074 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5075 #[serde(default)]
5076 pub terminal: Option<TerminalAuthCapabilities>,
5077 #[serde_as(deserialize_as = "DefaultOnError")]
5083 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5084 #[serde(default)]
5085 #[serde(rename = "_meta")]
5086 pub meta: Option<Meta>,
5087}
5088
5089impl ClientAuthCapabilities {
5090 #[must_use]
5092 pub fn new() -> Self {
5093 Self::default()
5094 }
5095
5096 #[must_use]
5104 pub fn terminal(mut self, terminal: impl IntoOption<TerminalAuthCapabilities>) -> Self {
5105 self.terminal = terminal.into_option();
5106 self
5107 }
5108
5109 #[must_use]
5115 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5116 self.meta = meta.into_option();
5117 self
5118 }
5119}
5120
5121#[serde_as]
5127#[skip_serializing_none]
5128#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5129#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5130#[non_exhaustive]
5131pub struct TerminalAuthCapabilities {
5132 #[serde_as(deserialize_as = "DefaultOnError")]
5138 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5139 #[serde(default)]
5140 #[serde(rename = "_meta")]
5141 pub meta: Option<Meta>,
5142}
5143
5144impl TerminalAuthCapabilities {
5145 #[must_use]
5147 pub fn new() -> Self {
5148 Self::default()
5149 }
5150
5151 #[must_use]
5157 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5158 self.meta = meta.into_option();
5159 self
5160 }
5161}
5162
5163#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5169#[non_exhaustive]
5170pub struct ClientMethodNames {
5171 pub session_request_permission: &'static str,
5173 pub session_update: &'static str,
5175 #[cfg(feature = "unstable_mcp_over_acp")]
5177 pub mcp_message: &'static str,
5178 pub elicitation_create: &'static str,
5180 pub elicitation_complete: &'static str,
5182 #[cfg(feature = "unstable_auth_status")]
5184 pub auth_status_update: &'static str,
5185}
5186
5187pub const CLIENT_METHOD_NAMES: ClientMethodNames = ClientMethodNames {
5189 session_update: SESSION_UPDATE_NOTIFICATION,
5190 session_request_permission: SESSION_REQUEST_PERMISSION_METHOD_NAME,
5191 #[cfg(feature = "unstable_mcp_over_acp")]
5192 mcp_message: MCP_MESSAGE_METHOD_NAME,
5193 elicitation_create: ELICITATION_CREATE_METHOD_NAME,
5194 elicitation_complete: ELICITATION_COMPLETE_NOTIFICATION,
5195 #[cfg(feature = "unstable_auth_status")]
5196 auth_status_update: AUTH_STATUS_UPDATE_NOTIFICATION,
5197};
5198
5199pub(crate) const SESSION_UPDATE_NOTIFICATION: &str = "session/update";
5201pub(crate) const SESSION_REQUEST_PERMISSION_METHOD_NAME: &str = "session/request_permission";
5203pub(crate) const ELICITATION_CREATE_METHOD_NAME: &str = "elicitation/create";
5205pub(crate) const ELICITATION_COMPLETE_NOTIFICATION: &str = "elicitation/complete";
5207#[cfg(feature = "unstable_auth_status")]
5209pub(crate) const AUTH_STATUS_UPDATE_NOTIFICATION: &str = "auth/status_update";
5210
5211#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5218#[derive(Clone, Debug, Serialize, Deserialize)]
5219#[serde(untagged)]
5220#[cfg_attr(feature = "schemars", schemars(inline))]
5221#[non_exhaustive]
5222pub enum AgentRequest {
5223 RequestPermissionRequest(Box<RequestPermissionRequest>),
5235 CreateElicitationRequest(Box<CreateElicitationRequest>),
5239 #[cfg(feature = "unstable_mcp_over_acp")]
5245 MessageMcpRequest(Box<MessageMcpRequest>),
5246 ExtMethodRequest(Box<ExtRequest>),
5254}
5255
5256impl_request_dispatch! {
5257 AgentRequest => ClientResponse {
5258 RequestPermissionRequest => RequestPermissionResponse: CLIENT_METHOD_NAMES.session_request_permission,
5259 CreateElicitationRequest => CreateElicitationResponse: CLIENT_METHOD_NAMES.elicitation_create,
5260 #[cfg(feature = "unstable_mcp_over_acp")]
5261 MessageMcpRequest => MessageMcpResponse: CLIENT_METHOD_NAMES.mcp_message,
5262 }
5263 extension ExtMethodRequest(Box<ExtRequest>) => ExtMethodResponse;
5264}
5265
5266#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5273#[derive(Clone, Debug, Serialize, Deserialize)]
5274#[serde(untagged)]
5275#[cfg_attr(feature = "schemars", schemars(inline))]
5276#[non_exhaustive]
5277pub enum ClientResponse {
5278 RequestPermissionResponse(Box<RequestPermissionResponse>),
5280 CreateElicitationResponse(Box<CreateElicitationResponse>),
5282 #[cfg(feature = "unstable_mcp_over_acp")]
5284 MessageMcpResponse(Box<MessageMcpResponse>),
5285 ExtMethodResponse(Box<ExtResponse>),
5287}
5288
5289#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5296#[derive(Clone, Debug, Serialize, Deserialize)]
5297#[serde(untagged)]
5298#[cfg_attr(feature = "schemars", schemars(inline))]
5299#[non_exhaustive]
5300pub enum AgentNotification {
5301 UpdateSessionNotification(Box<UpdateSessionNotification>),
5314 CompleteElicitationNotification(Box<CompleteElicitationNotification>),
5318 #[cfg(feature = "unstable_auth_status")]
5326 AuthStatusUpdateNotification(Box<AuthStatusUpdateNotification>),
5327 ExtNotification(Box<ExtNotification>),
5335}
5336
5337impl_message_dispatch! {
5338 AgentNotification {
5339 UpdateSessionNotification => CLIENT_METHOD_NAMES.session_update,
5340 CompleteElicitationNotification => CLIENT_METHOD_NAMES.elicitation_complete,
5341 #[cfg(feature = "unstable_auth_status")]
5342 AuthStatusUpdateNotification => CLIENT_METHOD_NAMES.auth_status_update,
5343 }
5344 extension ExtNotification(Box<ExtNotification>);
5345}
5346
5347#[cfg(test)]
5348mod tests {
5349
5350 #[test]
5351 fn background_list_round_trips_on_state_updates() {
5352 use serde_json::json;
5353 let idle = super::StateUpdate::Idle(super::IdleStateUpdate::new().background(vec![
5354 super::BackgroundWork::Terminal(super::BackgroundTerminal::new("term_003")),
5355 super::BackgroundWork::ToolCall(super::BackgroundToolCall::new("call_012")),
5356 ]));
5357 let wire = json!({
5358 "state": "idle",
5359 "background": [
5360 { "type": "terminal", "terminalId": "term_003" },
5361 { "type": "tool_call", "toolCallId": "call_012" }
5362 ]
5363 });
5364 assert_eq!(serde_json::to_value(&idle).unwrap(), wire);
5365 assert_eq!(
5366 serde_json::from_value::<super::StateUpdate>(wire).unwrap(),
5367 idle
5368 );
5369
5370 assert_eq!(idle.background().map(<[_]>::len), Some(2));
5371
5372 let empty = super::RunningStateUpdate::new().background(vec![]);
5373 assert_eq!(
5374 serde_json::to_value(&empty).unwrap(),
5375 json!({ "background": [] })
5376 );
5377 assert_eq!(
5378 super::StateUpdate::Running(empty).background(),
5379 Some(&[][..])
5380 );
5381 assert_eq!(
5382 super::StateUpdate::RequiresAction(super::RequiresActionStateUpdate::new())
5383 .background(),
5384 None
5385 );
5386 let custom: super::StateUpdate = serde_json::from_value(json!({
5387 "state": "_waiting",
5388 "background": [{ "type": "terminal", "terminalId": "term_003" }]
5389 }))
5390 .unwrap();
5391 assert_eq!(custom.background(), None);
5392 }
5393
5394 #[test]
5395 fn background_list_keeps_unknown_items_and_drops_malformed_lists() {
5396 use serde_json::json;
5397 let parsed: super::RunningStateUpdate = serde_json::from_value(json!({
5398 "background": [{ "type": "_cron", "schedule": "* * * * *" }]
5399 }))
5400 .unwrap();
5401 let Some([super::BackgroundWork::Other(other)]) = parsed.background.as_deref() else {
5402 panic!("expected one unknown item: {parsed:?}");
5403 };
5404 assert_eq!(other.kind, "_cron");
5405 assert_eq!(other.fields["schedule"], json!("* * * * *"));
5406
5407 for background in [
5408 json!(null),
5409 json!("oops"),
5410 json!([{ "type": "terminal" }]),
5411 json!([{ "type": "tool_call", "toolCallId": "call_1" }, { "type": "terminal", "terminalId": 7 }]),
5412 ] {
5413 let parsed: super::IdleStateUpdate =
5414 serde_json::from_value(json!({ "background": background })).unwrap();
5415 assert_eq!(parsed.background, None, "{background}");
5416 }
5417 }
5418
5419 #[test]
5420 fn replacement_lists_reject_non_arrays_instead_of_clearing() {
5421 use serde_json::json;
5422 for (update, key) in [
5423 ("config_option_update", "configOptions"),
5424 ("available_commands_update", "availableCommands"),
5425 ] {
5426 let empty = json!({ "sessionUpdate": update, key: [] });
5427 serde_json::from_value::<super::SessionUpdate>(empty).unwrap();
5428 for bad in [json!("oops"), json!(null), json!({})] {
5429 let wire = json!({ "sessionUpdate": update, key: bad });
5430 assert!(
5431 serde_json::from_value::<super::SessionUpdate>(wire).is_err(),
5432 "{update} {bad}"
5433 );
5434 }
5435 }
5436 let plan = |entries: serde_json::Value| {
5437 json!({ "sessionUpdate": "plan_update",
5438 "plan": { "type": "items", "planId": "p", "entries": entries } })
5439 };
5440 serde_json::from_value::<super::SessionUpdate>(plan(json!([]))).unwrap();
5441 assert!(serde_json::from_value::<super::SessionUpdate>(plan(json!("oops"))).is_err());
5442 let skipped =
5444 plan(json!([42, { "content": "a", "priority": "high", "status": "pending" }]));
5445 let super::SessionUpdate::PlanUpdate(update) =
5446 serde_json::from_value::<super::SessionUpdate>(skipped).unwrap()
5447 else {
5448 panic!("expected plan_update");
5449 };
5450 let crate::v2::PlanUpdateContent::Items(items) = update.plan else {
5451 panic!("expected items");
5452 };
5453 assert_eq!(items.entries.len(), 1);
5454 }
5455
5456 #[test]
5457 fn other_available_command_preserves_meta_verbatim() {
5458 for meta in [serde_json::json!({ "k": 1 }), serde_json::json!("bad")] {
5459 let wire = serde_json::json!({ "type": "_custom", "name": "c",
5460 "description": "d", "_meta": meta, "extra": true });
5461 let command: super::AvailableCommand = serde_json::from_value(wire.clone()).unwrap();
5462 assert_eq!(command.meta(), meta.as_object());
5463 assert_eq!(serde_json::to_value(&command).unwrap(), wire);
5464 }
5465 }
5466
5467 #[test]
5468 fn cancelled_permission_outcome_wire_format() {
5469 let outcome: RequestPermissionOutcome =
5470 serde_json::from_value(serde_json::json!({ "outcome": "cancelled" })).unwrap();
5471 assert_eq!(outcome, CancelledPermissionOutcome::new().into());
5472 assert_eq!(
5473 serde_json::to_value(&outcome).unwrap(),
5474 serde_json::json!({ "outcome": "cancelled" })
5475 );
5476
5477 let with_meta: RequestPermissionOutcome = CancelledPermissionOutcome::new()
5478 .meta(serde_json::Map::from_iter([(
5479 "k".to_string(),
5480 serde_json::json!(1),
5481 )]))
5482 .into();
5483 let json = serde_json::to_value(&with_meta).unwrap();
5484 assert_eq!(
5485 json,
5486 serde_json::json!({ "outcome": "cancelled", "_meta": { "k": 1 } })
5487 );
5488 assert_eq!(
5489 serde_json::from_value::<RequestPermissionOutcome>(json).unwrap(),
5490 with_meta
5491 );
5492 }
5493
5494 use super::*;
5495
5496 #[test]
5497 fn subagent_update_serializes_as_upsert() {
5498 use serde_json::json;
5499
5500 let announced =
5501 SessionUpdate::SubagentUpdate(SubagentUpdate::new("sess_child_1").capabilities(
5502 SubagentSessionCapabilities::new().cancel(SessionCancelCapabilities::new()),
5503 ));
5504 let wire = json!({
5505 "sessionUpdate": "subagent_update",
5506 "sessionId": "sess_child_1",
5507 "capabilities": { "cancel": {} }
5508 });
5509 assert_eq!(serde_json::to_value(&announced).unwrap(), wire);
5510 assert_eq!(
5511 serde_json::from_value::<SessionUpdate>(wire).unwrap(),
5512 announced
5513 );
5514
5515 let minimal = SubagentUpdate::new("sess_child_1");
5516 assert_eq!(
5517 serde_json::to_value(&minimal).unwrap(),
5518 json!({
5519 "sessionId": "sess_child_1"
5520 })
5521 );
5522 assert!(minimal.capabilities.is_undefined());
5523 assert!(minimal.state.is_undefined());
5524 assert!(minimal.meta.is_undefined());
5525
5526 let cleared_wire = json!({
5528 "sessionId": "sess_child_1",
5529 "capabilities": null,
5530 "state": null,
5531 "_meta": null
5532 });
5533 let cleared: SubagentUpdate = serde_json::from_value(cleared_wire.clone()).unwrap();
5534 assert!(cleared.capabilities.is_null());
5535 assert!(cleared.state.is_null());
5536 assert!(cleared.meta.is_null());
5537 assert_eq!(serde_json::to_value(cleared).unwrap(), cleared_wire);
5538
5539 let revoked: SubagentUpdate = serde_json::from_value(json!({
5540 "sessionId": "sess_child_1",
5541 "capabilities": {}
5542 }))
5543 .unwrap();
5544 assert_eq!(
5545 revoked.capabilities,
5546 MaybeUndefined::Value(SubagentSessionCapabilities::new())
5547 );
5548 assert!(
5549 matches!(revoked.capabilities, MaybeUndefined::Value(ref child) if child.cancel.is_none())
5550 );
5551
5552 assert!(
5553 serde_json::from_value::<SessionUpdate>(json!({
5554 "sessionUpdate": "subagent_update"
5555 }))
5556 .is_err()
5557 );
5558 }
5559
5560 #[test]
5561 fn subagent_cancel_capability_is_optional_object() {
5562 use serde_json::json;
5563
5564 for wire in [
5565 json!({}),
5566 json!({"cancel": null}),
5567 json!({"cancel": true}),
5568 json!({"cancel": false}),
5569 ] {
5570 let child: SubagentSessionCapabilities = serde_json::from_value(wire).unwrap();
5571 assert!(child.cancel.is_none());
5572 assert_eq!(serde_json::to_value(child).unwrap(), json!({}));
5573 }
5574 let enabled = SubagentSessionCapabilities::new().cancel(SessionCancelCapabilities::new());
5575 assert_eq!(
5576 serde_json::to_value(&enabled).unwrap(),
5577 json!({"cancel": {}})
5578 );
5579 assert_eq!(
5580 serde_json::from_value::<SubagentSessionCapabilities>(json!({"cancel": {}})).unwrap(),
5581 enabled
5582 );
5583 let meta: Meta = [("source".into(), json!("worker"))].into_iter().collect();
5584 let with_meta =
5585 SubagentSessionCapabilities::new().cancel(SessionCancelCapabilities::new().meta(meta));
5586 let wire = json!({"cancel": {"_meta": {"source": "worker"}}});
5587 assert_eq!(serde_json::to_value(&with_meta).unwrap(), wire);
5588 assert_eq!(
5589 serde_json::from_value::<SubagentSessionCapabilities>(wire).unwrap(),
5590 with_meta
5591 );
5592 assert!(enabled.cancel.is_some());
5593 assert!(enabled.cancel(None).cancel.is_none());
5594 let removed = SubagentUpdate::new("child").capabilities(SubagentSessionCapabilities::new());
5595 assert_eq!(
5596 serde_json::to_value(removed).unwrap(),
5597 json!({"sessionId": "child", "capabilities": {}})
5598 );
5599 }
5600
5601 #[test]
5602 fn subagent_display_metadata_uses_patch_semantics() {
5603 use serde_json::json;
5604
5605 let update = SubagentUpdate::new("child")
5606 .title("Test investigator".to_string())
5607 .description("Investigates platform-specific test failures.".to_string());
5608 let wire = json!({
5609 "sessionId": "child",
5610 "title": "Test investigator",
5611 "description": "Investigates platform-specific test failures."
5612 });
5613 assert_eq!(serde_json::to_value(&update).unwrap(), wire);
5614 assert_eq!(
5615 serde_json::from_value::<SubagentUpdate>(wire).unwrap(),
5616 update
5617 );
5618
5619 let minimal = SubagentUpdate::new("child");
5620 assert!(minimal.title.is_undefined());
5621 assert!(minimal.description.is_undefined());
5622 assert_eq!(
5623 serde_json::to_value(&minimal).unwrap(),
5624 json!({"sessionId": "child"})
5625 );
5626 let cleared_wire = json!({
5627 "sessionId": "child", "title": null, "description": null
5628 });
5629 let cleared: SubagentUpdate = serde_json::from_value(cleared_wire.clone()).unwrap();
5630 assert!(cleared.title.is_null());
5631 assert!(cleared.description.is_null());
5632 assert_eq!(serde_json::to_value(cleared).unwrap(), cleared_wire);
5633
5634 let title_only: SubagentUpdate = serde_json::from_value(json!({
5635 "sessionId": "child", "title": "Updated title"
5636 }))
5637 .unwrap();
5638 assert_eq!(
5639 title_only.title,
5640 MaybeUndefined::Value("Updated title".to_string())
5641 );
5642 assert!(title_only.description.is_undefined());
5643 let malformed: SubagentUpdate = serde_json::from_value(json!({
5644 "sessionId": "child", "title": false, "description": false
5645 }))
5646 .unwrap();
5647 assert_eq!(malformed, minimal);
5648 }
5649
5650 #[test]
5651 fn subagent_directories_use_strict_patch_semantics() {
5652 use serde_json::json;
5653
5654 let update = SubagentUpdate::new("child")
5655 .cwd("/home/user/project/.worktrees/investigator")
5656 .additional_directories(vec![]);
5657 let wire = json!({
5658 "sessionId": "child",
5659 "cwd": "/home/user/project/.worktrees/investigator",
5660 "additionalDirectories": []
5661 });
5662 assert_eq!(serde_json::to_value(&update).unwrap(), wire);
5663 assert_eq!(
5664 serde_json::from_value::<SubagentUpdate>(wire).unwrap(),
5665 update
5666 );
5667
5668 let inherited: SubagentUpdate =
5669 serde_json::from_value(json!({"sessionId": "child"})).unwrap();
5670 assert!(inherited.cwd.is_undefined());
5671 assert!(inherited.additional_directories.is_undefined());
5672
5673 let cleared_wire = json!({
5674 "sessionId": "child", "cwd": null, "additionalDirectories": null
5675 });
5676 let cleared: SubagentUpdate = serde_json::from_value(cleared_wire.clone()).unwrap();
5677 assert!(cleared.cwd.is_null());
5678 assert!(cleared.additional_directories.is_null());
5679 assert_eq!(serde_json::to_value(cleared).unwrap(), cleared_wire);
5680
5681 for malformed in [
5682 json!({"sessionId": "child", "cwd": false}),
5683 json!({"sessionId": "child", "additionalDirectories": "/tmp/wt"}),
5684 json!({"sessionId": "child", "additionalDirectories": ["/tmp/wt", false]}),
5685 ] {
5686 assert!(
5687 serde_json::from_value::<SubagentUpdate>(malformed.clone()).is_err(),
5688 "{malformed}"
5689 );
5690 }
5691 }
5692
5693 #[test]
5694 fn subagent_notification_keeps_parent_and_child_ids_nested() {
5695 use serde_json::json;
5696
5697 let notification = UpdateSessionNotification::new(
5698 "parent",
5699 SessionUpdate::SubagentUpdate(SubagentUpdate::new("child")),
5700 );
5701 let wire = json!({
5702 "sessionId": "parent",
5703 "update": {
5704 "sessionUpdate": "subagent_update",
5705 "sessionId": "child"
5706 }
5707 });
5708 assert_eq!(serde_json::to_value(¬ification).unwrap(), wire);
5709 assert_eq!(
5710 serde_json::from_value::<UpdateSessionNotification>(wire).unwrap(),
5711 notification
5712 );
5713 for malformed in [
5714 json!({"sessionId": "parent", "update": {"sessionUpdate": "subagent_update"}}),
5715 json!({"update": {"sessionUpdate": "subagent_update", "sessionId": "child"}}),
5716 ] {
5717 assert!(serde_json::from_value::<UpdateSessionNotification>(malformed).is_err());
5718 }
5719 }
5720
5721 #[test]
5722 fn subagent_mirrors_normal_child_state_notifications() {
5723 use serde_json::json;
5724
5725 let association = SubagentUpdate::new("sess_child");
5726 for state in [
5727 StateUpdate::Running(RunningStateUpdate::new()),
5728 StateUpdate::RequiresAction(RequiresActionStateUpdate::new()),
5729 StateUpdate::Unknown(UnknownStateUpdate::new()),
5730 StateUpdate::Running(RunningStateUpdate::new()),
5731 StateUpdate::Idle(IdleStateUpdate::new().stop_reason(StopReason::EndTurn)),
5732 StateUpdate::Running(RunningStateUpdate::new()),
5733 StateUpdate::Idle(IdleStateUpdate::new().stop_reason(StopReason::Cancelled)),
5734 ] {
5735 let child_notification = UpdateSessionNotification::new(
5736 association.session_id.clone(),
5737 SessionUpdate::StateUpdate(state.clone()),
5738 );
5739 let parent_notification = UpdateSessionNotification::new(
5740 "sess_parent",
5741 SessionUpdate::SubagentUpdate(association.clone().state(state)),
5742 );
5743 let child_wire = serde_json::to_value(&child_notification).unwrap();
5744 let parent_wire = serde_json::to_value(&parent_notification).unwrap();
5745 assert_eq!(child_wire["sessionId"], json!("sess_child"));
5746 assert_eq!(child_wire["update"]["sessionUpdate"], json!("state_update"));
5747 assert_eq!(parent_wire["sessionId"], json!("sess_parent"));
5748 assert_eq!(parent_wire["update"]["sessionId"], json!("sess_child"));
5749 let mut child_snapshot = child_wire["update"].clone();
5750 child_snapshot
5751 .as_object_mut()
5752 .unwrap()
5753 .remove("sessionUpdate");
5754 assert_eq!(parent_wire["update"]["state"], child_snapshot);
5755 assert_eq!(
5756 serde_json::from_value::<UpdateSessionNotification>(child_wire).unwrap(),
5757 child_notification
5758 );
5759 assert_eq!(
5760 serde_json::from_value::<UpdateSessionNotification>(parent_wire).unwrap(),
5761 parent_notification
5762 );
5763 }
5764 }
5765
5766 #[test]
5767 fn subagent_state_uses_whole_snapshot_patch_semantics() {
5768 use serde_json::json;
5769
5770 let minimal = SubagentUpdate::new("child");
5771 assert!(minimal.state.is_undefined());
5772 assert_eq!(
5773 serde_json::to_value(&minimal).unwrap(),
5774 json!({"sessionId": "child"})
5775 );
5776
5777 let cleared = minimal.clone().state(None::<StateUpdate>);
5778 assert!(cleared.state.is_null());
5779 assert_eq!(
5780 serde_json::to_value(&cleared).unwrap(),
5781 json!({"sessionId": "child", "state": null})
5782 );
5783 assert_eq!(
5784 serde_json::from_value::<SubagentUpdate>(json!({"sessionId": "child", "state": null}))
5785 .unwrap(),
5786 cleared
5787 );
5788
5789 for snapshot in [
5790 json!({"state": "running", "_meta": {"source": "worker"}}),
5791 json!({"state": "idle", "stopReason": "end_turn"}),
5792 json!({"state": "requires_action"}),
5793 json!({"state": "unknown"}),
5794 json!({"state": "_custom", "detail": {"phase": 2}}),
5795 ] {
5796 let state: StateUpdate = serde_json::from_value(snapshot.clone()).unwrap();
5797 let update = minimal.clone().state(state.clone());
5798 let wire = json!({"sessionId": "child", "state": snapshot});
5799 assert_eq!(serde_json::to_value(&update).unwrap(), wire);
5800 assert_eq!(
5801 serde_json::from_value::<SubagentUpdate>(wire).unwrap(),
5802 update
5803 );
5804 assert_eq!(update.state, MaybeUndefined::Value(state));
5805 }
5806
5807 let idle = SubagentUpdate::new("child").state(StateUpdate::Idle(
5810 IdleStateUpdate::new().stop_reason(StopReason::Cancelled),
5811 ));
5812 let running = idle.state(StateUpdate::Running(RunningStateUpdate::new()));
5813 assert_eq!(
5814 serde_json::to_value(running).unwrap(),
5815 json!({"sessionId": "child", "state": {"state": "running"}})
5816 );
5817 for invalid in [json!(false), json!(42), json!({}), json!({"state": 7})] {
5818 let parsed: SubagentUpdate =
5819 serde_json::from_value(json!({"sessionId": "child", "state": invalid})).unwrap();
5820 assert_eq!(parsed, minimal);
5821 }
5822 }
5823
5824 #[test]
5825 fn unknown_activity_is_a_known_state_update() {
5826 use serde_json::json;
5827
5828 let update = SessionUpdate::StateUpdate(StateUpdate::Unknown(
5829 UnknownStateUpdate::new().meta(
5830 [("source".into(), json!("worker"))]
5831 .into_iter()
5832 .collect::<Meta>(),
5833 ),
5834 ));
5835 let wire = json!({
5836 "sessionUpdate": "state_update",
5837 "state": "unknown",
5838 "_meta": { "source": "worker" }
5839 });
5840 assert_eq!(serde_json::to_value(&update).unwrap(), wire);
5841 assert_eq!(
5842 serde_json::from_value::<SessionUpdate>(wire).unwrap(),
5843 update
5844 );
5845
5846 for meta in [json!(null), json!(false)] {
5847 let state: StateUpdate = serde_json::from_value(json!({
5848 "state": "unknown",
5849 "_meta": meta
5850 }))
5851 .unwrap();
5852 assert_eq!(state, StateUpdate::Unknown(UnknownStateUpdate::new()));
5853 assert_eq!(
5854 serde_json::to_value(state).unwrap(),
5855 json!({"state": "unknown"})
5856 );
5857 }
5858 assert!(serde_json::from_value::<OtherStateUpdate>(json!({"state": "unknown"})).is_err());
5859 }
5860
5861 #[cfg(feature = "schemars")]
5862 #[test]
5863 fn subagent_schema_carries_optional_nullable_state_snapshot() {
5864 use serde_json::json;
5865
5866 let schema = serde_json::to_value(schemars::schema_for!(SubagentUpdate)).unwrap();
5867 let properties = schema["properties"].as_object().unwrap();
5868 assert!(properties.contains_key("sessionId"));
5869 assert!(properties.contains_key("title"));
5870 assert!(properties.contains_key("description"));
5871 assert!(properties.contains_key("capabilities"));
5872 assert!(properties.contains_key("state"));
5873 assert!(properties.contains_key("_meta"));
5874 assert!(!properties.contains_key("name"));
5875 assert!(!properties.contains_key("task"));
5876 assert_eq!(schema["required"], json!(["sessionId"]));
5877 assert_eq!(
5878 properties["state"]["x-deserialize-default-on-error"],
5879 json!(true)
5880 );
5881 let state_variants = properties["state"]["anyOf"].as_array().unwrap();
5882 assert!(state_variants.contains(&json!({"type": "null"})));
5883 assert!(
5884 state_variants
5885 .iter()
5886 .any(|variant| variant["$ref"] == "#/$defs/StateUpdate")
5887 );
5888 let child =
5889 serde_json::to_value(schemars::schema_for!(SubagentSessionCapabilities)).unwrap();
5890 let variants = child["properties"]["cancel"]["anyOf"]
5891 .as_array()
5892 .expect("cancel must allow the capability object or null");
5893 assert!(variants.contains(&json!({"type": "null"})));
5894 assert!(
5895 variants
5896 .iter()
5897 .any(|variant| variant["type"] == "object" || variant.get("$ref").is_some())
5898 );
5899 assert!(!variants.iter().any(|variant| variant["type"] == "boolean"));
5900 let cancel =
5901 serde_json::to_value(schemars::schema_for!(SessionCancelCapabilities)).unwrap();
5902 assert_eq!(cancel["type"], "object");
5903 assert!(
5904 !child["required"]
5905 .as_array()
5906 .is_some_and(|required| required.contains(&json!("cancel")))
5907 );
5908 }
5909
5910 #[test]
5911 fn notice_preserves_wire_shape_nullable_fields_and_open_severity() {
5912 use serde_json::json;
5913
5914 let mut meta = Meta::new();
5915 meta.insert("source".into(), json!("fallback"));
5916 let v2_notice = SessionUpdate::Notice(
5917 Notice::new(NoticeSeverity::Error, "Provider degraded")
5918 .description("Requests may take longer than usual.")
5919 .meta(meta.clone()),
5920 );
5921 let expected = json!({
5922 "sessionUpdate": "notice",
5923 "severity": "error",
5924 "title": "Provider degraded",
5925 "description": "Requests may take longer than usual.",
5926 "_meta": { "source": "fallback" }
5927 });
5928 assert_eq!(serde_json::to_value(&v2_notice).unwrap(), expected);
5929
5930 let v1_notice = crate::v1::SessionUpdate::Notice(
5931 crate::v1::Notice::new(crate::v1::NoticeSeverity::Error, "Provider degraded")
5932 .description("Requests may take longer than usual.")
5933 .meta(meta),
5934 );
5935 assert_eq!(
5936 serde_json::to_value(v2_notice).unwrap(),
5937 serde_json::to_value(v1_notice).unwrap()
5938 );
5939
5940 let SessionUpdate::Notice(notice) = serde_json::from_value(json!({
5941 "sessionUpdate": "notice",
5942 "severity": "critical",
5943 "title": "Provider degraded",
5944 "description": null,
5945 "_meta": null
5946 }))
5947 .unwrap() else {
5948 panic!("expected notice");
5949 };
5950
5951 assert_eq!(
5952 notice.severity,
5953 NoticeSeverity::Other("critical".to_string())
5954 );
5955 assert_eq!(notice.description, None);
5956 assert_eq!(notice.meta, None);
5957 assert_eq!(
5958 serde_json::to_value(SessionUpdate::Notice(notice)).unwrap(),
5959 json!({
5960 "sessionUpdate": "notice",
5961 "severity": "critical",
5962 "title": "Provider degraded"
5963 })
5964 );
5965 }
5966
5967 #[test]
5968 fn malformed_known_notice_is_not_hidden_as_unknown() {
5969 use serde_json::json;
5970
5971 for malformed in [
5972 json!({
5973 "sessionUpdate": "notice",
5974 "severity": "warning",
5975 "title": 42
5976 }),
5977 json!({
5978 "sessionUpdate": "notice",
5979 "severity": 42,
5980 "title": "MCP server unavailable"
5981 }),
5982 json!({
5983 "sessionUpdate": "notice",
5984 "severity": "warning"
5985 }),
5986 json!({
5987 "sessionUpdate": "notice",
5988 "severity": "warning",
5989 "title": null
5990 }),
5991 json!({
5992 "sessionUpdate": "notice",
5993 "title": "MCP server unavailable"
5994 }),
5995 json!({
5996 "sessionUpdate": "notice",
5997 "severity": null,
5998 "title": "MCP server unavailable"
5999 }),
6000 ] {
6001 assert!(serde_json::from_str::<SessionUpdate>(&malformed.to_string()).is_err());
6002 assert!(serde_json::from_value::<SessionUpdate>(malformed).is_err());
6003 }
6004 }
6005
6006 #[test]
6007 fn notice_tolerates_invalid_optional_display_fields_and_custom_severity() {
6008 use serde_json::json;
6009
6010 let wire = json!({
6011 "sessionUpdate": "notice",
6012 "severity": "_custom",
6013 "title": "Provider degraded",
6014 "description": 42,
6015 "_meta": false
6016 });
6017 let SessionUpdate::Notice(notice) = serde_json::from_value(wire.clone()).unwrap() else {
6018 panic!("expected notice");
6019 };
6020 assert_eq!(
6021 serde_json::from_str::<SessionUpdate>(&wire.to_string()).unwrap(),
6022 SessionUpdate::Notice(notice.clone())
6023 );
6024 assert_eq!(notice.severity, NoticeSeverity::Other("_custom".into()));
6025 assert_eq!(notice.description, None);
6026 assert_eq!(notice.meta, None);
6027 assert_eq!(
6028 serde_json::to_value(notice).unwrap(),
6029 json!({"severity": "_custom", "title": "Provider degraded"})
6030 );
6031 }
6032
6033 #[cfg(feature = "schemars")]
6034 #[test]
6035 fn notice_schema_preserves_required_fields_and_excludes_unknown_fallback() {
6036 use serde_json::json;
6037
6038 let schema = serde_json::to_value(schemars::schema_for!(Notice)).unwrap();
6039 assert_eq!(schema["required"], json!(["severity", "title"]));
6040 assert_eq!(schema["properties"]["title"]["minLength"], 1);
6041 for field in ["description", "_meta"] {
6042 assert!(
6043 schema["properties"][field]["type"]
6044 .as_array()
6045 .unwrap()
6046 .contains(&json!("null"))
6047 );
6048 }
6049 let fallback = serde_json::to_value(schemars::schema_for!(OtherSessionUpdate)).unwrap();
6050 assert!(
6051 fallback["not"]["anyOf"]
6052 .as_array()
6053 .unwrap()
6054 .iter()
6055 .any(|variant| variant["properties"]["sessionUpdate"]["const"] == "notice")
6056 );
6057 }
6058
6059 #[test]
6060 fn replay_complete_round_trips_with_and_without_meta() {
6061 use serde_json::json;
6062
6063 let bare = json!({ "sessionUpdate": "replay_complete" });
6064 assert_eq!(
6065 serde_json::to_value(SessionUpdate::ReplayComplete(ReplayComplete::new())).unwrap(),
6066 bare
6067 );
6068 assert_eq!(
6069 serde_json::from_value::<SessionUpdate>(bare).unwrap(),
6070 SessionUpdate::ReplayComplete(ReplayComplete::new())
6071 );
6072
6073 let mut meta = Meta::new();
6074 meta.insert("source".into(), json!("transcript"));
6075 let with_meta = json!({
6076 "sessionUpdate": "replay_complete",
6077 "_meta": { "source": "transcript" }
6078 });
6079 let update = SessionUpdate::ReplayComplete(ReplayComplete::new().meta(meta));
6080 assert_eq!(serde_json::to_value(&update).unwrap(), with_meta);
6081 assert_eq!(
6082 serde_json::from_value::<SessionUpdate>(with_meta).unwrap(),
6083 update
6084 );
6085 }
6086
6087 #[test]
6088 fn replay_complete_is_never_preserved_as_an_unknown_update() {
6089 use serde_json::json;
6090
6091 for wire in [
6095 json!({ "sessionUpdate": "replay_complete", "_meta": null }),
6096 json!({ "sessionUpdate": "replay_complete", "_meta": false }),
6097 json!({ "sessionUpdate": "replay_complete", "futureField": 1 }),
6098 ] {
6099 assert_eq!(
6100 serde_json::from_str::<SessionUpdate>(&wire.to_string()).unwrap(),
6101 SessionUpdate::ReplayComplete(ReplayComplete::new())
6102 );
6103 assert_eq!(
6104 serde_json::from_value::<SessionUpdate>(wire).unwrap(),
6105 SessionUpdate::ReplayComplete(ReplayComplete::new())
6106 );
6107 }
6108
6109 assert!(
6110 serde_json::from_value::<OtherSessionUpdate>(
6111 json!({ "sessionUpdate": "replay_complete" })
6112 )
6113 .is_err()
6114 );
6115 }
6116
6117 #[cfg(feature = "schemars")]
6118 #[test]
6119 fn replay_complete_schema_has_only_optional_meta_and_excludes_unknown_fallback() {
6120 use serde_json::json;
6121
6122 let schema = serde_json::to_value(schemars::schema_for!(ReplayComplete)).unwrap();
6123 assert!(schema.get("required").is_none());
6124 assert_eq!(
6125 schema["properties"]
6126 .as_object()
6127 .unwrap()
6128 .keys()
6129 .collect::<Vec<_>>(),
6130 ["_meta"]
6131 );
6132 assert_eq!(
6133 schema["properties"]["_meta"]["type"],
6134 json!(["object", "null"])
6135 );
6136 let fallback = serde_json::to_value(schemars::schema_for!(OtherSessionUpdate)).unwrap();
6137 assert!(
6138 fallback["not"]["anyOf"]
6139 .as_array()
6140 .unwrap()
6141 .iter()
6142 .any(|variant| variant["properties"]["sessionUpdate"]["const"]
6143 == "replay_complete")
6144 );
6145 }
6146
6147 #[cfg(feature = "unstable_prompt_suggestions")]
6148 #[test]
6149 fn prompt_suggestions_update_round_trips_prompt_content_and_meta() {
6150 use super::{ContentBlock, Meta, PromptSuggestion, PromptSuggestionsUpdate, SessionUpdate};
6151 use crate::v2::{ResourceLink, TextContent};
6152 use serde_json::json;
6153
6154 let mut meta = Meta::new();
6155 meta.insert("rank".into(), json!(1));
6156 let update = SessionUpdate::PromptSuggestionsUpdate(PromptSuggestionsUpdate::new(vec![
6157 PromptSuggestion::new(vec![ContentBlock::Text(TextContent::new(
6158 "Run the test suite and fix what breaks",
6159 ))])
6160 .meta(meta),
6161 PromptSuggestion::new(vec![
6162 ContentBlock::Text(TextContent::new("Add tests for ")),
6163 ContentBlock::ResourceLink(ResourceLink::new(
6164 "parser.rs",
6165 "file:///home/user/project/src/parser.rs",
6166 )),
6167 ]),
6168 ]));
6169 let wire = json!({
6170 "sessionUpdate": "prompt_suggestions_update",
6171 "suggestions": [
6172 {
6173 "prompt": [
6174 { "type": "text", "text": "Run the test suite and fix what breaks" }
6175 ],
6176 "_meta": { "rank": 1 }
6177 },
6178 {
6179 "prompt": [
6180 { "type": "text", "text": "Add tests for " },
6181 {
6182 "type": "resource_link",
6183 "name": "parser.rs",
6184 "uri": "file:///home/user/project/src/parser.rs"
6185 }
6186 ]
6187 }
6188 ]
6189 });
6190 assert_eq!(serde_json::to_value(&update).unwrap(), wire);
6191 assert_eq!(
6192 serde_json::from_value::<SessionUpdate>(wire).unwrap(),
6193 update
6194 );
6195 }
6196
6197 #[cfg(feature = "unstable_prompt_suggestions")]
6198 #[test]
6199 fn prompt_suggestions_update_with_an_empty_list_withdraws_suggestions() {
6200 use super::{PromptSuggestionsUpdate, SessionUpdate};
6201 use serde_json::json;
6202
6203 let update = SessionUpdate::PromptSuggestionsUpdate(PromptSuggestionsUpdate::new(vec![]));
6204 let wire = json!({
6205 "sessionUpdate": "prompt_suggestions_update",
6206 "suggestions": []
6207 });
6208 assert_eq!(serde_json::to_value(&update).unwrap(), wire);
6209 assert_eq!(
6210 serde_json::from_value::<SessionUpdate>(wire).unwrap(),
6211 update
6212 );
6213 }
6214
6215 #[cfg(feature = "unstable_prompt_suggestions")]
6216 #[test]
6217 fn prompt_suggestions_update_is_never_preserved_as_an_unknown_update() {
6218 use super::{OtherSessionUpdate, SessionUpdate};
6219 use serde_json::json;
6220
6221 for wire in [
6224 json!({ "sessionUpdate": "prompt_suggestions_update" }),
6225 json!({ "sessionUpdate": "prompt_suggestions_update", "suggestions": null }),
6226 json!({ "sessionUpdate": "prompt_suggestions_update", "suggestions": "none" }),
6227 json!({ "sessionUpdate": "prompt_suggestions_update", "suggestions": { "prompt": [] } }),
6228 ] {
6229 assert!(serde_json::from_str::<SessionUpdate>(&wire.to_string()).is_err());
6230 assert!(serde_json::from_value::<SessionUpdate>(wire).is_err());
6231 }
6232
6233 assert!(
6234 serde_json::from_value::<OtherSessionUpdate>(json!({
6235 "sessionUpdate": "prompt_suggestions_update",
6236 "suggestions": []
6237 }))
6238 .is_err()
6239 );
6240 }
6241
6242 #[cfg(feature = "unstable_prompt_suggestions")]
6243 #[test]
6244 fn prompt_suggestions_update_skips_whole_suggestions_it_cannot_parse() {
6245 use super::{ContentBlock, PromptSuggestion, PromptSuggestionsUpdate, SessionUpdate};
6246 use crate::v2::TextContent;
6247 use serde_json::json;
6248
6249 let text =
6250 |text: &str| PromptSuggestion::new(vec![ContentBlock::Text(TextContent::new(text))]);
6251
6252 let update: SessionUpdate = serde_json::from_value(json!({
6255 "sessionUpdate": "prompt_suggestions_update",
6256 "suggestions": [
6257 { "prompt": [{ "type": "text", "text": "Keep the first" }] },
6258 { "text": "A suggestion without a prompt" },
6259 { "prompt": "Not a list" },
6260 { "prompt": [{ "type": "text", "text": "Open " }, { "type": "text" }] },
6261 "not an object",
6262 { "prompt": [{ "type": "text", "text": "Keep the last" }], "_meta": false }
6263 ]
6264 }))
6265 .unwrap();
6266
6267 assert_eq!(
6268 update,
6269 SessionUpdate::PromptSuggestionsUpdate(PromptSuggestionsUpdate::new(vec![
6270 text("Keep the first"),
6271 text("Keep the last"),
6272 ]))
6273 );
6274 }
6275
6276 #[cfg(feature = "unstable_prompt_suggestions")]
6277 #[test]
6278 fn prompt_suggestions_update_preserves_custom_and_future_content_blocks() {
6279 use super::{ContentBlock, SessionUpdate};
6280 use serde_json::json;
6281
6282 let wire = json!({
6285 "sessionUpdate": "prompt_suggestions_update",
6286 "suggestions": [
6287 { "prompt": [{ "type": "_hologram", "data": "AAAA" }] }
6288 ]
6289 });
6290 let update: SessionUpdate = serde_json::from_value(wire.clone()).unwrap();
6291 let SessionUpdate::PromptSuggestionsUpdate(suggestions) = &update else {
6292 panic!("expected prompt_suggestions_update, got {update:?}");
6293 };
6294 assert!(matches!(
6295 suggestions.suggestions[0].prompt.as_slice(),
6296 [ContentBlock::Other(_)]
6297 ));
6298 assert_eq!(serde_json::to_value(&update).unwrap(), wire);
6299 }
6300
6301 #[cfg(feature = "unstable_prompt_suggestions")]
6302 #[test]
6303 fn prompt_suggestions_capability_advertises_support_and_content_types() {
6304 use super::{
6305 ClientCapabilities, ClientSessionCapabilities, PromptSuggestionsAudioCapabilities,
6306 PromptSuggestionsCapabilities, PromptSuggestionsEmbeddedContextCapabilities,
6307 PromptSuggestionsImageCapabilities,
6308 };
6309 use serde_json::json;
6310
6311 let capabilities = ClientCapabilities::new().session(
6312 ClientSessionCapabilities::new()
6313 .prompt_suggestions(PromptSuggestionsCapabilities::new()),
6314 );
6315 let value = serde_json::to_value(&capabilities).unwrap();
6316 assert_eq!(value, json!({ "session": { "promptSuggestions": {} } }));
6317 assert_eq!(
6318 serde_json::from_value::<ClientCapabilities>(value).unwrap(),
6319 capabilities
6320 );
6321
6322 let content_types = PromptSuggestionsCapabilities::new()
6323 .image(PromptSuggestionsImageCapabilities::new())
6324 .audio(PromptSuggestionsAudioCapabilities::new())
6325 .embedded_context(PromptSuggestionsEmbeddedContextCapabilities::new());
6326 let wire = json!({ "image": {}, "audio": {}, "embeddedContext": {} });
6327 assert_eq!(serde_json::to_value(&content_types).unwrap(), wire);
6328 assert_eq!(
6329 serde_json::from_value::<PromptSuggestionsCapabilities>(wire).unwrap(),
6330 content_types
6331 );
6332
6333 for unsupported in [
6335 json!({}),
6336 json!({ "session": null }),
6337 json!({ "session": {} }),
6338 json!({ "session": { "promptSuggestions": null } }),
6339 json!({ "session": { "promptSuggestions": false } }),
6340 json!({ "session": { "promptSuggestions": true } }),
6341 json!({ "session": { "promptSuggestions": "supported" } }),
6342 ] {
6343 let capabilities: ClientCapabilities = serde_json::from_value(unsupported).unwrap();
6344 assert!(
6345 capabilities
6346 .session
6347 .and_then(|session| session.prompt_suggestions)
6348 .is_none()
6349 );
6350 }
6351
6352 assert_eq!(
6355 serde_json::from_value::<PromptSuggestionsCapabilities>(json!({
6356 "image": true,
6357 "audio": null,
6358 "embeddedContext": {}
6359 }))
6360 .unwrap(),
6361 PromptSuggestionsCapabilities::new()
6362 .embedded_context(PromptSuggestionsEmbeddedContextCapabilities::new())
6363 );
6364 }
6365
6366 #[cfg(all(feature = "schemars", feature = "unstable_prompt_suggestions"))]
6367 #[test]
6368 fn prompt_suggestions_schema_requires_the_list_and_excludes_unknown_fallback() {
6369 use super::{
6370 ClientCapabilities, ClientSessionCapabilities, OtherSessionUpdate, PromptSuggestion,
6371 PromptSuggestionsCapabilities, PromptSuggestionsUpdate,
6372 };
6373 use serde_json::json;
6374
6375 let update = serde_json::to_value(schemars::schema_for!(PromptSuggestionsUpdate)).unwrap();
6376 assert_eq!(update["required"], json!(["suggestions"]));
6377 assert_eq!(update["properties"]["suggestions"]["type"], "array");
6378
6379 let suggestion = serde_json::to_value(schemars::schema_for!(PromptSuggestion)).unwrap();
6380 assert_eq!(suggestion["required"], json!(["prompt"]));
6381 assert_eq!(suggestion["properties"]["prompt"]["type"], "array");
6382 assert_eq!(suggestion["properties"]["prompt"]["minItems"], 1);
6383
6384 let fallback = serde_json::to_value(schemars::schema_for!(OtherSessionUpdate)).unwrap();
6385 assert!(
6386 fallback["not"]["anyOf"]
6387 .as_array()
6388 .unwrap()
6389 .iter()
6390 .any(|variant| variant["properties"]["sessionUpdate"]["const"]
6391 == "prompt_suggestions_update")
6392 );
6393
6394 for (schema, field) in [
6395 (
6396 serde_json::to_value(schemars::schema_for!(ClientCapabilities)).unwrap(),
6397 "session",
6398 ),
6399 (
6400 serde_json::to_value(schemars::schema_for!(ClientSessionCapabilities)).unwrap(),
6401 "promptSuggestions",
6402 ),
6403 ] {
6404 assert!(
6405 schema["properties"][field]["anyOf"]
6406 .as_array()
6407 .unwrap()
6408 .contains(&json!({"type": "null"}))
6409 );
6410 assert!(
6411 !schema["required"]
6412 .as_array()
6413 .is_some_and(|required| required.contains(&json!(field)))
6414 );
6415 }
6416
6417 let content_types =
6418 serde_json::to_value(schemars::schema_for!(PromptSuggestionsCapabilities)).unwrap();
6419 assert!(content_types.get("required").is_none());
6420 for field in ["image", "audio", "embeddedContext"] {
6421 assert!(
6422 content_types["properties"][field]["anyOf"]
6423 .as_array()
6424 .unwrap()
6425 .contains(&json!({"type": "null"}))
6426 );
6427 }
6428 }
6429
6430 #[test]
6431 fn compaction_updates_preserve_patch_and_open_status_semantics() {
6432 use serde_json::json;
6433
6434 assert_eq!(
6435 serde_json::to_value(SessionUpdate::CompactionUpdate(
6436 CompactionUpdate::new("cmp_001", CompactionStatus::Completed).summary(vec![
6437 ContentBlock::Text(crate::v2::TextContent::new("retained")),
6438 ]),
6439 ))
6440 .unwrap(),
6441 json!({
6442 "sessionUpdate": "compaction_update",
6443 "compactionId": "cmp_001",
6444 "status": "completed",
6445 "summary": [{ "type": "text", "text": "retained" }]
6446 })
6447 );
6448
6449 let SessionUpdate::CompactionUpdate(update) = serde_json::from_value(json!({
6450 "sessionUpdate": "compaction_update",
6451 "compactionId": "cmp_001",
6452 "status": "paused",
6453 "summary": null
6454 }))
6455 .unwrap() else {
6456 panic!("expected compaction update");
6457 };
6458 assert_eq!(update.status, CompactionStatus::Other("paused".into()));
6459 assert!(update.summary.is_null());
6460 assert!(update.error.is_undefined());
6461 }
6462
6463 #[test]
6464 fn malformed_known_compaction_update_is_not_hidden_as_unknown() {
6465 use serde_json::json;
6466
6467 assert!(
6468 serde_json::from_value::<SessionUpdate>(json!({
6469 "sessionUpdate": "compaction_update",
6470 "status": "completed"
6471 }))
6472 .is_err()
6473 );
6474 assert!(
6475 serde_json::from_value::<SessionUpdate>(json!({
6476 "sessionUpdate": "compaction_summary_chunk",
6477 "compactionId": "cmp_001"
6478 }))
6479 .is_err()
6480 );
6481 }
6482
6483 #[test]
6484 fn test_elicitation_capability_semantics() {
6485 use serde_json::json;
6486
6487 let unsupported: ClientCapabilities = serde_json::from_value(json!({})).unwrap();
6488 assert!(unsupported.elicitation.is_none());
6489
6490 let null: ClientCapabilities =
6491 serde_json::from_value(json!({ "elicitation": null })).unwrap();
6492 assert!(null.elicitation.is_none());
6493
6494 let malformed: ClientCapabilities =
6495 serde_json::from_value(json!({ "elicitation": false })).unwrap();
6496 assert!(malformed.elicitation.is_none());
6497
6498 let empty: ClientCapabilities =
6499 serde_json::from_value(json!({ "elicitation": {} })).unwrap();
6500 let empty = empty.elicitation.expect("present capability");
6501 assert!(!empty.supports_form());
6502 assert!(!empty.supports_url());
6503
6504 let form_only: ClientCapabilities = serde_json::from_value(json!({
6505 "elicitation": { "form": {} }
6506 }))
6507 .unwrap();
6508 let form_only = form_only.elicitation.expect("advertised capability");
6509 assert!(form_only.supports_form());
6510 assert!(!form_only.supports_url());
6511
6512 let url_only: ClientCapabilities = serde_json::from_value(json!({
6513 "elicitation": { "url": {} }
6514 }))
6515 .unwrap();
6516 let url_only = url_only.elicitation.expect("advertised capability");
6517 assert!(!url_only.supports_form());
6518 assert!(url_only.supports_url());
6519
6520 let both: ClientCapabilities = serde_json::from_value(json!({
6521 "elicitation": { "form": {}, "url": {} }
6522 }))
6523 .unwrap();
6524 let both = both.elicitation.expect("advertised capability");
6525 assert!(both.supports_form());
6526 assert!(both.supports_url());
6527 }
6528
6529 #[test]
6530 fn test_elicitation_method_routing_and_envelopes() {
6531 use serde_json::json;
6532
6533 assert_eq!(CLIENT_METHOD_NAMES.elicitation_create, "elicitation/create");
6534 assert_eq!(
6535 CLIENT_METHOD_NAMES.elicitation_complete,
6536 "elicitation/complete"
6537 );
6538
6539 let request =
6540 AgentRequest::CreateElicitationRequest(Box::new(CreateElicitationRequest::new(
6541 crate::v2::ElicitationFormMode::new(
6542 crate::v2::ElicitationSessionScope::new("sess_1"),
6543 crate::v2::ElicitationSchema::new(),
6544 ),
6545 "Choose a value",
6546 )));
6547 assert_eq!(request.method(), "elicitation/create");
6548 let method = Arc::from(request.method());
6549 let request = crate::v2::JsonRpcMessage::wrap(crate::v2::Request {
6550 id: crate::v2::RequestId::Number(7),
6551 method,
6552 params: Some(request),
6553 });
6554 assert_eq!(
6555 serde_json::to_value(request).unwrap(),
6556 json!({
6557 "jsonrpc": "2.0",
6558 "id": 7,
6559 "method": "elicitation/create",
6560 "params": {
6561 "mode": "form",
6562 "sessionId": "sess_1",
6563 "message": "Choose a value",
6564 "requestedSchema": { "type": "object", "properties": {} }
6565 }
6566 })
6567 );
6568
6569 let notification = AgentNotification::CompleteElicitationNotification(Box::new(
6570 CompleteElicitationNotification::new("elic_1"),
6571 ));
6572 assert_eq!(notification.method(), "elicitation/complete");
6573 let method = Arc::from(notification.method());
6574 let notification = crate::v2::JsonRpcMessage::wrap(crate::v2::Notification {
6575 method,
6576 params: Some(notification),
6577 });
6578 assert_eq!(
6579 serde_json::to_value(notification).unwrap(),
6580 json!({
6581 "jsonrpc": "2.0",
6582 "method": "elicitation/complete",
6583 "params": { "elicitationId": "elic_1" }
6584 })
6585 );
6586 }
6587
6588 #[test]
6589 fn test_client_capabilities_auth_defaults_on_malformed_value() {
6590 use serde_json::json;
6591
6592 let capabilities: ClientCapabilities = serde_json::from_value(json!({
6593 "auth": false
6594 }))
6595 .unwrap();
6596
6597 assert_eq!(capabilities.auth, None);
6598 }
6599
6600 #[test]
6601 fn test_serialization_behavior() {
6602 use serde_json::json;
6603
6604 assert_eq!(
6605 serde_json::from_value::<SessionInfoUpdate>(json!({})).unwrap(),
6606 SessionInfoUpdate {
6607 title: MaybeUndefined::Undefined,
6608 updated_at: MaybeUndefined::Undefined,
6609 meta: MaybeUndefined::Undefined
6610 }
6611 );
6612 assert_eq!(
6613 serde_json::from_value::<SessionInfoUpdate>(json!({"title": null, "updatedAt": null}))
6614 .unwrap(),
6615 SessionInfoUpdate {
6616 title: MaybeUndefined::Null,
6617 updated_at: MaybeUndefined::Null,
6618 meta: MaybeUndefined::Undefined
6619 }
6620 );
6621 assert_eq!(
6622 serde_json::from_value::<SessionInfoUpdate>(
6623 json!({"title": "title", "updatedAt": "timestamp"})
6624 )
6625 .unwrap(),
6626 SessionInfoUpdate {
6627 title: MaybeUndefined::Value("title".to_string()),
6628 updated_at: MaybeUndefined::Value("timestamp".to_string()),
6629 meta: MaybeUndefined::Undefined
6630 }
6631 );
6632
6633 let clear_meta =
6634 serde_json::from_value::<SessionInfoUpdate>(json!({"_meta": null})).unwrap();
6635 assert_eq!(clear_meta.meta, MaybeUndefined::Null);
6636
6637 let mut meta = Meta::new();
6638 meta.insert("source".to_string(), json!("session-info"));
6639
6640 assert_eq!(
6641 serde_json::from_value::<SessionInfoUpdate>(json!({"_meta": {
6642 "source": "session-info"
6643 }}))
6644 .unwrap()
6645 .meta,
6646 MaybeUndefined::Value(meta.clone())
6647 );
6648
6649 assert_eq!(
6650 serde_json::to_value(SessionInfoUpdate::new()).unwrap(),
6651 json!({})
6652 );
6653
6654 assert_eq!(
6655 serde_json::to_value(SessionInfoUpdate::new().meta(None::<Meta>)).unwrap(),
6656 json!({"_meta": null})
6657 );
6658
6659 assert_eq!(
6660 serde_json::to_value(SessionInfoUpdate::new().meta(meta)).unwrap(),
6661 json!({"_meta": {
6662 "source": "session-info"
6663 }})
6664 );
6665 assert_eq!(
6666 serde_json::to_value(SessionInfoUpdate::new().title("title")).unwrap(),
6667 json!({"title": "title"})
6668 );
6669 assert_eq!(
6670 serde_json::to_value(SessionInfoUpdate::new().title(None)).unwrap(),
6671 json!({"title": null})
6672 );
6673 assert_eq!(
6674 serde_json::to_value(
6675 SessionInfoUpdate::new()
6676 .title("title")
6677 .title(MaybeUndefined::Undefined)
6678 )
6679 .unwrap(),
6680 json!({})
6681 );
6682 }
6683
6684 #[test]
6685 fn test_content_chunk_message_id_serialization() {
6686 use serde_json::json;
6687
6688 assert_eq!(
6689 serde_json::to_value(SessionUpdate::AgentMessageChunk(ContentChunk::new(
6690 ContentBlock::Text(crate::v2::TextContent::new("Hello")),
6691 "msg_agent_c42b9",
6692 )))
6693 .unwrap(),
6694 json!({
6695 "sessionUpdate": "agent_message_chunk",
6696 "messageId": "msg_agent_c42b9",
6697 "content": {
6698 "type": "text",
6699 "text": "Hello"
6700 }
6701 })
6702 );
6703
6704 let err = serde_json::from_value::<ContentChunk>(json!({
6705 "content": {
6706 "type": "text",
6707 "text": "Hello"
6708 }
6709 }))
6710 .unwrap_err();
6711
6712 assert!(err.to_string().contains("messageId"), "{err}");
6713 }
6714
6715 #[test]
6716 fn test_tool_call_content_chunk_serialization() {
6717 use serde_json::json;
6718
6719 assert_eq!(
6720 serde_json::to_value(SessionUpdate::ToolCallContentChunk(
6721 ToolCallContentChunk::new(
6722 "call_001",
6723 crate::v2::ContentBlock::Text(crate::v2::TextContent::new("partial output")),
6724 )
6725 ))
6726 .unwrap(),
6727 json!({
6728 "sessionUpdate": "tool_call_content_chunk",
6729 "toolCallId": "call_001",
6730 "content": {
6731 "type": "content",
6732 "content": {
6733 "type": "text",
6734 "text": "partial output"
6735 }
6736 }
6737 })
6738 );
6739
6740 let err = serde_json::from_value::<ToolCallContentChunk>(json!({
6741 "content": {
6742 "type": "content",
6743 "content": {
6744 "type": "text",
6745 "text": "partial output"
6746 }
6747 }
6748 }))
6749 .unwrap_err();
6750
6751 assert!(err.to_string().contains("toolCallId"), "{err}");
6752 }
6753
6754 #[test]
6755 fn test_full_message_serialization() {
6756 use serde_json::json;
6757
6758 assert_eq!(
6759 serde_json::to_value(SessionUpdate::UserMessage(
6760 UserMessage::new("msg_user_8f7a1").content(vec![ContentBlock::Text(
6761 crate::v2::TextContent::new("Hello")
6762 )])
6763 ))
6764 .unwrap(),
6765 json!({
6766 "sessionUpdate": "user_message",
6767 "messageId": "msg_user_8f7a1",
6768 "content": [
6769 {
6770 "type": "text",
6771 "text": "Hello"
6772 }
6773 ]
6774 })
6775 );
6776
6777 assert_eq!(
6778 serde_json::to_value(SessionUpdate::AgentMessage(
6779 AgentMessage::new("msg_agent_c42b9").content(vec![ContentBlock::Text(
6780 crate::v2::TextContent::new("Hello")
6781 )])
6782 ))
6783 .unwrap(),
6784 json!({
6785 "sessionUpdate": "agent_message",
6786 "messageId": "msg_agent_c42b9",
6787 "content": [
6788 {
6789 "type": "text",
6790 "text": "Hello"
6791 }
6792 ]
6793 })
6794 );
6795
6796 assert_eq!(
6797 serde_json::to_value(SessionUpdate::AgentThought(
6798 AgentThought::new("msg_thought_a12").content(vec![ContentBlock::Text(
6799 crate::v2::TextContent::new("Need to inspect the call sites first.")
6800 )])
6801 ))
6802 .unwrap(),
6803 json!({
6804 "sessionUpdate": "agent_thought",
6805 "messageId": "msg_thought_a12",
6806 "content": [
6807 {
6808 "type": "text",
6809 "text": "Need to inspect the call sites first."
6810 }
6811 ]
6812 })
6813 );
6814 }
6815
6816 #[test]
6817 fn test_message_upsert_serialization() {
6818 use serde_json::json;
6819
6820 assert_eq!(
6821 serde_json::to_value(SessionUpdate::UserMessage(
6822 UserMessage::new("msg_empty").content(Vec::<ContentBlock>::new())
6823 ))
6824 .unwrap(),
6825 json!({
6826 "sessionUpdate": "user_message",
6827 "messageId": "msg_empty",
6828 "content": []
6829 })
6830 );
6831
6832 let empty = serde_json::from_value::<UserMessage>(json!({
6833 "messageId": "msg_empty",
6834 "content": []
6835 }))
6836 .unwrap();
6837 assert!(matches!(
6838 empty.content,
6839 MaybeUndefined::Value(ref content) if content.is_empty()
6840 ));
6841
6842 let patch = serde_json::from_value::<AgentMessage>(json!({
6843 "messageId": "msg_agent_c42b9"
6844 }))
6845 .unwrap();
6846 assert_eq!(patch.content, MaybeUndefined::Undefined);
6847 assert_eq!(patch.meta, MaybeUndefined::Undefined);
6848
6849 let malformed_meta = serde_json::from_value::<AgentMessage>(json!({
6850 "messageId": "msg_agent_c42b9",
6851 "_meta": false
6852 }))
6853 .unwrap();
6854 assert_eq!(malformed_meta.meta, MaybeUndefined::Undefined);
6855
6856 let patch = serde_json::from_value::<AgentThought>(json!({
6857 "messageId": "msg_thought_a12"
6858 }))
6859 .unwrap();
6860 assert_eq!(patch.content, MaybeUndefined::Undefined);
6861
6862 let clear = serde_json::from_value::<UserMessage>(json!({
6863 "messageId": "msg_user_8f7a1",
6864 "content": null
6865 }))
6866 .unwrap();
6867 assert_eq!(clear.content, MaybeUndefined::Null);
6868
6869 let clear_meta = serde_json::from_value::<UserMessage>(json!({
6870 "messageId": "msg_user_8f7a1",
6871 "_meta": null
6872 }))
6873 .unwrap();
6874 assert_eq!(clear_meta.meta, MaybeUndefined::Null);
6875
6876 let mut meta = Meta::new();
6877 meta.insert("source".to_string(), json!("replay"));
6878
6879 assert_eq!(
6880 serde_json::to_value(SessionUpdate::UserMessage(
6881 UserMessage::new("msg_user_8f7a1").meta(meta)
6882 ))
6883 .unwrap(),
6884 json!({
6885 "sessionUpdate": "user_message",
6886 "messageId": "msg_user_8f7a1",
6887 "_meta": {
6888 "source": "replay"
6889 }
6890 })
6891 );
6892
6893 assert_eq!(
6894 serde_json::to_value(SessionUpdate::UserMessage(
6895 UserMessage::new("msg_user_8f7a1").meta(None::<Meta>)
6896 ))
6897 .unwrap(),
6898 json!({
6899 "sessionUpdate": "user_message",
6900 "messageId": "msg_user_8f7a1",
6901 "_meta": null
6902 })
6903 );
6904 }
6905
6906 #[test]
6907 fn test_usage_update_serialization() {
6908 use serde_json::json;
6909
6910 assert_eq!(
6911 serde_json::to_value(SessionUpdate::UsageUpdate(UsageUpdate::new(
6912 53_000, 200_000
6913 )))
6914 .unwrap(),
6915 json!({
6916 "sessionUpdate": "usage_update",
6917 "used": 53000,
6918 "size": 200_000
6919 })
6920 );
6921
6922 assert_eq!(
6923 serde_json::to_value(SessionUpdate::UsageUpdate(
6924 UsageUpdate::new(53_000, 200_000).cost(Cost::new(0.045, "USD"))
6925 ))
6926 .unwrap(),
6927 json!({
6928 "sessionUpdate": "usage_update",
6929 "used": 53000,
6930 "size": 200_000,
6931 "cost": {
6932 "amount": 0.045,
6933 "currency": "USD"
6934 }
6935 })
6936 );
6937
6938 let SessionUpdate::UsageUpdate(update) = serde_json::from_value(json!({
6939 "sessionUpdate": "usage_update",
6940 "used": 53000,
6941 "size": 200_000,
6942 "cost": null
6943 }))
6944 .unwrap() else {
6945 panic!("expected usage update");
6946 };
6947
6948 assert_eq!(update.cost, MaybeUndefined::Null);
6949
6950 let SessionUpdate::UsageUpdate(update) = serde_json::from_value(json!({
6951 "sessionUpdate": "usage_update",
6952 "used": 53000,
6953 "size": 200_000
6954 }))
6955 .unwrap() else {
6956 panic!("expected usage update");
6957 };
6958
6959 assert_eq!(update.cost, MaybeUndefined::Undefined);
6960 }
6961
6962 #[test]
6963 fn error_stop_reason_carries_failure_beside_discriminator() {
6964 use crate::v2::{Error, ErrorStopReason};
6965 use serde_json::json;
6966
6967 let update =
6968 SessionUpdate::StateUpdate(StateUpdate::Idle(IdleStateUpdate::new().stop_reason(
6969 StopReason::from(ErrorStopReason::new().error(Error::auth_required())),
6970 )));
6971 let wire = json!({
6972 "sessionUpdate": "state_update",
6973 "state": "idle",
6974 "stopReason": "error",
6975 "error": { "code": -32000, "message": "Authentication required" }
6976 });
6977 assert_eq!(serde_json::to_value(&update).unwrap(), wire);
6978 assert_eq!(
6979 serde_json::from_value::<SessionUpdate>(wire).unwrap(),
6980 update
6981 );
6982
6983 let with_data =
6984 StateUpdate::Idle(IdleStateUpdate::new().stop_reason(StopReason::from(
6985 ErrorStopReason::new().error(
6986 Error::new(-32099, "Provider unavailable").data(json!({ "status": 503 })),
6987 ),
6988 )));
6989 let wire = json!({
6990 "state": "idle",
6991 "stopReason": "error",
6992 "error": {
6993 "code": -32099,
6994 "message": "Provider unavailable",
6995 "data": { "status": 503 }
6996 }
6997 });
6998 assert_eq!(serde_json::to_value(&with_data).unwrap(), wire);
6999 assert_eq!(
7000 serde_json::from_value::<StateUpdate>(wire).unwrap(),
7001 with_data
7002 );
7003
7004 let without_details = StateUpdate::Idle(
7007 IdleStateUpdate::new().stop_reason(StopReason::from(ErrorStopReason::new())),
7008 );
7009 for error in [
7010 None,
7011 Some(json!(null)),
7012 Some(json!("failed")),
7013 Some(json!({ "message": "missing code" })),
7014 ] {
7015 let mut wire = json!({ "state": "idle", "stopReason": "error" });
7016 if let Some(error) = error {
7017 wire["error"] = error;
7018 }
7019 assert_eq!(
7020 serde_json::from_value::<StateUpdate>(wire).unwrap(),
7021 without_details
7022 );
7023 }
7024 assert_eq!(
7025 serde_json::to_value(&without_details).unwrap(),
7026 json!({ "state": "idle", "stopReason": "error" })
7027 );
7028
7029 let parsed: StateUpdate = serde_json::from_value(json!({
7033 "state": "idle",
7034 "stopReason": "end_turn",
7035 "error": { "code": -32603, "message": "Internal error" }
7036 }))
7037 .unwrap();
7038 assert_eq!(
7039 parsed,
7040 StateUpdate::Idle(IdleStateUpdate::new().stop_reason(StopReason::EndTurn))
7041 );
7042 }
7043
7044 #[test]
7045 fn flattened_stop_reason_keeps_open_enum_tolerance() {
7046 use crate::v2::OtherStopReason;
7047 use serde_json::json;
7048
7049 let meta: Meta = [("source".into(), json!("test"))].into_iter().collect();
7050
7051 for stop_reason in [None, Some(json!(null)), Some(json!(true)), Some(json!({}))] {
7054 let mut wire = json!({ "state": "idle", "_meta": { "source": "test" } });
7055 if let Some(stop_reason) = stop_reason {
7056 wire["stopReason"] = stop_reason;
7057 }
7058 let StateUpdate::Idle(idle) = serde_json::from_value(wire).unwrap() else {
7059 panic!("expected idle state update");
7060 };
7061 assert_eq!(idle.stop_reason, None);
7062 assert_eq!(idle.meta, Some(meta.clone()));
7063 }
7064
7065 let wire = json!({
7068 "state": "idle",
7069 "stopReason": "_paused",
7070 "resumeAfter": 30,
7071 "_meta": { "source": "test" }
7072 });
7073 let parsed: StateUpdate = serde_json::from_value(wire.clone()).unwrap();
7074 let expected = StateUpdate::Idle(
7075 IdleStateUpdate::new()
7076 .stop_reason(StopReason::Other(OtherStopReason::new(
7077 "_paused",
7078 [("resumeAfter".into(), json!(30))].into_iter().collect(),
7079 )))
7080 .meta(meta),
7081 );
7082 assert_eq!(parsed, expected);
7083 assert_eq!(serde_json::to_value(&parsed).unwrap(), wire);
7084 }
7085
7086 #[test]
7087 fn known_stop_reasons_are_never_read_as_other() {
7088 use crate::v2::{ErrorStopReason, OtherStopReason};
7089 use serde_json::json;
7090
7091 let known = [
7092 StopReason::EndTurn,
7093 StopReason::MaxTokens,
7094 StopReason::MaxTurnRequests,
7095 StopReason::Refusal,
7096 StopReason::Cancelled,
7097 StopReason::Error(ErrorStopReason::new()),
7098 ];
7099 for stop_reason in &known {
7101 match stop_reason {
7102 StopReason::EndTurn
7103 | StopReason::MaxTokens
7104 | StopReason::MaxTurnRequests
7105 | StopReason::Refusal
7106 | StopReason::Cancelled
7107 | StopReason::Error(_)
7108 | StopReason::Other(_) => {}
7109 }
7110 }
7111
7112 for stop_reason in known {
7113 let update = StateUpdate::Idle(IdleStateUpdate::new().stop_reason(stop_reason));
7114 let wire = serde_json::to_value(&update).unwrap();
7115 assert_eq!(
7116 serde_json::from_value::<StateUpdate>(wire.clone()).unwrap(),
7117 update
7118 );
7119 assert!(
7120 serde_json::from_value::<OtherStopReason>(
7121 json!({ "stopReason": wire["stopReason"] })
7122 )
7123 .is_err(),
7124 "{} must not be accepted as a custom stop reason",
7125 wire["stopReason"]
7126 );
7127 }
7128 }
7129
7130 #[test]
7131 fn unknown_stop_reason_leaves_usage_on_the_idle_update() {
7132 use serde_json::json;
7133
7134 let usage = json!({ "totalTokens": 10, "inputTokens": 6, "outputTokens": 4 });
7135 let wire = json!({ "state": "idle", "stopReason": "_paused", "usage": usage });
7136 let StateUpdate::Idle(idle) = serde_json::from_value(wire.clone()).unwrap() else {
7137 panic!("expected idle state update");
7138 };
7139 let Some(StopReason::Other(other)) = &idle.stop_reason else {
7140 panic!("expected a custom stop reason");
7141 };
7142 assert!(other.fields.is_empty());
7143
7144 #[cfg(feature = "unstable_end_turn_token_usage")]
7145 {
7146 assert!(idle.usage.is_some());
7147 assert_eq!(serde_json::to_value(&idle).unwrap()["usage"], usage);
7148 }
7149 #[cfg(not(feature = "unstable_end_turn_token_usage"))]
7152 assert!(serde_json::to_value(&idle).unwrap().get("usage").is_none());
7153 }
7154
7155 #[test]
7156 fn test_state_update_serialization() {
7157 use serde_json::json;
7158
7159 assert_eq!(
7160 serde_json::to_value(SessionUpdate::StateUpdate(StateUpdate::Running(
7161 RunningStateUpdate::new()
7162 )))
7163 .unwrap(),
7164 json!({
7165 "sessionUpdate": "state_update",
7166 "state": "running"
7167 })
7168 );
7169
7170 assert_eq!(
7171 serde_json::to_value(SessionUpdate::StateUpdate(StateUpdate::Idle(
7172 IdleStateUpdate::new().stop_reason(StopReason::EndTurn)
7173 )))
7174 .unwrap(),
7175 json!({
7176 "sessionUpdate": "state_update",
7177 "state": "idle",
7178 "stopReason": "end_turn"
7179 })
7180 );
7181
7182 let SessionUpdate::StateUpdate(update) = serde_json::from_value(json!({
7183 "sessionUpdate": "state_update",
7184 "state": "requires_action"
7185 }))
7186 .unwrap() else {
7187 panic!("expected state update");
7188 };
7189
7190 assert!(matches!(update, StateUpdate::RequiresAction(_)));
7191
7192 let SessionUpdate::StateUpdate(StateUpdate::Idle(update)) = serde_json::from_value(json!({
7193 "sessionUpdate": "state_update",
7194 "state": "idle",
7195 "stopReason": null
7196 }))
7197 .unwrap() else {
7198 panic!("expected idle state update");
7199 };
7200
7201 assert_eq!(update.stop_reason, None);
7202
7203 let SessionUpdate::StateUpdate(StateUpdate::Other(update)) =
7204 serde_json::from_value(json!({
7205 "sessionUpdate": "state_update",
7206 "state": "_paused",
7207 "label": "Paused"
7208 }))
7209 .unwrap()
7210 else {
7211 panic!("expected unknown state update");
7212 };
7213
7214 assert_eq!(update.state, "_paused");
7215 assert_eq!(update.fields["label"], json!("Paused"));
7216 }
7217
7218 #[test]
7219 fn session_update_preserves_unknown_variant() {
7220 use serde_json::json;
7221
7222 let update: SessionUpdate = serde_json::from_value(json!({
7223 "sessionUpdate": "_status_badge",
7224 "label": "Indexing",
7225 "progress": 0.5
7226 }))
7227 .unwrap();
7228
7229 let SessionUpdate::Other(unknown) = update else {
7230 panic!("expected unknown session update");
7231 };
7232
7233 assert_eq!(unknown.session_update, "_status_badge");
7234 assert_eq!(unknown.fields.get("label"), Some(&json!("Indexing")));
7235 assert_eq!(unknown.fields.get("progress"), Some(&json!(0.5)));
7236
7237 assert_eq!(
7238 serde_json::to_value(SessionUpdate::Other(unknown)).unwrap(),
7239 json!({
7240 "sessionUpdate": "_status_badge",
7241 "label": "Indexing",
7242 "progress": 0.5
7243 })
7244 );
7245 }
7246
7247 #[test]
7248 fn terminal_session_updates_use_known_discriminators() {
7249 use serde_json::json;
7250
7251 assert_eq!(
7252 serde_json::to_value(SessionUpdate::TerminalUpdate(
7253 TerminalUpdate::new("term_1").command("cargo test")
7254 ))
7255 .unwrap(),
7256 json!({
7257 "sessionUpdate": "terminal_update",
7258 "terminalId": "term_1",
7259 "command": "cargo test"
7260 })
7261 );
7262 assert_eq!(
7263 serde_json::to_value(SessionUpdate::TerminalOutputChunk(
7264 TerminalOutputChunk::new("term_1", "dGVzdAo=")
7265 ))
7266 .unwrap(),
7267 json!({
7268 "sessionUpdate": "terminal_output_chunk",
7269 "terminalId": "term_1",
7270 "data": "dGVzdAo="
7271 })
7272 );
7273 }
7274
7275 #[test]
7276 fn session_update_does_not_hide_malformed_known_terminal_variants() {
7277 use serde_json::json;
7278
7279 assert!(
7280 serde_json::from_value::<SessionUpdate>(json!({
7281 "sessionUpdate": "terminal_update"
7282 }))
7283 .is_err()
7284 );
7285 assert!(
7286 serde_json::from_value::<SessionUpdate>(json!({
7287 "sessionUpdate": "terminal_output_chunk",
7288 "terminalId": "term_1"
7289 }))
7290 .is_err()
7291 );
7292 }
7293
7294 #[test]
7295 fn test_plan_update_serialization() {
7296 use serde_json::json;
7297
7298 let plan_update =
7299 SessionUpdate::PlanUpdate(PlanUpdate::new(crate::v2::PlanUpdateContent::items(
7300 "plan-1",
7301 vec![crate::v2::PlanEntry::new(
7302 "Step 1",
7303 crate::v2::PlanEntryPriority::High,
7304 crate::v2::PlanEntryStatus::Pending,
7305 )],
7306 )));
7307
7308 assert_eq!(
7309 serde_json::to_value(plan_update).unwrap(),
7310 json!({
7311 "sessionUpdate": "plan_update",
7312 "plan": {
7313 "type": "items",
7314 "planId": "plan-1",
7315 "entries": [
7316 {
7317 "content": "Step 1",
7318 "priority": "high",
7319 "status": "pending"
7320 }
7321 ]
7322 }
7323 })
7324 );
7325 }
7326
7327 #[cfg(feature = "unstable_plan_operations")]
7328 #[test]
7329 fn test_plan_removed_serialization() {
7330 use serde_json::json;
7331
7332 assert_eq!(
7333 serde_json::to_value(SessionUpdate::PlanRemoved(PlanRemoved::new("plan-1"))).unwrap(),
7334 json!({
7335 "sessionUpdate": "plan_removed",
7336 "planId": "plan-1"
7337 })
7338 );
7339 }
7340
7341 #[test]
7342 fn available_command_uses_type_discriminator() {
7343 use serde_json::json;
7344
7345 let command = AvailableCommand::Command(
7346 Command::new("web", "Search the web")
7347 .input(AvailableCommandInput::Text(TextCommandInput::new("Query"))),
7348 );
7349
7350 let json = serde_json::to_value(&command).unwrap();
7351 assert_eq!(
7352 json,
7353 json!({
7354 "type": "command",
7355 "name": "web",
7356 "description": "Search the web",
7357 "input": { "type": "text", "hint": "Query" }
7358 })
7359 );
7360
7361 let roundtripped: AvailableCommand = serde_json::from_value(json).unwrap();
7362 assert_eq!(roundtripped, command);
7363 assert_eq!(roundtripped.name(), "web");
7364 assert_eq!(roundtripped.description(), "Search the web");
7365 }
7366
7367 #[test]
7368 fn available_command_preserves_unknown_typed_variant() {
7369 use serde_json::json;
7370
7371 let payload = json!({
7372 "type": "_skill",
7373 "name": "pdf-processing",
7374 "description": "Extract text from PDFs",
7375 "uri": "skill://pdf-processing/SKILL.md",
7376 "_meta": { "example.com/source": "mcp" }
7377 });
7378 let command: AvailableCommand = serde_json::from_value(payload.clone()).unwrap();
7379
7380 assert_eq!(command.name(), "pdf-processing");
7381 assert_eq!(command.description(), "Extract text from PDFs");
7382 assert!(command.meta().is_some());
7383
7384 let AvailableCommand::Other(unknown) = &command else {
7385 panic!("expected unknown command");
7386 };
7387 assert_eq!(unknown.type_, "_skill");
7388 assert_eq!(
7389 unknown.fields.get("uri"),
7390 Some(&json!("skill://pdf-processing/SKILL.md"))
7391 );
7392 assert_eq!(serde_json::to_value(&command).unwrap(), payload);
7393 }
7394
7395 #[test]
7396 fn available_command_unknown_tolerates_invalid_meta() {
7397 use serde_json::json;
7398
7399 let command: AvailableCommand = serde_json::from_value(json!({
7400 "type": "_skill",
7401 "name": "pdf-processing",
7402 "description": "Extract text from PDFs",
7403 "_meta": "oops"
7404 }))
7405 .unwrap();
7406
7407 assert!(matches!(command, AvailableCommand::Other(_)));
7408 assert!(command.meta().is_none());
7409 }
7410
7411 #[test]
7412 fn available_command_unknown_does_not_hide_malformed_command_variant() {
7413 use serde_json::json;
7414
7415 assert!(
7417 serde_json::from_value::<AvailableCommand>(json!({
7418 "name": "test",
7419 "description": "Run project tests"
7420 }))
7421 .is_err()
7422 );
7423 assert!(
7424 serde_json::from_value::<AvailableCommand>(json!({
7425 "type": "command",
7426 "name": "test"
7427 }))
7428 .is_err()
7429 );
7430 assert!(
7431 serde_json::from_value::<OtherAvailableCommand>(json!({
7432 "type": "command",
7433 "name": "test",
7434 "description": "Run project tests"
7435 }))
7436 .is_err()
7437 );
7438 assert!(
7439 serde_json::from_value::<AvailableCommand>(json!({
7440 "type": "_skill",
7441 "name": "pdf-processing"
7442 }))
7443 .is_err()
7444 );
7445 }
7446
7447 #[cfg(feature = "unstable_agent_skills")]
7448 #[test]
7449 fn skill_command_uses_type_discriminator() {
7450 use serde_json::json;
7451
7452 let skill = AvailableCommand::Skill(
7453 Skill::new("pdf-processing", "Extract text and tables from PDF files").path(
7454 AbsolutePath::new("/home/alice/.agents/skills/pdf-processing/SKILL.md"),
7455 ),
7456 );
7457
7458 let wire = json!({
7459 "type": "skill",
7460 "name": "pdf-processing",
7461 "description": "Extract text and tables from PDF files",
7462 "path": "/home/alice/.agents/skills/pdf-processing/SKILL.md"
7463 });
7464 assert_eq!(serde_json::to_value(&skill).unwrap(), wire);
7465
7466 let roundtripped: AvailableCommand = serde_json::from_value(wire).unwrap();
7467 assert_eq!(roundtripped, skill);
7468 assert_eq!(roundtripped.name(), "pdf-processing");
7469 assert_eq!(
7470 roundtripped.description(),
7471 "Extract text and tables from PDF files"
7472 );
7473 assert!(roundtripped.meta().is_none());
7474
7475 assert_eq!(
7477 serde_json::to_value(AvailableCommand::Skill(Skill::new(
7478 "simplify",
7479 "Simplify the changed code"
7480 )))
7481 .unwrap(),
7482 json!({
7483 "type": "skill",
7484 "name": "simplify",
7485 "description": "Simplify the changed code"
7486 })
7487 );
7488 }
7489
7490 #[cfg(feature = "unstable_agent_skills")]
7491 #[test]
7492 fn skill_command_treats_invalid_display_fields_as_absent() {
7493 use serde_json::json;
7494
7495 let expected = AvailableCommand::Skill(Skill::new("pdf-processing", "Extract text"));
7496 for (field, value) in [
7497 ("path", json!(null)),
7498 ("path", json!(7)),
7499 ("path", json!({ "uri": "file:///SKILL.md" })),
7500 ("_meta", json!(null)),
7501 ("_meta", json!("oops")),
7502 ] {
7503 let mut wire = json!({
7504 "type": "skill",
7505 "name": "pdf-processing",
7506 "description": "Extract text"
7507 });
7508 wire[field] = value;
7509 assert_eq!(
7510 serde_json::from_value::<AvailableCommand>(wire).unwrap(),
7511 expected,
7512 "{field}"
7513 );
7514 }
7515 }
7516
7517 #[cfg(feature = "unstable_agent_skills")]
7518 #[test]
7519 fn skill_command_has_no_input_specification() {
7520 use serde_json::json;
7521
7522 let skill: AvailableCommand = serde_json::from_value(json!({
7524 "type": "skill",
7525 "name": "pdf-processing",
7526 "description": "Extract text",
7527 "input": { "type": "text", "hint": "file or instructions" }
7528 }))
7529 .unwrap();
7530 assert_eq!(
7531 skill,
7532 AvailableCommand::Skill(Skill::new("pdf-processing", "Extract text"))
7533 );
7534 assert!(serde_json::to_value(&skill).unwrap().get("input").is_none());
7535 }
7536
7537 #[cfg(feature = "unstable_agent_skills")]
7538 #[test]
7539 fn malformed_skill_command_is_skipped_and_never_preserved_as_unknown() {
7540 use serde_json::json;
7541
7542 for malformed in [
7543 json!({ "type": "skill", "name": "pdf-processing" }),
7544 json!({ "type": "skill", "description": "Extract text" }),
7545 json!({ "type": "skill", "name": 1, "description": "Extract text" }),
7546 ] {
7547 assert!(serde_json::from_value::<AvailableCommand>(malformed.clone()).is_err());
7548 assert!(serde_json::from_value::<OtherAvailableCommand>(malformed).is_err());
7549 }
7550
7551 let update: AvailableCommandsUpdate = serde_json::from_value(json!({
7553 "availableCommands": [
7554 { "type": "skill", "name": "pdf-processing", "description": "Extract text" },
7555 { "type": "skill", "name": "broken" },
7556 { "type": "command", "name": "test", "description": "Run project tests" }
7557 ]
7558 }))
7559 .unwrap();
7560 assert_eq!(
7561 update.available_commands,
7562 vec![
7563 AvailableCommand::Skill(Skill::new("pdf-processing", "Extract text")),
7564 AvailableCommand::Command(Command::new("test", "Run project tests")),
7565 ]
7566 );
7567 }
7568
7569 #[cfg(feature = "unstable_agent_skills")]
7570 #[test]
7571 fn skill_commands_capability_is_advertised_only_by_an_object() {
7572 use serde_json::json;
7573
7574 let capabilities = ClientCapabilities::new().session(
7575 ClientSessionCapabilities::new()
7576 .commands(CommandsCapabilities::new().skill(CommandsSkillCapabilities::new())),
7577 );
7578 let wire = json!({ "session": { "commands": { "skill": {} } } });
7579 assert_eq!(serde_json::to_value(&capabilities).unwrap(), wire);
7580 assert_eq!(
7581 serde_json::from_value::<ClientCapabilities>(wire).unwrap(),
7582 capabilities
7583 );
7584
7585 for unsupported in [
7587 json!({}),
7588 json!({ "session": null }),
7589 json!({ "session": {} }),
7590 json!({ "session": { "commands": null } }),
7591 json!({ "session": { "commands": {} } }),
7592 json!({ "session": { "commands": true } }),
7593 json!({ "session": { "commands": { "skill": null } } }),
7594 json!({ "session": { "commands": { "skill": true } } }),
7595 json!({ "session": { "commands": { "skill": "supported" } } }),
7596 ] {
7597 let capabilities: ClientCapabilities = serde_json::from_value(unsupported).unwrap();
7598 assert!(
7599 capabilities
7600 .session
7601 .and_then(|session| session.commands)
7602 .and_then(|commands| commands.skill)
7603 .is_none()
7604 );
7605 }
7606 }
7607
7608 #[cfg(all(
7609 feature = "unstable_agent_skills",
7610 feature = "unstable_prompt_suggestions"
7611 ))]
7612 #[test]
7613 fn client_session_capabilities_are_independent_of_each_other() {
7614 use serde_json::json;
7615
7616 let capabilities: ClientCapabilities = serde_json::from_value(json!({
7618 "session": {
7619 "promptSuggestions": true,
7620 "commands": { "skill": {} }
7621 }
7622 }))
7623 .unwrap();
7624 let session = capabilities.session.unwrap();
7625 assert!(session.prompt_suggestions.is_none());
7626 assert!(session.commands.unwrap().skill.is_some());
7627 }
7628
7629 #[cfg(all(feature = "schemars", feature = "unstable_agent_skills"))]
7630 #[test]
7631 fn skill_schemas_keep_acted_on_fields_strict() {
7632 use serde_json::json;
7633
7634 let skill = serde_json::to_value(schemars::schema_for!(Skill)).unwrap();
7635 assert_eq!(skill["required"], json!(["name", "description"]));
7636 for lenient in ["path", "_meta"] {
7637 assert_eq!(
7638 skill["properties"][lenient]["x-deserialize-default-on-error"], true,
7639 "{lenient}"
7640 );
7641 }
7642
7643 let reference =
7645 serde_json::to_value(schemars::schema_for!(crate::v2::SkillReference)).unwrap();
7646 assert_eq!(reference["required"], json!(["name"]));
7647 assert!(
7648 reference["properties"]["name"]
7649 .get("x-deserialize-default-on-error")
7650 .is_none()
7651 );
7652 }
7653
7654 #[test]
7655 fn available_command_input_preserves_unknown_typed_variant() {
7656 use serde_json::json;
7657
7658 let input: AvailableCommandInput = serde_json::from_value(json!({
7659 "type": "_choices",
7660 "hint": "Pick one",
7661 "options": ["fast", "careful"]
7662 }))
7663 .unwrap();
7664
7665 let AvailableCommandInput::Other(unknown) = input else {
7666 panic!("expected unknown command input");
7667 };
7668
7669 assert_eq!(unknown.type_, "_choices");
7670 assert_eq!(unknown.fields.get("hint"), Some(&json!("Pick one")));
7671 assert_eq!(
7672 unknown.fields.get("options"),
7673 Some(&json!(["fast", "careful"]))
7674 );
7675 assert_eq!(
7676 serde_json::to_value(AvailableCommandInput::Other(unknown)).unwrap(),
7677 json!({
7678 "type": "_choices",
7679 "hint": "Pick one",
7680 "options": ["fast", "careful"]
7681 })
7682 );
7683 }
7684
7685 #[test]
7686 fn available_command_input_text_uses_type_discriminator() {
7687 use serde_json::json;
7688
7689 let input = AvailableCommandInput::Text(TextCommandInput::new("Describe changes"));
7690
7691 let json = serde_json::to_value(&input).unwrap();
7692 assert_eq!(
7693 json,
7694 json!({
7695 "type": "text",
7696 "hint": "Describe changes"
7697 })
7698 );
7699
7700 let roundtripped: AvailableCommandInput = serde_json::from_value(json).unwrap();
7701 assert!(matches!(roundtripped, AvailableCommandInput::Text(_)));
7702 }
7703
7704 #[test]
7705 fn request_permission_subject_tool_call_uses_type_discriminator() {
7706 use serde_json::json;
7707
7708 let subject = RequestPermissionSubject::from(ToolCallUpdate::new("call_001"));
7709
7710 let json = serde_json::to_value(&subject).unwrap();
7711 assert_eq!(
7712 json,
7713 json!({
7714 "type": "tool_call",
7715 "toolCall": {
7716 "toolCallId": "call_001"
7717 }
7718 })
7719 );
7720
7721 let roundtripped: RequestPermissionSubject = serde_json::from_value(json).unwrap();
7722 assert!(matches!(
7723 roundtripped,
7724 RequestPermissionSubject::ToolCall(_)
7725 ));
7726 }
7727
7728 #[test]
7729 fn request_permission_subject_command_uses_type_discriminator() {
7730 use serde_json::json;
7731
7732 let mut meta = Meta::new();
7733 meta.insert("source".to_string(), json!("shell"));
7734 let subject = RequestPermissionSubject::from(
7735 CommandPermissionSubject::new("cargo test", "/workspace/project")
7736 .tool_call_id("call_001")
7737 .terminal_id("term_1")
7738 .meta(meta),
7739 );
7740
7741 let json = serde_json::to_value(&subject).unwrap();
7742 assert_eq!(
7743 json,
7744 json!({
7745 "type": "command",
7746 "command": "cargo test",
7747 "cwd": "/workspace/project",
7748 "toolCallId": "call_001",
7749 "terminalId": "term_1",
7750 "_meta": {
7751 "source": "shell"
7752 }
7753 })
7754 );
7755
7756 let roundtripped: RequestPermissionSubject = serde_json::from_value(json).unwrap();
7757 assert!(matches!(roundtripped, RequestPermissionSubject::Command(_)));
7758 }
7759
7760 #[test]
7761 fn command_permission_subject_treats_optional_association_nulls_as_omitted() {
7762 use serde_json::json;
7763
7764 let subject: RequestPermissionSubject = serde_json::from_value(json!({
7765 "type": "command",
7766 "command": "cargo test",
7767 "cwd": "/workspace/project",
7768 "toolCallId": null,
7769 "terminalId": null,
7770 "_meta": null
7771 }))
7772 .unwrap();
7773
7774 let RequestPermissionSubject::Command(subject) = subject else {
7775 panic!("expected command permission subject");
7776 };
7777 assert_eq!(subject.cwd, AbsolutePath::new("/workspace/project"));
7778 assert_eq!(subject.tool_call_id, None);
7779 assert_eq!(subject.terminal_id, None);
7780 assert_eq!(subject.meta, None);
7781 assert_eq!(
7782 serde_json::to_value(RequestPermissionSubject::Command(subject)).unwrap(),
7783 json!({
7784 "type": "command",
7785 "command": "cargo test",
7786 "cwd": "/workspace/project"
7787 })
7788 );
7789 }
7790
7791 #[test]
7792 fn request_permission_subject_preserves_unknown_variant() {
7793 use serde_json::json;
7794
7795 let subject: RequestPermissionSubject = serde_json::from_value(json!({
7796 "type": "_review",
7797 "reason": "needs-review",
7798 "retryAfterSeconds": 30
7799 }))
7800 .unwrap();
7801
7802 let RequestPermissionSubject::Other(unknown) = subject else {
7803 panic!("expected unknown permission subject");
7804 };
7805
7806 assert_eq!(unknown.type_, "_review");
7807 assert_eq!(unknown.fields.get("reason"), Some(&json!("needs-review")));
7808 assert_eq!(unknown.fields.get("retryAfterSeconds"), Some(&json!(30)));
7809 assert_eq!(
7810 serde_json::to_value(RequestPermissionSubject::Other(unknown)).unwrap(),
7811 json!({
7812 "type": "_review",
7813 "reason": "needs-review",
7814 "retryAfterSeconds": 30
7815 })
7816 );
7817 }
7818
7819 #[test]
7820 fn request_permission_subject_unknown_does_not_hide_malformed_known_variant() {
7821 use serde_json::json;
7822
7823 assert!(
7824 serde_json::from_value::<RequestPermissionSubject>(json!({
7825 "type": "tool_call"
7826 }))
7827 .is_err()
7828 );
7829 assert!(
7830 serde_json::from_value::<RequestPermissionSubject>(json!({
7831 "type": 1
7832 }))
7833 .is_err()
7834 );
7835 assert!(
7836 serde_json::from_value::<RequestPermissionSubject>(json!({
7837 "type": "command",
7838 "cwd": "/workspace/project"
7839 }))
7840 .is_err()
7841 );
7842 assert!(
7843 serde_json::from_value::<RequestPermissionSubject>(json!({
7844 "type": "command",
7845 "command": "cargo test"
7846 }))
7847 .is_err()
7848 );
7849 assert!(
7850 serde_json::from_value::<RequestPermissionSubject>(json!({
7851 "type": "command",
7852 "command": "cargo test",
7853 "cwd": null
7854 }))
7855 .is_err()
7856 );
7857 }
7858
7859 #[test]
7860 fn request_permission_title_and_description_are_separate_from_tool_call_content() {
7861 use serde_json::json;
7862
7863 let request =
7864 RequestPermissionRequest::new("sess_abc123def456", "Approve file edit?", Vec::new())
7865 .description("Allow this tool to edit src/main.rs?")
7866 .subject(RequestPermissionSubject::from(ToolCallUpdate::new(
7867 "call_001",
7868 )));
7869
7870 assert_eq!(
7871 serde_json::to_value(request).unwrap(),
7872 json!({
7873 "sessionId": "sess_abc123def456",
7874 "title": "Approve file edit?",
7875 "description": "Allow this tool to edit src/main.rs?",
7876 "subject": {
7877 "type": "tool_call",
7878 "toolCall": {
7879 "toolCallId": "call_001"
7880 }
7881 },
7882 "options": []
7883 })
7884 );
7885 }
7886
7887 #[test]
7888 fn request_permission_requires_title_and_allows_missing_subject() {
7889 use serde_json::json;
7890
7891 let request = RequestPermissionRequest::new(
7892 "sess_abc123def456",
7893 "Approve elevated permissions?",
7894 Vec::new(),
7895 );
7896
7897 assert_eq!(
7898 serde_json::to_value(request).unwrap(),
7899 json!({
7900 "sessionId": "sess_abc123def456",
7901 "title": "Approve elevated permissions?",
7902 "options": []
7903 })
7904 );
7905
7906 let missing_subject: RequestPermissionRequest = serde_json::from_value(json!({
7907 "sessionId": "sess_abc123def456",
7908 "title": "Approve elevated permissions?",
7909 "options": []
7910 }))
7911 .unwrap();
7912 assert!(missing_subject.subject.is_none());
7913
7914 let null_subject: RequestPermissionRequest = serde_json::from_value(json!({
7915 "sessionId": "sess_abc123def456",
7916 "title": "Approve elevated permissions?",
7917 "subject": null,
7918 "options": []
7919 }))
7920 .unwrap();
7921 assert!(null_subject.subject.is_none());
7922
7923 assert!(
7924 serde_json::from_value::<RequestPermissionRequest>(json!({
7925 "sessionId": "sess_abc123def456",
7926 "options": []
7927 }))
7928 .is_err()
7929 );
7930 }
7931
7932 #[test]
7933 fn request_permission_outcome_preserves_unknown_variant() {
7934 use serde_json::json;
7935
7936 let outcome: RequestPermissionOutcome = serde_json::from_value(json!({
7937 "outcome": "_defer",
7938 "reason": "needs-review",
7939 "retryAfterSeconds": 30
7940 }))
7941 .unwrap();
7942
7943 let RequestPermissionOutcome::Other(unknown) = outcome else {
7944 panic!("expected unknown permission outcome");
7945 };
7946
7947 assert_eq!(unknown.outcome, "_defer");
7948 assert_eq!(unknown.fields.get("reason"), Some(&json!("needs-review")));
7949 assert_eq!(unknown.fields.get("retryAfterSeconds"), Some(&json!(30)));
7950 assert_eq!(
7951 serde_json::to_value(RequestPermissionOutcome::Other(unknown)).unwrap(),
7952 json!({
7953 "outcome": "_defer",
7954 "reason": "needs-review",
7955 "retryAfterSeconds": 30
7956 })
7957 );
7958 }
7959
7960 #[test]
7961 fn request_permission_outcome_unknown_does_not_hide_malformed_known_variant() {
7962 use serde_json::json;
7963
7964 assert!(
7965 serde_json::from_value::<RequestPermissionOutcome>(json!({
7966 "outcome": "selected"
7967 }))
7968 .is_err()
7969 );
7970 assert!(
7971 serde_json::from_value::<RequestPermissionOutcome>(json!({
7972 "outcome": 1
7973 }))
7974 .is_err()
7975 );
7976 }
7977
7978 #[test]
7979 fn available_command_input_unknown_does_not_hide_malformed_text_variant() {
7980 use serde_json::json;
7981
7982 assert!(serde_json::from_value::<AvailableCommandInput>(json!({})).is_err());
7983 assert!(
7984 serde_json::from_value::<AvailableCommandInput>(json!({
7985 "hint": "Pick one"
7986 }))
7987 .is_err()
7988 );
7989 assert!(
7990 serde_json::from_value::<AvailableCommandInput>(json!({
7991 "type": 1,
7992 "hint": "Pick one"
7993 }))
7994 .is_err()
7995 );
7996 assert!(
7997 serde_json::from_value::<OtherAvailableCommandInput>(json!({
7998 "type": "text",
7999 "hint": "Pick one"
8000 }))
8001 .is_err()
8002 );
8003 }
8004
8005 #[cfg(feature = "unstable_mcp_over_acp")]
8006 #[test]
8007 fn test_agent_mcp_request_method_names() {
8008 use serde_json::json;
8009
8010 let params: serde_json::Map<String, serde_json::Value> =
8011 [("cursor".to_string(), json!("abc"))].into_iter().collect();
8012
8013 assert_eq!(CLIENT_METHOD_NAMES.mcp_message, "mcp/message");
8014 assert_eq!(
8015 AgentRequest::MessageMcpRequest(Box::new(MessageMcpRequest::new(
8016 "server-1",
8017 "req-1",
8018 "tools/list"
8019 )))
8020 .method(),
8021 "mcp/message"
8022 );
8023 assert_eq!(
8024 serde_json::to_value(
8025 MessageMcpRequest::new("server-1", "req-1", "tools/list").params(params)
8026 )
8027 .unwrap(),
8028 json!({
8029 "serverId": "server-1",
8030 "requestId": "req-1",
8031 "method": "tools/list",
8032 "params": { "cursor": "abc" }
8033 })
8034 );
8035
8036 let request_with_null_params: MessageMcpRequest = serde_json::from_value(json!({
8037 "serverId": "server-1",
8038 "requestId": "req-1",
8039 "method": "tools/list",
8040 "params": null,
8041 "_meta": null
8042 }))
8043 .unwrap();
8044 assert_eq!(request_with_null_params.params, None);
8045 assert_eq!(request_with_null_params.meta, None);
8046 for key in ["serverId", "requestId", "method"] {
8047 let mut value =
8048 json!({"serverId":"server-1", "requestId":"req-1", "method":"tools/list"});
8049 value.as_object_mut().unwrap().remove(key);
8050 assert!(serde_json::from_value::<MessageMcpRequest>(value).is_err());
8051 }
8052 for key in ["serverId", "requestId", "method"] {
8053 let mut value =
8054 json!({"serverId":"server-1", "requestId":"req-1", "method":"tools/list"});
8055 value[key] = serde_json::Value::Null;
8056 assert!(serde_json::from_value::<MessageMcpRequest>(value).is_err());
8057 }
8058 }
8059
8060 #[test]
8061 fn test_auth_capabilities_serialize_terminal_support_as_object() {
8062 use serde_json::json;
8063
8064 let capabilities = ClientAuthCapabilities::new().terminal(TerminalAuthCapabilities::new());
8065
8066 assert_eq!(
8067 serde_json::to_value(&capabilities).unwrap(),
8068 json!({
8069 "terminal": {}
8070 })
8071 );
8072
8073 let deserialized: ClientAuthCapabilities = serde_json::from_value(json!({
8074 "terminal": false
8075 }))
8076 .unwrap();
8077 assert!(deserialized.terminal.is_none());
8078 }
8079
8080 #[test]
8081 fn request_permission_request_rejects_malformed_options() {
8082 use serde_json::json;
8083
8084 assert!(
8085 serde_json::from_value::<RequestPermissionRequest>(json!({
8086 "sessionId": "sess-1",
8087 "title": "Run tool?",
8088 "options": "not-an-array"
8089 }))
8090 .is_err()
8091 );
8092 assert!(
8093 serde_json::from_value::<RequestPermissionRequest>(json!({
8094 "sessionId": "sess-1",
8095 "title": "Run tool?",
8096 "options": [{"optionId": "allow"}]
8097 }))
8098 .is_err()
8099 );
8100 }
8101
8102 #[cfg(feature = "unstable_plan_operations")]
8103 #[test]
8104 fn malformed_plan_removed_is_not_hidden_as_unknown_update() {
8105 use serde_json::json;
8106
8107 assert!(
8108 serde_json::from_value::<SessionUpdate>(json!({
8109 "sessionUpdate": "plan_removed"
8110 }))
8111 .is_err()
8112 );
8113 }
8114
8115 #[cfg(feature = "unstable_session_cursors")]
8116 #[test]
8117 fn cursor_updates_round_trip_and_patch_capabilities() {
8118 use serde_json::json;
8119
8120 let update = SessionUpdate::CursorUpdate(
8121 CursorUpdate::new("cur_1")
8122 .capabilities(CursorCapabilities::new())
8123 .anchor(CursorAnchor::UserMessage(CursorMessageAnchor::new(
8124 "msg_user_2",
8125 CursorAnchorPosition::Before,
8126 ))),
8127 );
8128 let wire = json!({
8129 "sessionUpdate": "cursor_update",
8130 "cursorId": "cur_1",
8131 "capabilities": {},
8132 "anchor": { "type": "user_message", "messageId": "msg_user_2", "position": "before" }
8133 });
8134 assert_eq!(serde_json::to_value(&update).unwrap(), wire);
8135 assert_eq!(
8136 serde_json::from_value::<SessionUpdate>(wire).unwrap(),
8137 update
8138 );
8139
8140 let SessionUpdate::CursorUpdate(omitted) = serde_json::from_value(json!({
8142 "sessionUpdate": "cursor_update",
8143 "cursorId": "cur_1"
8144 }))
8145 .unwrap() else {
8146 panic!("expected cursor update");
8147 };
8148 assert!(omitted.capabilities.is_undefined());
8149 assert_eq!(omitted.anchor, None);
8150 assert!(omitted.meta.is_undefined());
8151 assert_eq!(
8152 serde_json::to_value(SessionUpdate::CursorUpdate(CursorUpdate::new("cur_1"))).unwrap(),
8153 json!({ "sessionUpdate": "cursor_update", "cursorId": "cur_1" })
8154 );
8155
8156 let SessionUpdate::CursorUpdate(cleared) = serde_json::from_value(json!({
8158 "sessionUpdate": "cursor_update",
8159 "cursorId": "cur_1",
8160 "capabilities": null,
8161 "anchor": null
8162 }))
8163 .unwrap() else {
8164 panic!("expected cursor update");
8165 };
8166 assert!(cleared.capabilities.is_null());
8167 assert_eq!(cleared.anchor, None);
8168 assert_eq!(
8169 serde_json::to_value(SessionUpdate::CursorUpdate(
8170 CursorUpdate::new("cur_1").capabilities(None)
8171 ))
8172 .unwrap(),
8173 json!({ "sessionUpdate": "cursor_update", "cursorId": "cur_1", "capabilities": null })
8174 );
8175 }
8176
8177 #[cfg(feature = "unstable_session_cursors")]
8178 #[test]
8179 fn cursor_anchors_cover_each_entity_type_and_preserve_unknown_ones() {
8180 use serde_json::json;
8181
8182 for (anchor, wire) in [
8183 (
8184 CursorAnchor::AgentMessage(CursorMessageAnchor::new(
8185 "msg_agent_1",
8186 CursorAnchorPosition::After,
8187 )),
8188 json!({ "type": "agent_message", "messageId": "msg_agent_1", "position": "after" }),
8189 ),
8190 (
8191 CursorAnchor::AgentThought(CursorMessageAnchor::new(
8192 "msg_agent_1",
8193 CursorAnchorPosition::After,
8194 )),
8195 json!({ "type": "agent_thought", "messageId": "msg_agent_1", "position": "after" }),
8196 ),
8197 (
8198 CursorAnchor::SessionMessage(CursorMessageAnchor::new(
8199 "msg_session_1",
8200 CursorAnchorPosition::Before,
8201 )),
8202 json!({ "type": "session_message", "messageId": "msg_session_1", "position": "before" }),
8203 ),
8204 (
8205 CursorAnchor::ToolCall(CursorToolCallAnchor::new(
8206 "call_1",
8207 CursorAnchorPosition::After,
8208 )),
8209 json!({ "type": "tool_call", "toolCallId": "call_1", "position": "after" }),
8210 ),
8211 (
8212 CursorAnchor::Compaction(CursorCompactionAnchor::new(
8213 "cmp_1",
8214 CursorAnchorPosition::Before,
8215 )),
8216 json!({ "type": "compaction", "compactionId": "cmp_1", "position": "before" }),
8217 ),
8218 ] {
8219 assert_eq!(serde_json::to_value(&anchor).unwrap(), wire);
8220 assert_eq!(
8221 serde_json::from_value::<CursorAnchor>(wire).unwrap(),
8222 anchor
8223 );
8224 }
8225
8226 let wire = json!({ "type": "_acme_marker", "markerId": "mk_1", "position": "after" });
8228 let other = serde_json::from_value::<CursorAnchor>(wire.clone()).unwrap();
8229 assert!(matches!(other, CursorAnchor::Other(_)));
8230 assert_eq!(serde_json::to_value(&other).unwrap(), wire);
8231
8232 let wire =
8234 json!({ "type": "user_message", "messageId": "msg_user_2", "position": "inside" });
8235 let future = serde_json::from_value::<CursorAnchor>(wire.clone()).unwrap();
8236 assert_eq!(
8237 future,
8238 CursorAnchor::UserMessage(CursorMessageAnchor::new(
8239 "msg_user_2",
8240 CursorAnchorPosition::Other("inside".into()),
8241 ))
8242 );
8243 assert_eq!(serde_json::to_value(&future).unwrap(), wire);
8244 }
8245
8246 #[cfg(feature = "unstable_session_cursors")]
8247 #[test]
8248 fn malformed_cursor_anchor_fails_the_update() {
8249 use serde_json::json;
8250
8251 for anchor in [
8253 json!({ "type": "user_message", "position": "before" }),
8254 json!({ "type": "tool_call", "toolCallId": 7, "position": "after" }),
8255 json!({ "type": "compaction", "compactionId": "cmp_1" }),
8256 json!({ "messageId": "msg_user_2", "position": "before" }),
8257 json!("before"),
8258 ] {
8259 assert!(
8260 serde_json::from_value::<SessionUpdate>(json!({
8261 "sessionUpdate": "cursor_update",
8262 "cursorId": "cur_1",
8263 "anchor": anchor
8264 }))
8265 .is_err(),
8266 "{anchor}"
8267 );
8268 }
8269 assert!(
8271 serde_json::from_value::<SessionUpdate>(json!({ "sessionUpdate": "cursor_update" }))
8272 .is_err()
8273 );
8274 }
8275
8276 #[cfg(feature = "unstable_session_cursors")]
8277 #[test]
8278 fn malformed_cursor_capabilities_are_not_advertised() {
8279 use serde_json::json;
8280
8281 let SessionUpdate::CursorUpdate(update) = serde_json::from_value(json!({
8283 "sessionUpdate": "cursor_update",
8284 "cursorId": "cur_1",
8285 "capabilities": "fork"
8286 }))
8287 .unwrap() else {
8288 panic!("expected cursor update");
8289 };
8290 assert!(update.capabilities.is_undefined());
8291
8292 assert_eq!(
8294 serde_json::from_value::<CursorCapabilities>(json!({ "futureMethod": {} })).unwrap(),
8295 CursorCapabilities::new()
8296 );
8297
8298 #[cfg(feature = "unstable_session_fork")]
8299 {
8300 assert_eq!(
8301 serde_json::to_value(CursorCapabilities::new().fork(CursorForkCapabilities::new()))
8302 .unwrap(),
8303 json!({ "fork": {} })
8304 );
8305 assert_eq!(
8306 serde_json::from_value::<CursorCapabilities>(json!({ "fork": {} }))
8307 .unwrap()
8308 .fork,
8309 Some(CursorForkCapabilities::new())
8310 );
8311 for fork in [json!(null), json!(true), json!("yes")] {
8312 assert_eq!(
8313 serde_json::from_value::<CursorCapabilities>(json!({ "fork": fork }))
8314 .unwrap()
8315 .fork,
8316 None
8317 );
8318 }
8319 }
8320 }
8321}