1use std::{path::PathBuf, sync::Arc};
7
8use derive_more::{Display, From};
9use indexmap::IndexMap;
10#[cfg(feature = "schemars")]
11use schemars::Schema;
12use serde::{Deserialize, Serialize};
13use serde_with::{DefaultOnError, DefaultOnNull, VecSkipError, serde_as, skip_serializing_none};
14
15#[cfg(feature = "unstable_auth_status")]
16use super::AuthStatusUpdateNotification;
17#[cfg(feature = "unstable_session_cursors")]
18use super::ToolCallId;
19#[cfg(feature = "unstable_end_turn_token_usage")]
20use super::Usage;
21use super::{
22 CompleteElicitationNotification, CreateElicitationRequest, CreateElicitationResponse,
23 ElicitationCapabilities,
24};
25use crate::{IntoMaybeUndefined, IntoOption, MaybeUndefined};
26
27use super::{
28 ContentBlock, EnvVariable, Error, ExtNotification, ExtRequest, ExtResponse, Meta, Plan,
29 PlanCapabilities, PlanRemoved, PlanUpdate, SessionConfigOption, SessionId, SessionModeId,
30 ToolCall, ToolCallUpdate,
31};
32
33#[cfg(feature = "unstable_mcp_over_acp")]
34use super::mcp::{MCP_MESSAGE_METHOD_NAME, MessageMcpRequest, MessageMcpResponse};
35
36#[serde_as]
44#[skip_serializing_none]
45#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
46#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
47#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = SESSION_UPDATE_NOTIFICATION)))]
48#[serde(rename_all = "camelCase")]
49#[non_exhaustive]
50pub struct SessionNotification {
51 pub session_id: SessionId,
53 pub update: SessionUpdate,
55 #[serde_as(deserialize_as = "DefaultOnError")]
61 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
62 #[serde(default)]
63 #[serde(rename = "_meta")]
64 pub meta: Option<Meta>,
65}
66
67impl SessionNotification {
68 #[must_use]
70 pub fn new(session_id: impl Into<SessionId>, update: SessionUpdate) -> Self {
71 Self {
72 session_id: session_id.into(),
73 update,
74 meta: None,
75 }
76 }
77
78 #[must_use]
84 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
85 self.meta = meta.into_option();
86 self
87 }
88}
89
90#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
96#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
97#[serde(tag = "sessionUpdate", rename_all = "snake_case")]
98#[cfg_attr(feature = "schemars", schemars(extend("discriminator" = {"propertyName": "sessionUpdate"})))]
99#[non_exhaustive]
100pub enum SessionUpdate {
101 UserMessageChunk(ContentChunk),
103 AgentMessageChunk(ContentChunk),
105 AgentThoughtChunk(ContentChunk),
107 ToolCall(ToolCall),
109 ToolCallUpdate(ToolCallUpdate),
111 Plan(Plan),
114 PlanUpdate(PlanUpdate),
117 PlanRemoved(PlanRemoved),
120 AvailableCommandsUpdate(AvailableCommandsUpdate),
122 CurrentModeUpdate(CurrentModeUpdate),
126 ConfigOptionUpdate(ConfigOptionUpdate),
128 SessionInfoUpdate(SessionInfoUpdate),
130 UsageUpdate(UsageUpdate),
132 Notice(Notice),
137 CompactionUpdate(CompactionUpdate),
142 CompactionSummaryChunk(CompactionSummaryChunk),
147 #[cfg(feature = "unstable_prompt_suggestions")]
156 PromptSuggestionsUpdate(PromptSuggestionsUpdate),
157 #[cfg(feature = "unstable_session_cursors")]
166 CursorUpdate(CursorUpdate),
167 SubagentUpdate(SubagentUpdate),
175 SessionMessage(SessionMessage),
183 SessionMessageChunk(SessionMessageChunk),
190}
191
192#[serde_as]
197#[skip_serializing_none]
198#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
199#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
200#[serde(rename_all = "camelCase")]
201#[non_exhaustive]
202pub struct SessionMessageChunk {
203 pub message_id: MessageId,
205 pub content: ContentBlock,
207 #[serde_as(deserialize_as = "DefaultOnError")]
211 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
212 #[serde(default, rename = "_meta")]
213 pub meta: Option<Meta>,
214}
215
216impl SessionMessageChunk {
217 #[must_use]
219 pub fn new(message_id: impl Into<MessageId>, content: ContentBlock) -> Self {
220 Self {
221 message_id: message_id.into(),
222 content,
223 meta: None,
224 }
225 }
226
227 #[must_use]
229 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
230 self.meta = meta.into_option();
231 self
232 }
233}
234
235#[serde_as]
237#[skip_serializing_none]
238#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
239#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
240#[serde(rename_all = "camelCase")]
241#[non_exhaustive]
242pub struct SessionMessage {
243 pub message_id: MessageId,
245 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
249 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
250 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
251 pub sender_session_id: MaybeUndefined<SessionId>,
252 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
256 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
257 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
258 pub recipient_session_id: MaybeUndefined<SessionId>,
259 #[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_message_id: MaybeUndefined<MessageId>,
268 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
274 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
275 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
276 pub recipient_message_id: MaybeUndefined<MessageId>,
277 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<VecSkipError<_>>>")]
280 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
281 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
282 pub content: MaybeUndefined<Vec<ContentBlock>>,
283 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
287 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
288 #[serde(
289 default,
290 rename = "_meta",
291 skip_serializing_if = "MaybeUndefined::is_undefined"
292 )]
293 pub meta: MaybeUndefined<Meta>,
294}
295
296impl SessionMessage {
297 #[must_use]
299 pub fn new(message_id: impl Into<MessageId>) -> Self {
300 Self {
301 message_id: message_id.into(),
302 sender_session_id: MaybeUndefined::Undefined,
303 recipient_session_id: MaybeUndefined::Undefined,
304 sender_message_id: MaybeUndefined::Undefined,
305 recipient_message_id: MaybeUndefined::Undefined,
306 content: MaybeUndefined::Undefined,
307 meta: MaybeUndefined::Undefined,
308 }
309 }
310
311 #[must_use]
313 pub fn sender_session_id(
314 mut self,
315 sender_session_id: impl IntoMaybeUndefined<SessionId>,
316 ) -> Self {
317 self.sender_session_id = sender_session_id.into_maybe_undefined();
318 self
319 }
320
321 #[must_use]
323 pub fn recipient_session_id(
324 mut self,
325 recipient_session_id: impl IntoMaybeUndefined<SessionId>,
326 ) -> Self {
327 self.recipient_session_id = recipient_session_id.into_maybe_undefined();
328 self
329 }
330
331 #[must_use]
333 pub fn sender_message_id(
334 mut self,
335 sender_message_id: impl IntoMaybeUndefined<MessageId>,
336 ) -> Self {
337 self.sender_message_id = sender_message_id.into_maybe_undefined();
338 self
339 }
340
341 #[must_use]
343 pub fn recipient_message_id(
344 mut self,
345 recipient_message_id: impl IntoMaybeUndefined<MessageId>,
346 ) -> Self {
347 self.recipient_message_id = recipient_message_id.into_maybe_undefined();
348 self
349 }
350
351 #[must_use]
353 pub fn content(mut self, content: impl IntoMaybeUndefined<Vec<ContentBlock>>) -> Self {
354 self.content = content.into_maybe_undefined();
355 self
356 }
357
358 #[must_use]
360 pub fn meta(mut self, meta: impl IntoMaybeUndefined<Meta>) -> Self {
361 self.meta = meta.into_maybe_undefined();
362 self
363 }
364}
365
366#[cfg(test)]
367mod session_message_tests {
368 use super::*;
369 use serde_json::{Value, json};
370
371 #[test]
372 fn envelopes_preserve_participants_and_multimodal_content() {
373 let content = json!([
374 {"type": "text", "text": "Please inspect this"},
375 {"type": "image", "data": "aGVsbG8=", "mimeType": "image/png"}
376 ]);
377 for (transcript, sender, recipient, id) in [
378 ("parent", "parent", "child", "sent-1"),
379 ("child", "parent", "child", "received-9"),
380 ("child", "child", "parent", "sent-2"),
381 ] {
382 let wire = json!({"sessionId": transcript, "update": {
383 "sessionUpdate": "session_message", "messageId": id,
384 "senderSessionId": sender, "recipientSessionId": recipient, "content": content
385 }});
386 let decoded: SessionNotification = serde_json::from_value(wire.clone()).unwrap();
387 assert_eq!(serde_json::to_value(&decoded).unwrap(), wire);
388 assert!(matches!(decoded.update, SessionUpdate::SessionMessage(_)));
389 let message = SessionMessage::new(id)
390 .sender_session_id(SessionId::new(sender))
391 .recipient_session_id(SessionId::new(recipient))
392 .content(vec![]);
393 assert_eq!(serde_json::to_value(message).unwrap()["content"], json!([]));
394 }
395 }
396
397 #[test]
398 fn message_upserts_validate_ids_and_patch_fields() {
399 let base = json!({"sessionUpdate": "session_message", "messageId": "m1",
400 "senderSessionId": "parent", "recipientSessionId": "child", "content": []});
401 {
402 let key = "messageId";
403 let mut missing = base.clone();
404 missing.as_object_mut().unwrap().remove(key);
405 assert!(
406 serde_json::from_value::<SessionUpdate>(missing).is_err(),
407 "{key}"
408 );
409 let mut null = base.clone();
410 null[key] = Value::Null;
411 assert!(
412 serde_json::from_value::<SessionUpdate>(null).is_err(),
413 "{key}"
414 );
415 let mut non_string = base.clone();
416 non_string[key] = json!(42);
417 assert!(
418 serde_json::from_value::<SessionUpdate>(non_string).is_err(),
419 "{key}"
420 );
421 }
422 for content in [None, Some(json!({}))] {
423 let mut wire = base.clone();
424 wire.as_object_mut().unwrap().remove("content");
425 if let Some(content) = content {
426 wire["content"] = content;
427 }
428 let decoded: SessionUpdate = serde_json::from_value(wire).unwrap();
429 let encoded = serde_json::to_value(decoded).unwrap();
430 let mut unchanged = base.clone();
431 unchanged.as_object_mut().unwrap().remove("content");
432 assert_eq!(encoded, unchanged);
433 }
434 let clear = SessionMessage::new("m1")
435 .sender_session_id(SessionId::new("parent"))
436 .recipient_session_id(SessionId::new("child"))
437 .content(None)
438 .meta(None);
439 let mut clear_wire = base.clone();
440 clear_wire["content"] = Value::Null;
441 clear_wire["_meta"] = Value::Null;
442 assert_eq!(
443 serde_json::to_value(&clear).unwrap()["content"],
444 Value::Null
445 );
446 let clear_update: SessionUpdate = serde_json::from_value(clear_wire.clone()).unwrap();
447 assert_eq!(serde_json::to_value(clear_update).unwrap(), clear_wire);
448 assert!(clear.content.is_null());
449 assert!(clear.meta.is_null());
450 for meta in [None, Some(Value::Null), Some(json!({"tag": "value"}))] {
451 let mut wire = base.clone();
452 if let Some(meta) = meta {
453 wire["_meta"] = meta;
454 }
455 let decoded: SessionUpdate = serde_json::from_value(wire.clone()).unwrap();
456 let encoded = serde_json::to_value(decoded).unwrap();
457 assert_eq!(encoded, wire);
458 }
459 let metadata_only = json!({"sessionUpdate": "session_message",
460 "messageId": "m1", "senderSessionId": "parent",
461 "recipientSessionId": "child", "_meta": {"tag": "value"}});
462 let decoded: SessionUpdate = serde_json::from_value(metadata_only.clone()).unwrap();
463 assert_eq!(serde_json::to_value(decoded).unwrap(), metadata_only);
464 let unset = SessionMessage::new("m1");
465 assert_eq!(
466 serde_json::to_value(&unset).unwrap(),
467 json!({"messageId": "m1"})
468 );
469 assert!(unset.content.is_undefined());
470 assert!(unset.meta.is_undefined());
471 let reset = SessionMessage::new("m1").content(vec![]);
472 assert_eq!(serde_json::to_value(reset).unwrap()["content"], json!([]));
473 let malformed: SessionMessage = serde_json::from_value(json!({
474 "messageId": "m1", "senderSessionId": "parent", "recipientSessionId": "child",
475 "content": false, "_meta": false
476 }))
477 .unwrap();
478 assert!(malformed.content.is_undefined());
479 assert!(malformed.meta.is_undefined());
480 }
481
482 #[test]
483 fn first_chunk_and_upsert_share_transcript_local_identity() {
484 for (transcript, id) in [("parent", "sent-1"), ("child", "received-9")] {
485 let wire = json!({"sessionId": transcript, "update": {
486 "sessionUpdate": "session_message_chunk", "messageId": id,
487 "content": {"type": "text", "text": "first"}
488 }});
489 let decoded: SessionNotification = serde_json::from_value(wire.clone()).unwrap();
490 assert_eq!(serde_json::to_value(decoded).unwrap(), wire);
491 let upsert = SessionMessage::new(id)
492 .sender_session_id(SessionId::new("parent"))
493 .recipient_session_id(SessionId::new("child"));
494 let chunk = SessionMessageChunk::new(
495 id,
496 ContentBlock::Text(crate::v1::TextContent::new("first")),
497 );
498 assert_eq!(chunk.message_id, upsert.message_id);
499 assert_eq!(
500 serde_json::to_value(SessionUpdate::SessionMessageChunk(chunk)).unwrap(),
501 wire["update"]
502 );
503 }
504 let wire = json!({"sessionId": "child", "update": {
505 "sessionUpdate": "session_message_chunk", "messageId": "received-9",
506 "content": {"type": "text", "text": "first"}
507 }});
508 let base = wire["update"].clone();
509 for key in ["messageId", "content"] {
510 let mut missing = base.clone();
511 missing.as_object_mut().unwrap().remove(key);
512 assert!(
513 serde_json::from_value::<SessionUpdate>(missing).is_err(),
514 "{key}"
515 );
516 let mut null = base.clone();
517 null[key] = Value::Null;
518 assert!(
519 serde_json::from_value::<SessionUpdate>(null).is_err(),
520 "{key}"
521 );
522 let mut non_string = base.clone();
523 non_string[key] = json!(42);
524 assert!(
525 serde_json::from_value::<SessionUpdate>(non_string).is_err(),
526 "{key}"
527 );
528 }
529 for meta in [None, Some(Value::Null), Some(json!({"chunk": true}))] {
530 let mut value = base.clone();
531 if let Some(meta) = meta {
532 value["_meta"] = meta;
533 }
534 let decoded: SessionUpdate = serde_json::from_value(value.clone()).unwrap();
535 let encoded = serde_json::to_value(decoded).unwrap();
536 if value["_meta"].is_null() {
537 assert_eq!(encoded, base);
538 } else {
539 assert_eq!(encoded, value);
540 }
541 }
542 let with_identity = json!({"sessionUpdate": "session_message_chunk", "messageId": "m1",
544 "senderSessionId": "parent", "recipientSessionId": "child",
545 "senderMessageId": "sent-1", "recipientMessageId": "received-1",
546 "content": {"type": "text", "text": "hello"}});
547 let decoded: SessionUpdate = serde_json::from_value(with_identity).unwrap();
548 assert_eq!(
549 serde_json::to_value(decoded).unwrap(),
550 json!({"sessionUpdate": "session_message_chunk", "messageId": "m1",
551 "content": {"type": "text", "text": "hello"}})
552 );
553 }
554
555 #[cfg(feature = "schemars")]
556 #[test]
557 fn schema_requires_ids_and_chunk_content() {
558 let schema = serde_json::to_value(schemars::schema_for!(SessionMessage)).unwrap();
559 let required = schema["required"].as_array().unwrap();
560 assert_eq!(required, &vec![json!("messageId")]);
561 let chunk = serde_json::to_value(schemars::schema_for!(SessionMessageChunk)).unwrap();
562 let required = chunk["required"].as_array().unwrap();
563 assert_eq!(required.len(), 2);
564 assert!(required.contains(&json!("messageId")));
565 assert!(required.contains(&json!("content")));
566 }
567
568 #[test]
569 fn endpoints_can_arrive_late_or_be_omitted_from_later_events() {
570 let block = ContentBlock::Text(crate::v1::TextContent::new("hello"));
571 let minimal = SessionMessage::new("m1");
572 let first = SessionMessageChunk::new("m1", block.clone());
573 assert_eq!(
574 serde_json::to_value(&minimal).unwrap(),
575 json!({"messageId": "m1"})
576 );
577 assert_eq!(
578 serde_json::to_value(&first).unwrap(),
579 json!({"messageId": "m1", "content": {"type": "text", "text": "hello"}})
580 );
581 let enriched = SessionMessage::new("m1")
582 .sender_session_id(SessionId::new("parent"))
583 .recipient_session_id(SessionId::new("child"));
584 assert_eq!(
585 enriched.sender_session_id,
586 MaybeUndefined::Value(SessionId::new("parent"))
587 );
588 assert_eq!(
589 enriched.recipient_session_id,
590 MaybeUndefined::Value(SessionId::new("child"))
591 );
592 let later = SessionMessage::new("m1").sender_session_id(SessionId::new("parent"));
593 assert_eq!(
594 later.sender_session_id,
595 MaybeUndefined::Value(SessionId::new("parent"))
596 );
597 assert_eq!(later.recipient_session_id, MaybeUndefined::Undefined);
598 let more = SessionMessageChunk::new("m1", block);
599 for update in [
600 SessionUpdate::SessionMessage(minimal),
601 SessionUpdate::SessionMessageChunk(first),
602 SessionUpdate::SessionMessage(enriched),
603 SessionUpdate::SessionMessage(later),
604 SessionUpdate::SessionMessageChunk(more),
605 ] {
606 let wire = serde_json::to_value(&update).unwrap();
607 let decoded: SessionUpdate = serde_json::from_value(wire.clone()).unwrap();
608 assert_eq!(serde_json::to_value(decoded).unwrap(), wire);
609 }
610 }
611
612 #[test]
613 fn null_endpoints_clear_invalid_are_absent_but_message_id_is_required() {
614 let mut base = json!({"sessionUpdate": "session_message", "messageId": "m1",
615 "senderSessionId": null, "recipientSessionId": 42});
616 let decoded: SessionUpdate = serde_json::from_value(base.clone()).unwrap();
617 let encoded = serde_json::to_value(decoded).unwrap();
618 base.as_object_mut().unwrap().remove("recipientSessionId");
619 assert_eq!(encoded, base);
620 for bad in [Value::Null, json!(42)] {
621 let mut invalid = base.clone();
622 invalid["messageId"] = bad;
623 assert!(serde_json::from_value::<SessionUpdate>(invalid).is_err());
624 }
625 }
626
627 #[test]
628 fn message_references_link_views_and_can_arrive_late() {
629 let block = ContentBlock::Text(crate::v1::TextContent::new("hello"));
630 let incoming = SessionMessage::new("received-1")
631 .sender_session_id(SessionId::new("parent"))
632 .recipient_session_id(SessionId::new("child"))
633 .sender_message_id(MessageId::new("sent-1"))
634 .content(vec![block]);
635 let outgoing =
637 SessionMessage::new("sent-1").recipient_message_id(MessageId::new("received-1"));
638 for (update, wire) in [
639 (
640 SessionUpdate::SessionMessage(incoming),
641 json!({"sessionUpdate": "session_message", "messageId": "received-1",
642 "senderSessionId": "parent", "recipientSessionId": "child",
643 "senderMessageId": "sent-1", "content": [{"type": "text", "text": "hello"}]}),
644 ),
645 (
646 SessionUpdate::SessionMessage(outgoing),
647 json!({"sessionUpdate": "session_message", "messageId": "sent-1",
648 "recipientMessageId": "received-1"}),
649 ),
650 ] {
651 assert_eq!(serde_json::to_value(&update).unwrap(), wire);
652 let decoded: SessionUpdate = serde_json::from_value(wire.clone()).unwrap();
653 assert_eq!(decoded, update);
654 }
655
656 let mut wire = json!({"sessionUpdate": "session_message", "messageId": "m1",
657 "senderMessageId": null, "recipientMessageId": 42});
658 let decoded: SessionUpdate = serde_json::from_value(wire.clone()).unwrap();
659 wire.as_object_mut().unwrap().remove("recipientMessageId");
660 assert_eq!(
661 serde_json::to_value(decoded).unwrap(),
662 wire,
663 "null clears a reference and a malformed one is not supplied"
664 );
665 }
666}
667
668#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
670#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
671#[serde(rename_all = "snake_case")]
672#[non_exhaustive]
673pub enum NoticeSeverity {
674 Info,
676 Warning,
678 Error,
680 #[serde(untagged)]
685 Other(String),
686}
687
688#[serde_as]
698#[skip_serializing_none]
699#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
700#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
701#[serde(rename_all = "camelCase")]
702#[non_exhaustive]
703pub struct Notice {
704 pub severity: NoticeSeverity,
706 #[cfg_attr(feature = "schemars", schemars(length(min = 1)))]
708 pub title: String,
709 #[serde_as(deserialize_as = "DefaultOnError")]
713 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
714 #[serde(default)]
715 pub description: Option<String>,
716 #[serde_as(deserialize_as = "DefaultOnError")]
720 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
721 #[serde(default, rename = "_meta")]
722 pub meta: Option<Meta>,
723}
724
725impl Notice {
726 #[must_use]
728 pub fn new(severity: NoticeSeverity, title: impl Into<String>) -> Self {
729 Self {
730 severity,
731 title: title.into(),
732 description: None,
733 meta: None,
734 }
735 }
736
737 #[must_use]
739 pub fn description(mut self, description: impl IntoOption<String>) -> Self {
740 self.description = description.into_option();
741 self
742 }
743
744 #[must_use]
746 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
747 self.meta = meta.into_option();
748 self
749 }
750}
751
752#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
754#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
755#[serde(transparent)]
756#[from(Arc<str>, String, &'static str)]
757#[non_exhaustive]
758pub struct CompactionId(pub Arc<str>);
759
760impl CompactionId {
761 #[must_use]
763 pub fn new(id: impl Into<Arc<str>>) -> Self {
764 Self(id.into())
765 }
766}
767
768#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
770#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
771#[serde(rename_all = "snake_case")]
772#[non_exhaustive]
773pub enum CompactionStatus {
774 #[default]
776 InProgress,
777 Completed,
779 Failed,
781 Cancelled,
783 #[serde(untagged)]
788 Other(String),
789}
790
791#[serde_as]
800#[skip_serializing_none]
801#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
802#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
803#[serde(rename_all = "camelCase")]
804#[non_exhaustive]
805pub struct CompactionUpdate {
806 pub compaction_id: CompactionId,
808 pub status: CompactionStatus,
810 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<VecSkipError<_>>>")]
812 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
813 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
814 pub summary: MaybeUndefined<Vec<ContentBlock>>,
815 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
817 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
818 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
819 pub error: MaybeUndefined<String>,
820 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
822 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
823 #[serde(
824 rename = "_meta",
825 default,
826 skip_serializing_if = "MaybeUndefined::is_undefined"
827 )]
828 pub meta: MaybeUndefined<Meta>,
829}
830
831impl CompactionUpdate {
832 #[must_use]
834 pub fn new(compaction_id: impl Into<CompactionId>, status: CompactionStatus) -> Self {
835 Self {
836 compaction_id: compaction_id.into(),
837 status,
838 summary: MaybeUndefined::Undefined,
839 error: MaybeUndefined::Undefined,
840 meta: MaybeUndefined::Undefined,
841 }
842 }
843
844 #[must_use]
846 pub fn summary(mut self, summary: impl IntoMaybeUndefined<Vec<ContentBlock>>) -> Self {
847 self.summary = summary.into_maybe_undefined();
848 self
849 }
850
851 #[must_use]
853 pub fn error(mut self, error: impl IntoMaybeUndefined<String>) -> Self {
854 self.error = error.into_maybe_undefined();
855 self
856 }
857
858 #[must_use]
860 pub fn meta(mut self, meta: impl IntoMaybeUndefined<Meta>) -> Self {
861 self.meta = meta.into_maybe_undefined();
862 self
863 }
864}
865
866#[serde_as]
871#[skip_serializing_none]
872#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
873#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
874#[serde(rename_all = "camelCase")]
875#[non_exhaustive]
876pub struct CompactionSummaryChunk {
877 pub compaction_id: CompactionId,
879 pub content: ContentBlock,
881 #[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")]
953#[serde_as]
954#[skip_serializing_none]
955#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
956#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
957#[serde(rename_all = "camelCase")]
958#[non_exhaustive]
959pub struct CursorUpdate {
960 pub cursor_id: CursorId,
962 #[serde_as(deserialize_as = "DefaultOnError")]
967 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
968 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
969 pub capabilities: MaybeUndefined<CursorCapabilities>,
970 #[serde(default)]
976 pub anchor: Option<CursorAnchor>,
977 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
979 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
980 #[serde(
981 rename = "_meta",
982 default,
983 skip_serializing_if = "MaybeUndefined::is_undefined"
984 )]
985 pub meta: MaybeUndefined<Meta>,
986}
987
988#[cfg(feature = "unstable_session_cursors")]
989impl CursorUpdate {
990 #[must_use]
992 pub fn new(cursor_id: impl Into<CursorId>) -> Self {
993 Self {
994 cursor_id: cursor_id.into(),
995 capabilities: MaybeUndefined::Undefined,
996 anchor: None,
997 meta: MaybeUndefined::Undefined,
998 }
999 }
1000
1001 #[must_use]
1003 pub fn capabilities(
1004 mut self,
1005 capabilities: impl IntoMaybeUndefined<CursorCapabilities>,
1006 ) -> Self {
1007 self.capabilities = capabilities.into_maybe_undefined();
1008 self
1009 }
1010
1011 #[must_use]
1013 pub fn anchor(mut self, anchor: impl IntoOption<CursorAnchor>) -> Self {
1014 self.anchor = anchor.into_option();
1015 self
1016 }
1017
1018 #[must_use]
1020 pub fn meta(mut self, meta: impl IntoMaybeUndefined<Meta>) -> Self {
1021 self.meta = meta.into_maybe_undefined();
1022 self
1023 }
1024}
1025
1026#[cfg(feature = "unstable_session_cursors")]
1034#[serde_as]
1035#[skip_serializing_none]
1036#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1037#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1038#[serde(rename_all = "camelCase")]
1039#[non_exhaustive]
1040pub struct CursorCapabilities {
1041 #[cfg(feature = "unstable_session_fork")]
1046 #[serde_as(deserialize_as = "DefaultOnError")]
1047 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1048 #[serde(default)]
1049 pub fork: Option<CursorForkCapabilities>,
1050 #[serde_as(deserialize_as = "DefaultOnError")]
1056 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1057 #[serde(default)]
1058 #[serde(rename = "_meta")]
1059 pub meta: Option<Meta>,
1060}
1061
1062#[cfg(feature = "unstable_session_cursors")]
1063impl CursorCapabilities {
1064 #[must_use]
1066 pub fn new() -> Self {
1067 Self::default()
1068 }
1069
1070 #[cfg(feature = "unstable_session_fork")]
1072 #[must_use]
1073 pub fn fork(mut self, fork: impl IntoOption<CursorForkCapabilities>) -> Self {
1074 self.fork = fork.into_option();
1075 self
1076 }
1077
1078 #[must_use]
1084 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1085 self.meta = meta.into_option();
1086 self
1087 }
1088}
1089
1090#[cfg(all(
1098 feature = "unstable_session_cursors",
1099 feature = "unstable_session_fork"
1100))]
1101#[serde_as]
1102#[skip_serializing_none]
1103#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1104#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1105#[non_exhaustive]
1106pub struct CursorForkCapabilities {
1107 #[serde_as(deserialize_as = "DefaultOnError")]
1113 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1114 #[serde(default)]
1115 #[serde(rename = "_meta")]
1116 pub meta: Option<Meta>,
1117}
1118
1119#[cfg(all(
1120 feature = "unstable_session_cursors",
1121 feature = "unstable_session_fork"
1122))]
1123impl CursorForkCapabilities {
1124 #[must_use]
1126 pub fn new() -> Self {
1127 Self::default()
1128 }
1129
1130 #[must_use]
1136 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1137 self.meta = meta.into_option();
1138 self
1139 }
1140}
1141
1142#[cfg(feature = "unstable_session_cursors")]
1154#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1155#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1156#[serde(tag = "type", rename_all = "snake_case")]
1157#[non_exhaustive]
1158pub enum CursorAnchor {
1159 UserMessage(CursorMessageAnchor),
1161 AgentMessage(CursorMessageAnchor),
1163 AgentThought(CursorMessageAnchor),
1165 SessionMessage(CursorMessageAnchor),
1167 ToolCall(CursorToolCallAnchor),
1169 Compaction(CursorCompactionAnchor),
1171 #[serde(untagged)]
1180 Other(OtherCursorAnchor),
1181}
1182
1183#[cfg(feature = "unstable_session_cursors")]
1189#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1190#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1191#[serde(rename_all = "snake_case")]
1192#[non_exhaustive]
1193pub enum CursorAnchorPosition {
1194 Before,
1197 After,
1200 #[serde(untagged)]
1206 Other(String),
1207}
1208
1209#[cfg(feature = "unstable_session_cursors")]
1215#[serde_as]
1216#[skip_serializing_none]
1217#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1218#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1219#[serde(rename_all = "camelCase")]
1220#[non_exhaustive]
1221pub struct CursorMessageAnchor {
1222 pub message_id: MessageId,
1224 pub position: CursorAnchorPosition,
1226 #[serde_as(deserialize_as = "DefaultOnError")]
1232 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1233 #[serde(default)]
1234 #[serde(rename = "_meta")]
1235 pub meta: Option<Meta>,
1236}
1237
1238#[cfg(feature = "unstable_session_cursors")]
1239impl CursorMessageAnchor {
1240 #[must_use]
1242 pub fn new(message_id: impl Into<MessageId>, position: CursorAnchorPosition) -> Self {
1243 Self {
1244 message_id: message_id.into(),
1245 position,
1246 meta: None,
1247 }
1248 }
1249
1250 #[must_use]
1256 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1257 self.meta = meta.into_option();
1258 self
1259 }
1260}
1261
1262#[cfg(feature = "unstable_session_cursors")]
1268#[serde_as]
1269#[skip_serializing_none]
1270#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1271#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1272#[serde(rename_all = "camelCase")]
1273#[non_exhaustive]
1274pub struct CursorToolCallAnchor {
1275 pub tool_call_id: ToolCallId,
1277 pub position: CursorAnchorPosition,
1279 #[serde_as(deserialize_as = "DefaultOnError")]
1285 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1286 #[serde(default)]
1287 #[serde(rename = "_meta")]
1288 pub meta: Option<Meta>,
1289}
1290
1291#[cfg(feature = "unstable_session_cursors")]
1292impl CursorToolCallAnchor {
1293 #[must_use]
1295 pub fn new(tool_call_id: impl Into<ToolCallId>, position: CursorAnchorPosition) -> Self {
1296 Self {
1297 tool_call_id: tool_call_id.into(),
1298 position,
1299 meta: None,
1300 }
1301 }
1302
1303 #[must_use]
1309 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1310 self.meta = meta.into_option();
1311 self
1312 }
1313}
1314
1315#[cfg(feature = "unstable_session_cursors")]
1321#[serde_as]
1322#[skip_serializing_none]
1323#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1324#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1325#[serde(rename_all = "camelCase")]
1326#[non_exhaustive]
1327pub struct CursorCompactionAnchor {
1328 pub compaction_id: CompactionId,
1330 pub position: CursorAnchorPosition,
1332 #[serde_as(deserialize_as = "DefaultOnError")]
1338 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1339 #[serde(default)]
1340 #[serde(rename = "_meta")]
1341 pub meta: Option<Meta>,
1342}
1343
1344#[cfg(feature = "unstable_session_cursors")]
1345impl CursorCompactionAnchor {
1346 #[must_use]
1348 pub fn new(compaction_id: impl Into<CompactionId>, position: CursorAnchorPosition) -> Self {
1349 Self {
1350 compaction_id: compaction_id.into(),
1351 position,
1352 meta: None,
1353 }
1354 }
1355
1356 #[must_use]
1362 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1363 self.meta = meta.into_option();
1364 self
1365 }
1366}
1367
1368#[cfg(feature = "unstable_session_cursors")]
1377#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1378#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
1379#[cfg_attr(feature = "schemars", schemars(inline))]
1380#[cfg_attr(feature = "schemars", schemars(transform = other_cursor_anchor_schema))]
1381#[serde(rename_all = "camelCase")]
1382#[non_exhaustive]
1383pub struct OtherCursorAnchor {
1384 #[serde(rename = "type")]
1390 pub type_: String,
1391 #[serde(flatten)]
1394 pub fields: IndexMap<String, serde_json::Value>,
1395}
1396
1397#[cfg(feature = "unstable_session_cursors")]
1398impl OtherCursorAnchor {
1399 #[must_use]
1401 pub fn new(type_: impl Into<String>, mut fields: IndexMap<String, serde_json::Value>) -> Self {
1402 fields.shift_remove("type");
1403 Self {
1404 type_: type_.into(),
1405 fields,
1406 }
1407 }
1408}
1409
1410#[cfg(feature = "unstable_session_cursors")]
1411impl<'de> Deserialize<'de> for OtherCursorAnchor {
1412 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1413 where
1414 D: serde::Deserializer<'de>,
1415 {
1416 let mut fields = IndexMap::<String, serde_json::Value>::deserialize(deserializer)?;
1417 let type_ = fields
1418 .shift_remove("type")
1419 .ok_or_else(|| serde::de::Error::missing_field("type"))?;
1420 let serde_json::Value::String(type_) = type_ else {
1421 return Err(serde::de::Error::custom("`type` must be a string"));
1422 };
1423
1424 if KNOWN_CURSOR_ANCHOR_TYPES.contains(&type_.as_str()) {
1425 return Err(serde::de::Error::custom(format!(
1426 "known cursor anchor `{type_}` did not match its schema"
1427 )));
1428 }
1429
1430 Ok(Self { type_, fields })
1431 }
1432}
1433
1434#[cfg(feature = "unstable_session_cursors")]
1435const KNOWN_CURSOR_ANCHOR_TYPES: &[&str] = &[
1436 "user_message",
1437 "agent_message",
1438 "agent_thought",
1439 "session_message",
1440 "tool_call",
1441 "compaction",
1442];
1443
1444#[cfg(all(feature = "unstable_session_cursors", feature = "schemars"))]
1445fn other_cursor_anchor_schema(schema: &mut Schema) {
1446 let known = KNOWN_CURSOR_ANCHOR_TYPES
1447 .iter()
1448 .map(|type_| {
1449 serde_json::json!({
1450 "properties": { "type": { "const": type_, "type": "string" } },
1451 "required": ["type"],
1452 "type": "object"
1453 })
1454 })
1455 .collect::<Vec<_>>();
1456 schema.insert("not".into(), serde_json::json!({ "anyOf": known }));
1457}
1458
1459#[serde_as]
1481#[skip_serializing_none]
1482#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1483#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1484#[serde(rename_all = "camelCase")]
1485#[non_exhaustive]
1486pub struct SubagentUpdate {
1487 pub session_id: SessionId,
1489 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
1494 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1495 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
1496 pub title: MaybeUndefined<String>,
1497 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
1503 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1504 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
1505 pub description: MaybeUndefined<String>,
1506 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
1513 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1514 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
1515 pub capabilities: MaybeUndefined<SubagentSessionCapabilities>,
1516 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
1523 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1524 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
1525 pub state: MaybeUndefined<StateUpdate>,
1526 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
1533 pub cwd: MaybeUndefined<PathBuf>,
1534 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
1542 pub additional_directories: MaybeUndefined<Vec<PathBuf>>,
1543 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
1550 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1551 #[serde(
1552 default,
1553 rename = "_meta",
1554 skip_serializing_if = "MaybeUndefined::is_undefined"
1555 )]
1556 pub meta: MaybeUndefined<Meta>,
1557}
1558
1559impl SubagentUpdate {
1560 #[must_use]
1562 pub fn new(session_id: impl Into<SessionId>) -> Self {
1563 Self {
1564 session_id: session_id.into(),
1565 title: MaybeUndefined::Undefined,
1566 description: MaybeUndefined::Undefined,
1567 capabilities: MaybeUndefined::Undefined,
1568 state: MaybeUndefined::Undefined,
1569 cwd: MaybeUndefined::Undefined,
1570 additional_directories: MaybeUndefined::Undefined,
1571 meta: MaybeUndefined::Undefined,
1572 }
1573 }
1574
1575 #[must_use]
1577 pub fn title(mut self, title: impl IntoMaybeUndefined<String>) -> Self {
1578 self.title = title.into_maybe_undefined();
1579 self
1580 }
1581
1582 #[must_use]
1584 pub fn description(mut self, description: impl IntoMaybeUndefined<String>) -> Self {
1585 self.description = description.into_maybe_undefined();
1586 self
1587 }
1588
1589 #[must_use]
1591 pub fn capabilities(
1592 mut self,
1593 capabilities: impl IntoMaybeUndefined<SubagentSessionCapabilities>,
1594 ) -> Self {
1595 self.capabilities = capabilities.into_maybe_undefined();
1596 self
1597 }
1598
1599 #[must_use]
1601 pub fn state(mut self, state: impl IntoMaybeUndefined<StateUpdate>) -> Self {
1602 self.state = state.into_maybe_undefined();
1603 self
1604 }
1605
1606 #[must_use]
1610 pub fn cwd(mut self, cwd: impl IntoMaybeUndefined<PathBuf>) -> Self {
1611 self.cwd = cwd.into_maybe_undefined();
1612 self
1613 }
1614
1615 #[must_use]
1619 pub fn additional_directories(
1620 mut self,
1621 additional_directories: impl IntoMaybeUndefined<Vec<PathBuf>>,
1622 ) -> Self {
1623 self.additional_directories = additional_directories.into_maybe_undefined();
1624 self
1625 }
1626
1627 #[must_use]
1631 pub fn meta(mut self, meta: impl IntoMaybeUndefined<Meta>) -> Self {
1632 self.meta = meta.into_maybe_undefined();
1633 self
1634 }
1635}
1636
1637#[serde_as]
1642#[skip_serializing_none]
1643#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1644#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1645#[serde(rename_all = "camelCase")]
1646#[non_exhaustive]
1647pub struct SubagentSessionCapabilities {
1648 #[serde_as(deserialize_as = "DefaultOnError")]
1652 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1653 #[serde(default)]
1654 pub cancel: Option<SessionCancelCapabilities>,
1655 #[serde_as(deserialize_as = "DefaultOnError")]
1659 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1660 #[serde(default)]
1661 #[serde(rename = "_meta")]
1662 pub meta: Option<Meta>,
1663}
1664
1665impl SubagentSessionCapabilities {
1666 #[must_use]
1668 pub fn new() -> Self {
1669 Self::default()
1670 }
1671
1672 #[must_use]
1674 pub fn cancel(mut self, cancel: impl IntoOption<SessionCancelCapabilities>) -> Self {
1675 self.cancel = cancel.into_option();
1676 self
1677 }
1678
1679 #[must_use]
1683 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1684 self.meta = meta.into_option();
1685 self
1686 }
1687}
1688
1689#[serde_as]
1693#[skip_serializing_none]
1694#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1695#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1696#[non_exhaustive]
1697pub struct SessionCancelCapabilities {
1698 #[serde_as(deserialize_as = "DefaultOnError")]
1704 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1705 #[serde(default)]
1706 #[serde(rename = "_meta")]
1707 pub meta: Option<Meta>,
1708}
1709
1710impl SessionCancelCapabilities {
1711 #[must_use]
1713 pub fn new() -> Self {
1714 Self::default()
1715 }
1716
1717 #[must_use]
1723 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1724 self.meta = meta.into_option();
1725 self
1726 }
1727}
1728
1729#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1735#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1736#[serde(tag = "state", rename_all = "snake_case")]
1737#[non_exhaustive]
1738pub enum StateUpdate {
1739 Running(RunningStateUpdate),
1741 Idle(IdleStateUpdate),
1743 RequiresAction(RequiresActionStateUpdate),
1745 Unknown(UnknownStateUpdate),
1749 #[serde(untagged)]
1754 Other(OtherStateUpdate),
1755}
1756
1757#[serde_as]
1759#[skip_serializing_none]
1760#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1761#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1762#[serde(rename_all = "camelCase")]
1763#[non_exhaustive]
1764pub struct RunningStateUpdate {
1765 #[serde_as(deserialize_as = "DefaultOnError")]
1769 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1770 #[serde(default, rename = "_meta")]
1771 pub meta: Option<Meta>,
1772}
1773
1774impl RunningStateUpdate {
1775 #[must_use]
1777 pub fn new() -> Self {
1778 Self::default()
1779 }
1780
1781 #[must_use]
1783 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1784 self.meta = meta.into_option();
1785 self
1786 }
1787}
1788
1789#[serde_as]
1793#[skip_serializing_none]
1794#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1795#[cfg_attr(feature = "schemars", schemars(transform = idle_state_update_schema))]
1796#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1797#[serde(rename_all = "camelCase")]
1798#[non_exhaustive]
1799pub struct IdleStateUpdate {
1800 #[serde(flatten)]
1802 pub stop_reason: Option<IdleStopReason>,
1803 #[cfg(feature = "unstable_end_turn_token_usage")]
1807 #[serde_as(deserialize_as = "DefaultOnError")]
1808 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1809 #[serde(default)]
1810 pub usage: Option<Box<Usage>>,
1811 #[serde_as(deserialize_as = "DefaultOnError")]
1815 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1816 #[serde(default, rename = "_meta")]
1817 pub meta: Option<Meta>,
1818}
1819
1820impl IdleStateUpdate {
1821 #[must_use]
1823 pub fn new() -> Self {
1824 Self::default()
1825 }
1826
1827 #[must_use]
1829 pub fn stop_reason(mut self, stop_reason: impl IntoOption<IdleStopReason>) -> Self {
1830 self.stop_reason = stop_reason.into_option();
1831 self
1832 }
1833
1834 #[cfg(feature = "unstable_end_turn_token_usage")]
1836 #[must_use]
1837 pub fn usage(mut self, usage: impl IntoOption<Usage>) -> Self {
1838 self.usage = usage.into_option().map(Box::new);
1839 self
1840 }
1841
1842 #[must_use]
1844 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1845 self.meta = meta.into_option();
1846 self
1847 }
1848}
1849
1850#[cfg(feature = "schemars")]
1859fn idle_state_update_schema(schema: &mut Schema) {
1860 if let Some(properties) = schema
1861 .get_mut("properties")
1862 .and_then(serde_json::Value::as_object_mut)
1863 {
1864 properties.insert(
1865 "stopReason".into(),
1866 serde_json::json!({
1867 "description": "Why foreground work stopped. The value selects one of this type's variants, which may add fields of their own.\n\nOptional. Omitted or `null` both mean the agent is not reporting a stop reason.\n\nSee protocol docs: [Work state](https://agentclientprotocol.com/protocol/v1/subagents#work-state)",
1868 "type": ["string", "null"],
1869 "x-deserialize-default-on-error": true
1870 }),
1871 );
1872 }
1873 let Some(variants) = schema
1874 .get_mut("anyOf")
1875 .and_then(serde_json::Value::as_array_mut)
1876 else {
1877 return;
1878 };
1879 for variant in variants {
1880 if variant.as_object().is_some_and(serde_json::Map::is_empty) {
1881 *variant = serde_json::json!({
1882 "title": "none",
1883 "description": "No stop reason: `stopReason` is omitted or `null`.",
1884 "type": "object",
1885 "properties": {
1886 "stopReason": { "type": "null" }
1887 }
1888 });
1889 }
1890 }
1891}
1892
1893#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1901#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1902#[serde(tag = "stopReason", rename_all = "snake_case")]
1903#[non_exhaustive]
1904pub enum IdleStopReason {
1905 EndTurn,
1907 MaxTokens,
1909 MaxTurnRequests,
1912 Refusal,
1914 Cancelled,
1916 Error(ErrorStopReason),
1918 #[serde(untagged)]
1923 Other(OtherStopReason),
1924}
1925
1926impl From<ErrorStopReason> for IdleStopReason {
1927 fn from(value: ErrorStopReason) -> Self {
1928 Self::Error(value)
1929 }
1930}
1931
1932#[serde_as]
1934#[skip_serializing_none]
1935#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1936#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1937#[serde(rename_all = "camelCase")]
1938#[non_exhaustive]
1939pub struct ErrorStopReason {
1940 #[serde_as(deserialize_as = "DefaultOnError")]
1945 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1946 #[serde(default)]
1947 pub error: Option<Box<Error>>,
1948}
1949
1950impl ErrorStopReason {
1951 #[must_use]
1953 pub fn new() -> Self {
1954 Self::default()
1955 }
1956
1957 #[must_use]
1959 pub fn error(mut self, error: impl IntoOption<Error>) -> Self {
1960 self.error = error.into_option().map(Box::new);
1961 self
1962 }
1963}
1964
1965#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1967#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
1968#[cfg_attr(feature = "schemars", schemars(inline))]
1969#[cfg_attr(feature = "schemars", schemars(transform = other_stop_reason_schema))]
1970#[serde(rename_all = "camelCase")]
1971#[non_exhaustive]
1972pub struct OtherStopReason {
1973 pub stop_reason: String,
1975 #[serde(flatten)]
1977 pub fields: IndexMap<String, serde_json::Value>,
1978}
1979
1980impl OtherStopReason {
1981 #[must_use]
1983 pub fn new(
1984 stop_reason: impl Into<String>,
1985 mut fields: IndexMap<String, serde_json::Value>,
1986 ) -> Self {
1987 remove_idle_state_update_fields(&mut fields);
1988 Self {
1989 stop_reason: stop_reason.into(),
1990 fields,
1991 }
1992 }
1993}
1994
1995impl<'de> Deserialize<'de> for OtherStopReason {
1996 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1997 where
1998 D: serde::Deserializer<'de>,
1999 {
2000 let mut fields = IndexMap::<String, serde_json::Value>::deserialize(deserializer)?;
2001 let stop_reason = fields
2002 .shift_remove("stopReason")
2003 .ok_or_else(|| serde::de::Error::missing_field("stopReason"))?;
2004 let serde_json::Value::String(stop_reason) = stop_reason else {
2005 return Err(serde::de::Error::custom("`stopReason` must be a string"));
2006 };
2007 if KNOWN_STOP_REASONS.contains(&stop_reason.as_str()) {
2008 return Err(serde::de::Error::custom(format!(
2009 "known stop reason `{stop_reason}` did not match its schema"
2010 )));
2011 }
2012 remove_idle_state_update_fields(&mut fields);
2013 Ok(Self {
2014 stop_reason,
2015 fields,
2016 })
2017 }
2018}
2019
2020const KNOWN_STOP_REASONS: &[&str] = &[
2021 "end_turn",
2022 "max_tokens",
2023 "max_turn_requests",
2024 "refusal",
2025 "cancelled",
2026 "error",
2027];
2028
2029fn remove_idle_state_update_fields(fields: &mut IndexMap<String, serde_json::Value>) {
2031 fields.shift_remove("stopReason");
2032 fields.shift_remove("usage");
2033 fields.shift_remove("_meta");
2034}
2035
2036#[cfg(feature = "schemars")]
2037fn other_stop_reason_schema(schema: &mut Schema) {
2038 let known = KNOWN_STOP_REASONS
2039 .iter()
2040 .map(|stop_reason| {
2041 serde_json::json!({
2042 "properties": { "stopReason": { "const": stop_reason, "type": "string" } },
2043 "required": ["stopReason"],
2044 "type": "object"
2045 })
2046 })
2047 .collect::<Vec<_>>();
2048 schema.insert("not".into(), serde_json::json!({ "anyOf": known }));
2049}
2050
2051#[serde_as]
2053#[skip_serializing_none]
2054#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2055#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2056#[serde(rename_all = "camelCase")]
2057#[non_exhaustive]
2058pub struct RequiresActionStateUpdate {
2059 #[serde_as(deserialize_as = "DefaultOnError")]
2063 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2064 #[serde(default, rename = "_meta")]
2065 pub meta: Option<Meta>,
2066}
2067
2068impl RequiresActionStateUpdate {
2069 #[must_use]
2071 pub fn new() -> Self {
2072 Self::default()
2073 }
2074
2075 #[must_use]
2077 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2078 self.meta = meta.into_option();
2079 self
2080 }
2081}
2082
2083#[serde_as]
2096#[skip_serializing_none]
2097#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2098#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2099#[serde(rename_all = "camelCase")]
2100#[non_exhaustive]
2101pub struct UnknownStateUpdate {
2102 #[serde_as(deserialize_as = "DefaultOnError")]
2106 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2107 #[serde(default, rename = "_meta")]
2108 pub meta: Option<Meta>,
2109}
2110
2111impl UnknownStateUpdate {
2112 #[must_use]
2114 pub fn new() -> Self {
2115 Self::default()
2116 }
2117
2118 #[must_use]
2120 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2121 self.meta = meta.into_option();
2122 self
2123 }
2124}
2125
2126#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2128#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
2129#[cfg_attr(feature = "schemars", schemars(inline))]
2130#[cfg_attr(feature = "schemars", schemars(transform = other_state_update_schema))]
2131#[serde(rename_all = "camelCase")]
2132#[non_exhaustive]
2133pub struct OtherStateUpdate {
2134 pub state: String,
2136 #[serde(flatten)]
2138 pub fields: IndexMap<String, serde_json::Value>,
2139}
2140
2141impl OtherStateUpdate {
2142 #[must_use]
2144 pub fn new(state: impl Into<String>, mut fields: IndexMap<String, serde_json::Value>) -> Self {
2145 fields.shift_remove("state");
2146 Self {
2147 state: state.into(),
2148 fields,
2149 }
2150 }
2151}
2152
2153impl<'de> Deserialize<'de> for OtherStateUpdate {
2154 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2155 where
2156 D: serde::Deserializer<'de>,
2157 {
2158 let mut fields = IndexMap::<String, serde_json::Value>::deserialize(deserializer)?;
2159 let state = fields
2160 .shift_remove("state")
2161 .ok_or_else(|| serde::de::Error::missing_field("state"))?;
2162 let serde_json::Value::String(state) = state else {
2163 return Err(serde::de::Error::custom("`state` must be a string"));
2164 };
2165 if is_known_state_update(&state) {
2166 return Err(serde::de::Error::custom(format!(
2167 "known state update `{state}` did not match its schema"
2168 )));
2169 }
2170 Ok(Self { state, fields })
2171 }
2172}
2173
2174const KNOWN_STATE_UPDATE_STATES: &[&str] = &["running", "idle", "requires_action", "unknown"];
2175
2176fn is_known_state_update(state: &str) -> bool {
2177 KNOWN_STATE_UPDATE_STATES.contains(&state)
2178}
2179
2180#[cfg(feature = "schemars")]
2181fn other_state_update_schema(schema: &mut Schema) {
2182 let known = KNOWN_STATE_UPDATE_STATES
2183 .iter()
2184 .map(|state| {
2185 serde_json::json!({
2186 "properties": { "state": { "const": state, "type": "string" } },
2187 "required": ["state"],
2188 "type": "object"
2189 })
2190 })
2191 .collect::<Vec<_>>();
2192 schema.insert("not".into(), serde_json::json!({ "anyOf": known }));
2193}
2194
2195#[serde_as]
2199#[skip_serializing_none]
2200#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2201#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2202#[serde(rename_all = "camelCase")]
2203#[non_exhaustive]
2204pub struct CurrentModeUpdate {
2205 pub current_mode_id: SessionModeId,
2207 #[serde_as(deserialize_as = "DefaultOnError")]
2213 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2214 #[serde(default)]
2215 #[serde(rename = "_meta")]
2216 pub meta: Option<Meta>,
2217}
2218
2219impl CurrentModeUpdate {
2220 #[must_use]
2222 pub fn new(current_mode_id: impl Into<SessionModeId>) -> Self {
2223 Self {
2224 current_mode_id: current_mode_id.into(),
2225 meta: None,
2226 }
2227 }
2228
2229 #[must_use]
2235 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2236 self.meta = meta.into_option();
2237 self
2238 }
2239}
2240
2241#[serde_as]
2243#[skip_serializing_none]
2244#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2245#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2246#[serde(rename_all = "camelCase")]
2247#[non_exhaustive]
2248pub struct ConfigOptionUpdate {
2249 #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
2251 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
2252 pub config_options: Vec<SessionConfigOption>,
2253 #[serde_as(deserialize_as = "DefaultOnError")]
2259 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2260 #[serde(default)]
2261 #[serde(rename = "_meta")]
2262 pub meta: Option<Meta>,
2263}
2264
2265impl ConfigOptionUpdate {
2266 #[must_use]
2268 pub fn new(config_options: Vec<SessionConfigOption>) -> Self {
2269 Self {
2270 config_options,
2271 meta: None,
2272 }
2273 }
2274
2275 #[must_use]
2281 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2282 self.meta = meta.into_option();
2283 self
2284 }
2285}
2286
2287#[serde_as]
2292#[skip_serializing_none]
2293#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2294#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2295#[serde(rename_all = "camelCase")]
2296#[non_exhaustive]
2297pub struct SessionInfoUpdate {
2298 #[serde_as(deserialize_as = "DefaultOnError")]
2300 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2301 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
2302 pub title: MaybeUndefined<String>,
2303 #[serde_as(deserialize_as = "DefaultOnError")]
2305 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2306 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
2307 pub updated_at: MaybeUndefined<String>,
2308 #[serde_as(deserialize_as = "DefaultOnError")]
2314 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2315 #[serde(default)]
2316 #[serde(rename = "_meta")]
2317 pub meta: Option<Meta>,
2318}
2319
2320impl SessionInfoUpdate {
2321 #[must_use]
2323 pub fn new() -> Self {
2324 Self::default()
2325 }
2326
2327 #[must_use]
2329 pub fn title(mut self, title: impl IntoMaybeUndefined<String>) -> Self {
2330 self.title = title.into_maybe_undefined();
2331 self
2332 }
2333
2334 #[must_use]
2336 pub fn updated_at(mut self, updated_at: impl IntoMaybeUndefined<String>) -> Self {
2337 self.updated_at = updated_at.into_maybe_undefined();
2338 self
2339 }
2340
2341 #[must_use]
2347 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2348 self.meta = meta.into_option();
2349 self
2350 }
2351}
2352
2353#[serde_as]
2355#[skip_serializing_none]
2356#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2357#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
2358#[serde(rename_all = "camelCase")]
2359#[non_exhaustive]
2360pub struct UsageUpdate {
2361 pub used: u64,
2363 pub size: u64,
2365 #[serde_as(deserialize_as = "DefaultOnError")]
2367 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2368 #[serde(default)]
2369 pub cost: Option<Cost>,
2370 #[serde_as(deserialize_as = "DefaultOnError")]
2376 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2377 #[serde(default)]
2378 #[serde(rename = "_meta")]
2379 pub meta: Option<Meta>,
2380}
2381
2382impl UsageUpdate {
2383 #[must_use]
2385 pub fn new(used: u64, size: u64) -> Self {
2386 Self {
2387 used,
2388 size,
2389 cost: None,
2390 meta: None,
2391 }
2392 }
2393
2394 #[must_use]
2396 pub fn cost(mut self, cost: impl IntoOption<Cost>) -> Self {
2397 self.cost = cost.into_option();
2398 self
2399 }
2400
2401 #[must_use]
2407 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2408 self.meta = meta.into_option();
2409 self
2410 }
2411}
2412
2413#[serde_as]
2415#[skip_serializing_none]
2416#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2417#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
2418#[serde(rename_all = "camelCase")]
2419#[non_exhaustive]
2420pub struct Cost {
2421 pub amount: f64,
2423 pub currency: String,
2426 #[serde_as(deserialize_as = "DefaultOnError")]
2432 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2433 #[serde(default)]
2434 #[serde(rename = "_meta")]
2435 pub meta: Option<Meta>,
2436}
2437
2438impl Cost {
2439 #[must_use]
2441 pub fn new(amount: f64, currency: impl Into<String>) -> Self {
2442 Self {
2443 amount,
2444 currency: currency.into(),
2445 meta: None,
2446 }
2447 }
2448
2449 #[must_use]
2455 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2456 self.meta = meta.into_option();
2457 self
2458 }
2459}
2460
2461#[serde_as]
2463#[skip_serializing_none]
2464#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2465#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2466#[serde(rename_all = "camelCase")]
2467#[non_exhaustive]
2468pub struct ContentChunk {
2469 pub content: ContentBlock,
2471 #[serde_as(deserialize_as = "DefaultOnError")]
2476 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2477 #[serde(default)]
2478 pub message_id: Option<MessageId>,
2479 #[serde_as(deserialize_as = "DefaultOnError")]
2485 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2486 #[serde(default)]
2487 #[serde(rename = "_meta")]
2488 pub meta: Option<Meta>,
2489}
2490
2491impl ContentChunk {
2492 #[must_use]
2494 pub fn new(content: ContentBlock) -> Self {
2495 Self {
2496 content,
2497 message_id: None,
2498 meta: None,
2499 }
2500 }
2501
2502 #[must_use]
2507 pub fn message_id(mut self, message_id: impl IntoOption<MessageId>) -> Self {
2508 self.message_id = message_id.into_option();
2509 self
2510 }
2511
2512 #[must_use]
2518 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2519 self.meta = meta.into_option();
2520 self
2521 }
2522}
2523
2524#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2526#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
2527#[serde(transparent)]
2528#[from(Arc<str>, String, &'static str)]
2529#[non_exhaustive]
2530pub struct MessageId(pub Arc<str>);
2531
2532impl MessageId {
2533 #[must_use]
2535 pub fn new(id: impl Into<Arc<str>>) -> Self {
2536 Self(id.into())
2537 }
2538}
2539
2540impl IntoOption<MessageId> for &str {
2541 fn into_option(self) -> Option<MessageId> {
2542 Some(MessageId::new(self))
2543 }
2544}
2545
2546#[cfg(feature = "unstable_prompt_suggestions")]
2563#[serde_as]
2564#[skip_serializing_none]
2565#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2566#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2567#[serde(rename_all = "camelCase")]
2568#[non_exhaustive]
2569pub struct PromptSuggestionsUpdate {
2570 #[serde_as(deserialize_as = "VecSkipError<_>")]
2575 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-skip-invalid-items" = true)))]
2576 pub suggestions: Vec<PromptSuggestion>,
2577 #[serde_as(deserialize_as = "DefaultOnError")]
2583 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2584 #[serde(default)]
2585 #[serde(rename = "_meta")]
2586 pub meta: Option<Meta>,
2587}
2588
2589#[cfg(feature = "unstable_prompt_suggestions")]
2590impl PromptSuggestionsUpdate {
2591 #[must_use]
2595 pub fn new(suggestions: Vec<PromptSuggestion>) -> Self {
2596 Self {
2597 suggestions,
2598 meta: None,
2599 }
2600 }
2601
2602 #[must_use]
2608 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2609 self.meta = meta.into_option();
2610 self
2611 }
2612}
2613
2614#[cfg(feature = "unstable_prompt_suggestions")]
2620#[serde_as]
2621#[skip_serializing_none]
2622#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2623#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2624#[serde(rename_all = "camelCase")]
2625#[non_exhaustive]
2626pub struct PromptSuggestion {
2627 #[cfg_attr(feature = "schemars", schemars(length(min = 1)))]
2639 pub prompt: Vec<ContentBlock>,
2640 #[serde_as(deserialize_as = "DefaultOnError")]
2646 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2647 #[serde(default)]
2648 #[serde(rename = "_meta")]
2649 pub meta: Option<Meta>,
2650}
2651
2652#[cfg(feature = "unstable_prompt_suggestions")]
2653impl PromptSuggestion {
2654 #[must_use]
2656 pub fn new(prompt: Vec<ContentBlock>) -> Self {
2657 Self { prompt, meta: None }
2658 }
2659
2660 #[must_use]
2666 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2667 self.meta = meta.into_option();
2668 self
2669 }
2670}
2671
2672#[serde_as]
2674#[skip_serializing_none]
2675#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2676#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2677#[serde(rename_all = "camelCase")]
2678#[non_exhaustive]
2679pub struct AvailableCommandsUpdate {
2680 #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
2682 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
2683 pub available_commands: Vec<AvailableCommand>,
2684 #[serde_as(deserialize_as = "DefaultOnError")]
2690 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2691 #[serde(default)]
2692 #[serde(rename = "_meta")]
2693 pub meta: Option<Meta>,
2694}
2695
2696impl AvailableCommandsUpdate {
2697 #[must_use]
2699 pub fn new(available_commands: Vec<AvailableCommand>) -> Self {
2700 Self {
2701 available_commands,
2702 meta: None,
2703 }
2704 }
2705
2706 #[must_use]
2712 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2713 self.meta = meta.into_option();
2714 self
2715 }
2716}
2717
2718#[serde_as]
2720#[skip_serializing_none]
2721#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2722#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2723#[serde(rename_all = "camelCase")]
2724#[non_exhaustive]
2725pub struct AvailableCommand {
2726 pub name: String,
2728 pub description: String,
2730 #[serde_as(deserialize_as = "DefaultOnError")]
2732 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2733 #[serde(default)]
2734 pub input: Option<AvailableCommandInput>,
2735 #[serde_as(deserialize_as = "DefaultOnError")]
2741 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2742 #[serde(default)]
2743 #[serde(rename = "_meta")]
2744 pub meta: Option<Meta>,
2745}
2746
2747impl AvailableCommand {
2748 #[must_use]
2750 pub fn new(name: impl Into<String>, description: impl Into<String>) -> Self {
2751 Self {
2752 name: name.into(),
2753 description: description.into(),
2754 input: None,
2755 meta: None,
2756 }
2757 }
2758
2759 #[must_use]
2761 pub fn input(mut self, input: impl IntoOption<AvailableCommandInput>) -> Self {
2762 self.input = input.into_option();
2763 self
2764 }
2765
2766 #[must_use]
2772 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2773 self.meta = meta.into_option();
2774 self
2775 }
2776}
2777
2778#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2780#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2781#[serde(untagged, rename_all = "camelCase")]
2782#[non_exhaustive]
2783pub enum AvailableCommandInput {
2784 Unstructured(UnstructuredCommandInput),
2786}
2787
2788#[serde_as]
2790#[skip_serializing_none]
2791#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2792#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2793#[serde(rename_all = "camelCase")]
2794#[non_exhaustive]
2795pub struct UnstructuredCommandInput {
2796 pub hint: String,
2798 #[serde_as(deserialize_as = "DefaultOnError")]
2804 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2805 #[serde(default)]
2806 #[serde(rename = "_meta")]
2807 pub meta: Option<Meta>,
2808}
2809
2810impl UnstructuredCommandInput {
2811 #[must_use]
2813 pub fn new(hint: impl Into<String>) -> Self {
2814 Self {
2815 hint: hint.into(),
2816 meta: None,
2817 }
2818 }
2819
2820 #[must_use]
2826 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2827 self.meta = meta.into_option();
2828 self
2829 }
2830}
2831
2832#[serde_as]
2840#[skip_serializing_none]
2841#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2842#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2843#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = SESSION_REQUEST_PERMISSION_METHOD_NAME)))]
2844#[serde(rename_all = "camelCase")]
2845#[non_exhaustive]
2846pub struct RequestPermissionRequest {
2847 pub session_id: SessionId,
2849 pub tool_call: ToolCallUpdate,
2851 pub options: Vec<PermissionOption>,
2853 #[serde_as(deserialize_as = "DefaultOnError")]
2859 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2860 #[serde(default)]
2861 #[serde(rename = "_meta")]
2862 pub meta: Option<Meta>,
2863}
2864
2865impl RequestPermissionRequest {
2866 #[must_use]
2868 pub fn new(
2869 session_id: impl Into<SessionId>,
2870 tool_call: ToolCallUpdate,
2871 options: Vec<PermissionOption>,
2872 ) -> Self {
2873 Self {
2874 session_id: session_id.into(),
2875 tool_call,
2876 options,
2877 meta: None,
2878 }
2879 }
2880
2881 #[must_use]
2887 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2888 self.meta = meta.into_option();
2889 self
2890 }
2891}
2892
2893#[serde_as]
2895#[skip_serializing_none]
2896#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2897#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2898#[serde(rename_all = "camelCase")]
2899#[non_exhaustive]
2900pub struct PermissionOption {
2901 pub option_id: PermissionOptionId,
2903 pub name: String,
2905 pub kind: PermissionOptionKind,
2907 #[serde_as(deserialize_as = "DefaultOnError")]
2913 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2914 #[serde(default)]
2915 #[serde(rename = "_meta")]
2916 pub meta: Option<Meta>,
2917}
2918
2919impl PermissionOption {
2920 #[must_use]
2922 pub fn new(
2923 option_id: impl Into<PermissionOptionId>,
2924 name: impl Into<String>,
2925 kind: PermissionOptionKind,
2926 ) -> Self {
2927 Self {
2928 option_id: option_id.into(),
2929 name: name.into(),
2930 kind,
2931 meta: None,
2932 }
2933 }
2934
2935 #[must_use]
2941 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2942 self.meta = meta.into_option();
2943 self
2944 }
2945}
2946
2947#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2949#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
2950#[serde(transparent)]
2951#[from(Arc<str>, String, &'static str)]
2952#[non_exhaustive]
2953pub struct PermissionOptionId(pub Arc<str>);
2954
2955impl PermissionOptionId {
2956 #[must_use]
2958 pub fn new(id: impl Into<Arc<str>>) -> Self {
2959 Self(id.into())
2960 }
2961}
2962
2963#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2967#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
2968#[serde(rename_all = "snake_case")]
2969#[non_exhaustive]
2970pub enum PermissionOptionKind {
2971 AllowOnce,
2973 AllowAlways,
2975 RejectOnce,
2977 RejectAlways,
2979}
2980
2981#[serde_as]
2983#[skip_serializing_none]
2984#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2985#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2986#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = SESSION_REQUEST_PERMISSION_METHOD_NAME)))]
2987#[serde(rename_all = "camelCase")]
2988#[non_exhaustive]
2989pub struct RequestPermissionResponse {
2990 pub outcome: RequestPermissionOutcome,
2993 #[serde_as(deserialize_as = "DefaultOnError")]
2999 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3000 #[serde(default)]
3001 #[serde(rename = "_meta")]
3002 pub meta: Option<Meta>,
3003}
3004
3005impl RequestPermissionResponse {
3006 #[must_use]
3008 pub fn new(outcome: RequestPermissionOutcome) -> Self {
3009 Self {
3010 outcome,
3011 meta: None,
3012 }
3013 }
3014
3015 #[must_use]
3021 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3022 self.meta = meta.into_option();
3023 self
3024 }
3025}
3026
3027#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3029#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3030#[serde(tag = "outcome", rename_all = "snake_case")]
3031#[cfg_attr(feature = "schemars", schemars(extend("discriminator" = {"propertyName": "outcome"})))]
3032#[non_exhaustive]
3033pub enum RequestPermissionOutcome {
3034 Cancelled,
3042 #[serde(rename_all = "camelCase")]
3044 Selected(SelectedPermissionOutcome),
3045}
3046
3047#[serde_as]
3049#[skip_serializing_none]
3050#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3051#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3052#[serde(rename_all = "camelCase")]
3053#[non_exhaustive]
3054pub struct SelectedPermissionOutcome {
3055 pub option_id: PermissionOptionId,
3057 #[serde_as(deserialize_as = "DefaultOnError")]
3063 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3064 #[serde(default)]
3065 #[serde(rename = "_meta")]
3066 pub meta: Option<Meta>,
3067}
3068
3069impl SelectedPermissionOutcome {
3070 #[must_use]
3072 pub fn new(option_id: impl Into<PermissionOptionId>) -> Self {
3073 Self {
3074 option_id: option_id.into(),
3075 meta: None,
3076 }
3077 }
3078
3079 #[must_use]
3085 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3086 self.meta = meta.into_option();
3087 self
3088 }
3089}
3090
3091#[serde_as]
3097#[skip_serializing_none]
3098#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3099#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3100#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = FS_WRITE_TEXT_FILE_METHOD_NAME)))]
3101#[serde(rename_all = "camelCase")]
3102#[non_exhaustive]
3103pub struct WriteTextFileRequest {
3104 pub session_id: SessionId,
3106 pub path: PathBuf,
3108 pub content: String,
3110 #[serde_as(deserialize_as = "DefaultOnError")]
3116 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3117 #[serde(default)]
3118 #[serde(rename = "_meta")]
3119 pub meta: Option<Meta>,
3120}
3121
3122impl WriteTextFileRequest {
3123 #[must_use]
3125 pub fn new(
3126 session_id: impl Into<SessionId>,
3127 path: impl Into<PathBuf>,
3128 content: impl Into<String>,
3129 ) -> Self {
3130 Self {
3131 session_id: session_id.into(),
3132 path: path.into(),
3133 content: content.into(),
3134 meta: None,
3135 }
3136 }
3137
3138 #[must_use]
3144 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3145 self.meta = meta.into_option();
3146 self
3147 }
3148}
3149
3150crate::serde_util::default_on_null! {
3151 #[serde_as]
3153 #[skip_serializing_none]
3154 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3155 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
3156 #[serde(rename_all = "camelCase")]
3157 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = FS_WRITE_TEXT_FILE_METHOD_NAME)))]
3158 #[non_exhaustive]
3159 pub struct WriteTextFileResponse {
3160 #[serde_as(deserialize_as = "DefaultOnError")]
3166 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3167 #[serde(default)]
3168 #[serde(rename = "_meta")]
3169 pub meta: Option<Meta>,
3170 }
3171}
3172
3173impl WriteTextFileResponse {
3174 #[must_use]
3176 pub fn new() -> Self {
3177 Self::default()
3178 }
3179
3180 #[must_use]
3186 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3187 self.meta = meta.into_option();
3188 self
3189 }
3190}
3191
3192#[serde_as]
3198#[skip_serializing_none]
3199#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3200#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3201#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = FS_READ_TEXT_FILE_METHOD_NAME)))]
3202#[serde(rename_all = "camelCase")]
3203#[non_exhaustive]
3204pub struct ReadTextFileRequest {
3205 pub session_id: SessionId,
3207 pub path: PathBuf,
3209 #[serde(default)]
3211 pub line: Option<u32>,
3212 #[serde(default)]
3214 pub limit: Option<u32>,
3215 #[serde_as(deserialize_as = "DefaultOnError")]
3221 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3222 #[serde(default)]
3223 #[serde(rename = "_meta")]
3224 pub meta: Option<Meta>,
3225}
3226
3227impl ReadTextFileRequest {
3228 #[must_use]
3230 pub fn new(session_id: impl Into<SessionId>, path: impl Into<PathBuf>) -> Self {
3231 Self {
3232 session_id: session_id.into(),
3233 path: path.into(),
3234 line: None,
3235 limit: None,
3236 meta: None,
3237 }
3238 }
3239
3240 #[must_use]
3242 pub fn line(mut self, line: impl IntoOption<u32>) -> Self {
3243 self.line = line.into_option();
3244 self
3245 }
3246
3247 #[must_use]
3249 pub fn limit(mut self, limit: impl IntoOption<u32>) -> Self {
3250 self.limit = limit.into_option();
3251 self
3252 }
3253
3254 #[must_use]
3260 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3261 self.meta = meta.into_option();
3262 self
3263 }
3264}
3265
3266#[serde_as]
3268#[skip_serializing_none]
3269#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3270#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3271#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = FS_READ_TEXT_FILE_METHOD_NAME)))]
3272#[serde(rename_all = "camelCase")]
3273#[non_exhaustive]
3274pub struct ReadTextFileResponse {
3275 pub content: String,
3277 #[serde_as(deserialize_as = "DefaultOnError")]
3283 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3284 #[serde(default)]
3285 #[serde(rename = "_meta")]
3286 pub meta: Option<Meta>,
3287}
3288
3289impl ReadTextFileResponse {
3290 #[must_use]
3292 pub fn new(content: impl Into<String>) -> Self {
3293 Self {
3294 content: content.into(),
3295 meta: None,
3296 }
3297 }
3298
3299 #[must_use]
3305 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3306 self.meta = meta.into_option();
3307 self
3308 }
3309}
3310
3311#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3315#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
3316#[serde(transparent)]
3317#[from(Arc<str>, String, &'static str)]
3318#[non_exhaustive]
3319pub struct TerminalId(pub Arc<str>);
3320
3321impl TerminalId {
3322 #[must_use]
3324 pub fn new(id: impl Into<Arc<str>>) -> Self {
3325 Self(id.into())
3326 }
3327}
3328
3329#[serde_as]
3331#[skip_serializing_none]
3332#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3333#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3334#[serde(rename_all = "camelCase")]
3335#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = TERMINAL_CREATE_METHOD_NAME)))]
3336#[non_exhaustive]
3337pub struct CreateTerminalRequest {
3338 pub session_id: SessionId,
3340 pub command: String,
3342 #[serde_as(deserialize_as = "DefaultOnNull")]
3344 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
3345 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3346 pub args: Vec<String>,
3347 #[serde_as(deserialize_as = "DefaultOnNull")]
3349 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
3350 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3351 pub env: Vec<EnvVariable>,
3352 #[serde(default)]
3354 pub cwd: Option<PathBuf>,
3355 #[serde(default)]
3364 pub output_byte_limit: Option<u64>,
3365 #[serde_as(deserialize_as = "DefaultOnError")]
3371 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3372 #[serde(default)]
3373 #[serde(rename = "_meta")]
3374 pub meta: Option<Meta>,
3375}
3376
3377impl CreateTerminalRequest {
3378 #[must_use]
3380 pub fn new(session_id: impl Into<SessionId>, command: impl Into<String>) -> Self {
3381 Self {
3382 session_id: session_id.into(),
3383 command: command.into(),
3384 args: Vec::new(),
3385 env: Vec::new(),
3386 cwd: None,
3387 output_byte_limit: None,
3388 meta: None,
3389 }
3390 }
3391
3392 #[must_use]
3394 pub fn args(mut self, args: Vec<String>) -> Self {
3395 self.args = args;
3396 self
3397 }
3398
3399 #[must_use]
3401 pub fn env(mut self, env: Vec<EnvVariable>) -> Self {
3402 self.env = env;
3403 self
3404 }
3405
3406 #[must_use]
3408 pub fn cwd(mut self, cwd: impl IntoOption<PathBuf>) -> Self {
3409 self.cwd = cwd.into_option();
3410 self
3411 }
3412
3413 #[must_use]
3422 pub fn output_byte_limit(mut self, output_byte_limit: impl IntoOption<u64>) -> Self {
3423 self.output_byte_limit = output_byte_limit.into_option();
3424 self
3425 }
3426
3427 #[must_use]
3433 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3434 self.meta = meta.into_option();
3435 self
3436 }
3437}
3438
3439#[serde_as]
3441#[skip_serializing_none]
3442#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3443#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3444#[serde(rename_all = "camelCase")]
3445#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = TERMINAL_CREATE_METHOD_NAME)))]
3446#[non_exhaustive]
3447pub struct CreateTerminalResponse {
3448 pub terminal_id: TerminalId,
3450 #[serde_as(deserialize_as = "DefaultOnError")]
3456 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3457 #[serde(default)]
3458 #[serde(rename = "_meta")]
3459 pub meta: Option<Meta>,
3460}
3461
3462impl CreateTerminalResponse {
3463 #[must_use]
3465 pub fn new(terminal_id: impl Into<TerminalId>) -> Self {
3466 Self {
3467 terminal_id: terminal_id.into(),
3468 meta: None,
3469 }
3470 }
3471
3472 #[must_use]
3478 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3479 self.meta = meta.into_option();
3480 self
3481 }
3482}
3483
3484#[serde_as]
3486#[skip_serializing_none]
3487#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3488#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3489#[serde(rename_all = "camelCase")]
3490#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = TERMINAL_OUTPUT_METHOD_NAME)))]
3491#[non_exhaustive]
3492pub struct TerminalOutputRequest {
3493 pub session_id: SessionId,
3495 pub terminal_id: TerminalId,
3497 #[serde_as(deserialize_as = "DefaultOnError")]
3503 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3504 #[serde(default)]
3505 #[serde(rename = "_meta")]
3506 pub meta: Option<Meta>,
3507}
3508
3509impl TerminalOutputRequest {
3510 #[must_use]
3512 pub fn new(session_id: impl Into<SessionId>, terminal_id: impl Into<TerminalId>) -> Self {
3513 Self {
3514 session_id: session_id.into(),
3515 terminal_id: terminal_id.into(),
3516 meta: None,
3517 }
3518 }
3519
3520 #[must_use]
3526 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3527 self.meta = meta.into_option();
3528 self
3529 }
3530}
3531
3532#[serde_as]
3534#[skip_serializing_none]
3535#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3536#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3537#[serde(rename_all = "camelCase")]
3538#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = TERMINAL_OUTPUT_METHOD_NAME)))]
3539#[non_exhaustive]
3540pub struct TerminalOutputResponse {
3541 pub output: String,
3543 pub truncated: bool,
3545 #[serde_as(deserialize_as = "DefaultOnError")]
3547 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3548 #[serde(default)]
3549 pub exit_status: Option<TerminalExitStatus>,
3550 #[serde_as(deserialize_as = "DefaultOnError")]
3556 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3557 #[serde(default)]
3558 #[serde(rename = "_meta")]
3559 pub meta: Option<Meta>,
3560}
3561
3562impl TerminalOutputResponse {
3563 #[must_use]
3565 pub fn new(output: impl Into<String>, truncated: bool) -> Self {
3566 Self {
3567 output: output.into(),
3568 truncated,
3569 exit_status: None,
3570 meta: None,
3571 }
3572 }
3573
3574 #[must_use]
3576 pub fn exit_status(mut self, exit_status: impl IntoOption<TerminalExitStatus>) -> Self {
3577 self.exit_status = exit_status.into_option();
3578 self
3579 }
3580
3581 #[must_use]
3587 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3588 self.meta = meta.into_option();
3589 self
3590 }
3591}
3592
3593#[serde_as]
3595#[skip_serializing_none]
3596#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3597#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3598#[serde(rename_all = "camelCase")]
3599#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = TERMINAL_RELEASE_METHOD_NAME)))]
3600#[non_exhaustive]
3601pub struct ReleaseTerminalRequest {
3602 pub session_id: SessionId,
3604 pub terminal_id: TerminalId,
3606 #[serde_as(deserialize_as = "DefaultOnError")]
3612 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3613 #[serde(default)]
3614 #[serde(rename = "_meta")]
3615 pub meta: Option<Meta>,
3616}
3617
3618impl ReleaseTerminalRequest {
3619 #[must_use]
3621 pub fn new(session_id: impl Into<SessionId>, terminal_id: impl Into<TerminalId>) -> Self {
3622 Self {
3623 session_id: session_id.into(),
3624 terminal_id: terminal_id.into(),
3625 meta: None,
3626 }
3627 }
3628
3629 #[must_use]
3635 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3636 self.meta = meta.into_option();
3637 self
3638 }
3639}
3640
3641crate::serde_util::default_on_null! {
3642 #[serde_as]
3644 #[skip_serializing_none]
3645 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3646 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
3647 #[serde(rename_all = "camelCase")]
3648 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = TERMINAL_RELEASE_METHOD_NAME)))]
3649 #[non_exhaustive]
3650 pub struct ReleaseTerminalResponse {
3651 #[serde_as(deserialize_as = "DefaultOnError")]
3657 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3658 #[serde(default)]
3659 #[serde(rename = "_meta")]
3660 pub meta: Option<Meta>,
3661 }
3662}
3663
3664impl ReleaseTerminalResponse {
3665 #[must_use]
3667 pub fn new() -> Self {
3668 Self::default()
3669 }
3670
3671 #[must_use]
3677 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3678 self.meta = meta.into_option();
3679 self
3680 }
3681}
3682
3683#[serde_as]
3685#[skip_serializing_none]
3686#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3687#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3688#[serde(rename_all = "camelCase")]
3689#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = TERMINAL_KILL_METHOD_NAME)))]
3690#[non_exhaustive]
3691pub struct KillTerminalRequest {
3692 pub session_id: SessionId,
3694 pub terminal_id: TerminalId,
3696 #[serde_as(deserialize_as = "DefaultOnError")]
3702 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3703 #[serde(default)]
3704 #[serde(rename = "_meta")]
3705 pub meta: Option<Meta>,
3706}
3707
3708impl KillTerminalRequest {
3709 #[must_use]
3711 pub fn new(session_id: impl Into<SessionId>, terminal_id: impl Into<TerminalId>) -> Self {
3712 Self {
3713 session_id: session_id.into(),
3714 terminal_id: terminal_id.into(),
3715 meta: None,
3716 }
3717 }
3718
3719 #[must_use]
3725 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3726 self.meta = meta.into_option();
3727 self
3728 }
3729}
3730
3731crate::serde_util::default_on_null! {
3732 #[serde_as]
3734 #[skip_serializing_none]
3735 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3736 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
3737 #[serde(rename_all = "camelCase")]
3738 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = TERMINAL_KILL_METHOD_NAME)))]
3739 #[non_exhaustive]
3740 pub struct KillTerminalResponse {
3741 #[serde_as(deserialize_as = "DefaultOnError")]
3747 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3748 #[serde(default)]
3749 #[serde(rename = "_meta")]
3750 pub meta: Option<Meta>,
3751 }
3752}
3753
3754impl KillTerminalResponse {
3755 #[must_use]
3757 pub fn new() -> Self {
3758 Self::default()
3759 }
3760
3761 #[must_use]
3767 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3768 self.meta = meta.into_option();
3769 self
3770 }
3771}
3772
3773#[serde_as]
3775#[skip_serializing_none]
3776#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3777#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3778#[serde(rename_all = "camelCase")]
3779#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = TERMINAL_WAIT_FOR_EXIT_METHOD_NAME)))]
3780#[non_exhaustive]
3781pub struct WaitForTerminalExitRequest {
3782 pub session_id: SessionId,
3784 pub terminal_id: TerminalId,
3786 #[serde_as(deserialize_as = "DefaultOnError")]
3792 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3793 #[serde(default)]
3794 #[serde(rename = "_meta")]
3795 pub meta: Option<Meta>,
3796}
3797
3798impl WaitForTerminalExitRequest {
3799 #[must_use]
3801 pub fn new(session_id: impl Into<SessionId>, terminal_id: impl Into<TerminalId>) -> Self {
3802 Self {
3803 session_id: session_id.into(),
3804 terminal_id: terminal_id.into(),
3805 meta: None,
3806 }
3807 }
3808
3809 #[must_use]
3815 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3816 self.meta = meta.into_option();
3817 self
3818 }
3819}
3820
3821crate::serde_util::default_on_null! {
3822 #[serde_as]
3824 #[skip_serializing_none]
3825 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3826 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
3827 #[serde(rename_all = "camelCase")]
3828 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = TERMINAL_WAIT_FOR_EXIT_METHOD_NAME)))]
3829 #[non_exhaustive]
3830 pub struct WaitForTerminalExitResponse {
3831 #[serde(flatten)]
3833 pub exit_status: TerminalExitStatus,
3834 #[serde_as(deserialize_as = "DefaultOnError")]
3840 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3841 #[serde(default)]
3842 #[serde(rename = "_meta")]
3843 pub meta: Option<Meta>,
3844 }
3845}
3846
3847impl WaitForTerminalExitResponse {
3848 #[must_use]
3850 pub fn new(exit_status: TerminalExitStatus) -> Self {
3851 Self {
3852 exit_status,
3853 meta: None,
3854 }
3855 }
3856
3857 #[must_use]
3863 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3864 self.meta = meta.into_option();
3865 self
3866 }
3867}
3868
3869#[serde_as]
3871#[skip_serializing_none]
3872#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3873#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3874#[serde(rename_all = "camelCase")]
3875#[non_exhaustive]
3876pub struct TerminalExitStatus {
3877 #[serde_as(deserialize_as = "DefaultOnError")]
3879 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3880 #[serde(default)]
3881 pub exit_code: Option<u32>,
3882 #[serde_as(deserialize_as = "DefaultOnError")]
3884 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3885 #[serde(default)]
3886 pub signal: Option<String>,
3887 #[serde_as(deserialize_as = "DefaultOnError")]
3893 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3894 #[serde(default)]
3895 #[serde(rename = "_meta")]
3896 pub meta: Option<Meta>,
3897}
3898
3899impl TerminalExitStatus {
3900 #[must_use]
3902 pub fn new() -> Self {
3903 Self::default()
3904 }
3905
3906 #[must_use]
3908 pub fn exit_code(mut self, exit_code: impl IntoOption<u32>) -> Self {
3909 self.exit_code = exit_code.into_option();
3910 self
3911 }
3912
3913 #[must_use]
3915 pub fn signal(mut self, signal: impl IntoOption<String>) -> Self {
3916 self.signal = signal.into_option();
3917 self
3918 }
3919
3920 #[must_use]
3926 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3927 self.meta = meta.into_option();
3928 self
3929 }
3930}
3931
3932#[serde_as]
3941#[skip_serializing_none]
3942#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3943#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3944#[serde(rename_all = "camelCase")]
3945#[non_exhaustive]
3946pub struct ClientCapabilities {
3947 #[serde_as(deserialize_as = "DefaultOnError")]
3950 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3951 #[serde(default)]
3952 pub fs: FileSystemCapabilities,
3953 #[serde_as(deserialize_as = "DefaultOnError")]
3955 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3956 #[serde(default)]
3957 pub terminal: bool,
3958 #[serde_as(deserialize_as = "DefaultOnError")]
3963 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3964 #[serde(default)]
3965 pub session: Option<ClientSessionCapabilities>,
3966 #[serde_as(deserialize_as = "DefaultOnError")]
3975 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3976 #[serde(default)]
3977 pub subagents: Option<SubagentCapabilities>,
3978 #[serde_as(deserialize_as = "DefaultOnError")]
3983 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3984 #[serde(default)]
3985 pub plan: Option<PlanCapabilities>,
3986 #[serde_as(deserialize_as = "DefaultOnError")]
3990 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3991 #[serde(default)]
3992 pub auth: AuthCapabilities,
3993 #[serde_as(deserialize_as = "DefaultOnError")]
3999 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4000 #[serde(default)]
4001 pub elicitation: Option<ElicitationCapabilities>,
4002 #[serde_as(deserialize_as = "DefaultOnError")]
4008 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4009 #[serde(default)]
4010 #[serde(rename = "_meta")]
4011 pub meta: Option<Meta>,
4012}
4013
4014impl ClientCapabilities {
4015 #[must_use]
4017 pub fn new() -> Self {
4018 Self::default()
4019 }
4020
4021 #[must_use]
4024 pub fn fs(mut self, fs: FileSystemCapabilities) -> Self {
4025 self.fs = fs;
4026 self
4027 }
4028
4029 #[must_use]
4031 pub fn terminal(mut self, terminal: bool) -> Self {
4032 self.terminal = terminal;
4033 self
4034 }
4035
4036 #[must_use]
4038 pub fn session(mut self, session: impl IntoOption<ClientSessionCapabilities>) -> Self {
4039 self.session = session.into_option();
4040 self
4041 }
4042
4043 #[must_use]
4045 pub fn subagents(mut self, subagents: impl IntoOption<SubagentCapabilities>) -> Self {
4046 self.subagents = subagents.into_option();
4047 self
4048 }
4049
4050 #[must_use]
4055 pub fn plan(mut self, plan: impl IntoOption<PlanCapabilities>) -> Self {
4056 self.plan = plan.into_option();
4057 self
4058 }
4059
4060 #[must_use]
4064 pub fn auth(mut self, auth: AuthCapabilities) -> Self {
4065 self.auth = auth;
4066 self
4067 }
4068
4069 #[must_use]
4072 pub fn elicitation(mut self, elicitation: impl IntoOption<ElicitationCapabilities>) -> Self {
4073 self.elicitation = elicitation.into_option();
4074 self
4075 }
4076
4077 #[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#[serde_as]
4096#[skip_serializing_none]
4097#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4098#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4099#[non_exhaustive]
4100pub struct SubagentCapabilities {
4101 #[serde_as(deserialize_as = "DefaultOnError")]
4105 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4106 #[serde(default)]
4107 #[serde(rename = "_meta")]
4108 pub meta: Option<Meta>,
4109}
4110
4111impl SubagentCapabilities {
4112 #[must_use]
4114 pub fn new() -> Self {
4115 Self::default()
4116 }
4117
4118 #[must_use]
4122 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4123 self.meta = meta.into_option();
4124 self
4125 }
4126}
4127
4128#[serde_as]
4130#[skip_serializing_none]
4131#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4132#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4133#[serde(rename_all = "camelCase")]
4134#[non_exhaustive]
4135pub struct ClientSessionCapabilities {
4136 #[serde_as(deserialize_as = "DefaultOnError")]
4139 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4140 #[serde(default)]
4141 pub compaction: Option<CompactionCapabilities>,
4142 #[serde_as(deserialize_as = "DefaultOnError")]
4147 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4148 #[serde(default)]
4149 pub config_options: Option<SessionConfigOptionsCapabilities>,
4150 #[serde_as(deserialize_as = "DefaultOnError")]
4155 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4156 #[serde(default)]
4157 pub notices: Option<NoticeCapabilities>,
4158 #[cfg(feature = "unstable_prompt_suggestions")]
4168 #[serde_as(deserialize_as = "DefaultOnError")]
4169 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4170 #[serde(default)]
4171 pub prompt_suggestions: Option<PromptSuggestionsCapabilities>,
4172 #[cfg(feature = "unstable_session_cursors")]
4181 #[serde_as(deserialize_as = "DefaultOnError")]
4182 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4183 #[serde(default)]
4184 pub cursors: Option<SessionCursorsCapabilities>,
4185 #[serde_as(deserialize_as = "DefaultOnError")]
4191 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4192 #[serde(default)]
4193 #[serde(rename = "_meta")]
4194 pub meta: Option<Meta>,
4195}
4196
4197impl ClientSessionCapabilities {
4198 #[must_use]
4200 pub fn new() -> Self {
4201 Self::default()
4202 }
4203
4204 #[must_use]
4206 pub fn compaction(mut self, compaction: impl IntoOption<CompactionCapabilities>) -> Self {
4207 self.compaction = compaction.into_option();
4208 self
4209 }
4210
4211 #[must_use]
4216 pub fn config_options(
4217 mut self,
4218 config_options: impl IntoOption<SessionConfigOptionsCapabilities>,
4219 ) -> Self {
4220 self.config_options = config_options.into_option();
4221 self
4222 }
4223
4224 #[must_use]
4226 pub fn notices(mut self, notices: impl IntoOption<NoticeCapabilities>) -> Self {
4227 self.notices = notices.into_option();
4228 self
4229 }
4230
4231 #[cfg(feature = "unstable_prompt_suggestions")]
4237 #[must_use]
4238 pub fn prompt_suggestions(
4239 mut self,
4240 prompt_suggestions: impl IntoOption<PromptSuggestionsCapabilities>,
4241 ) -> Self {
4242 self.prompt_suggestions = prompt_suggestions.into_option();
4243 self
4244 }
4245
4246 #[cfg(feature = "unstable_session_cursors")]
4252 #[must_use]
4253 pub fn cursors(mut self, cursors: impl IntoOption<SessionCursorsCapabilities>) -> Self {
4254 self.cursors = cursors.into_option();
4255 self
4256 }
4257
4258 #[must_use]
4264 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4265 self.meta = meta.into_option();
4266 self
4267 }
4268}
4269
4270#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4272#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4273#[serde(rename_all = "camelCase")]
4274#[non_exhaustive]
4275pub struct CompactionCapabilities {}
4276
4277impl CompactionCapabilities {
4278 #[must_use]
4280 pub fn new() -> Self {
4281 Self {}
4282 }
4283}
4284
4285#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4287#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4288#[serde(rename_all = "camelCase")]
4289#[non_exhaustive]
4290pub struct NoticeCapabilities {}
4291
4292impl NoticeCapabilities {
4293 #[must_use]
4295 pub fn new() -> Self {
4296 Self {}
4297 }
4298}
4299
4300#[cfg(feature = "unstable_session_cursors")]
4308#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4309#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4310#[serde(rename_all = "camelCase")]
4311#[non_exhaustive]
4312pub struct SessionCursorsCapabilities {}
4313
4314#[cfg(feature = "unstable_session_cursors")]
4315impl SessionCursorsCapabilities {
4316 #[must_use]
4318 pub fn new() -> Self {
4319 Self {}
4320 }
4321}
4322
4323#[cfg(feature = "unstable_prompt_suggestions")]
4334#[serde_as]
4335#[skip_serializing_none]
4336#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4337#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4338#[serde(rename_all = "camelCase")]
4339#[non_exhaustive]
4340pub struct PromptSuggestionsCapabilities {
4341 #[serde_as(deserialize_as = "DefaultOnError")]
4346 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4347 #[serde(default)]
4348 pub image: Option<PromptSuggestionsImageCapabilities>,
4349 #[serde_as(deserialize_as = "DefaultOnError")]
4354 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4355 #[serde(default)]
4356 pub audio: Option<PromptSuggestionsAudioCapabilities>,
4357 #[serde_as(deserialize_as = "DefaultOnError")]
4363 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4364 #[serde(default)]
4365 pub embedded_context: Option<PromptSuggestionsEmbeddedContextCapabilities>,
4366 #[serde_as(deserialize_as = "DefaultOnError")]
4372 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4373 #[serde(default)]
4374 #[serde(rename = "_meta")]
4375 pub meta: Option<Meta>,
4376}
4377
4378#[cfg(feature = "unstable_prompt_suggestions")]
4379impl PromptSuggestionsCapabilities {
4380 #[must_use]
4382 pub fn new() -> Self {
4383 Self::default()
4384 }
4385
4386 #[must_use]
4388 pub fn image(mut self, image: impl IntoOption<PromptSuggestionsImageCapabilities>) -> Self {
4389 self.image = image.into_option();
4390 self
4391 }
4392
4393 #[must_use]
4395 pub fn audio(mut self, audio: impl IntoOption<PromptSuggestionsAudioCapabilities>) -> Self {
4396 self.audio = audio.into_option();
4397 self
4398 }
4399
4400 #[must_use]
4402 pub fn embedded_context(
4403 mut self,
4404 embedded_context: impl IntoOption<PromptSuggestionsEmbeddedContextCapabilities>,
4405 ) -> Self {
4406 self.embedded_context = embedded_context.into_option();
4407 self
4408 }
4409
4410 #[must_use]
4416 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4417 self.meta = meta.into_option();
4418 self
4419 }
4420}
4421
4422#[cfg(feature = "unstable_prompt_suggestions")]
4430#[serde_as]
4431#[skip_serializing_none]
4432#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4433#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4434#[non_exhaustive]
4435pub struct PromptSuggestionsImageCapabilities {
4436 #[serde_as(deserialize_as = "DefaultOnError")]
4442 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4443 #[serde(default)]
4444 #[serde(rename = "_meta")]
4445 pub meta: Option<Meta>,
4446}
4447
4448#[cfg(feature = "unstable_prompt_suggestions")]
4449impl PromptSuggestionsImageCapabilities {
4450 #[must_use]
4452 pub fn new() -> Self {
4453 Self::default()
4454 }
4455
4456 #[must_use]
4462 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4463 self.meta = meta.into_option();
4464 self
4465 }
4466}
4467
4468#[cfg(feature = "unstable_prompt_suggestions")]
4476#[serde_as]
4477#[skip_serializing_none]
4478#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4479#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4480#[non_exhaustive]
4481pub struct PromptSuggestionsAudioCapabilities {
4482 #[serde_as(deserialize_as = "DefaultOnError")]
4488 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4489 #[serde(default)]
4490 #[serde(rename = "_meta")]
4491 pub meta: Option<Meta>,
4492}
4493
4494#[cfg(feature = "unstable_prompt_suggestions")]
4495impl PromptSuggestionsAudioCapabilities {
4496 #[must_use]
4498 pub fn new() -> Self {
4499 Self::default()
4500 }
4501
4502 #[must_use]
4508 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4509 self.meta = meta.into_option();
4510 self
4511 }
4512}
4513
4514#[cfg(feature = "unstable_prompt_suggestions")]
4523#[serde_as]
4524#[skip_serializing_none]
4525#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4526#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4527#[non_exhaustive]
4528pub struct PromptSuggestionsEmbeddedContextCapabilities {
4529 #[serde_as(deserialize_as = "DefaultOnError")]
4535 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4536 #[serde(default)]
4537 #[serde(rename = "_meta")]
4538 pub meta: Option<Meta>,
4539}
4540
4541#[cfg(feature = "unstable_prompt_suggestions")]
4542impl PromptSuggestionsEmbeddedContextCapabilities {
4543 #[must_use]
4545 pub fn new() -> Self {
4546 Self::default()
4547 }
4548
4549 #[must_use]
4555 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4556 self.meta = meta.into_option();
4557 self
4558 }
4559}
4560
4561#[serde_as]
4563#[skip_serializing_none]
4564#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4565#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4566#[serde(rename_all = "camelCase")]
4567#[non_exhaustive]
4568pub struct SessionConfigOptionsCapabilities {
4569 #[serde_as(deserialize_as = "DefaultOnError")]
4576 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4577 #[serde(default)]
4578 pub boolean: Option<BooleanConfigOptionCapabilities>,
4579 #[serde_as(deserialize_as = "DefaultOnError")]
4585 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4586 #[serde(default)]
4587 #[serde(rename = "_meta")]
4588 pub meta: Option<Meta>,
4589}
4590
4591impl SessionConfigOptionsCapabilities {
4592 #[must_use]
4594 pub fn new() -> Self {
4595 Self::default()
4596 }
4597
4598 #[must_use]
4605 pub fn boolean(mut self, boolean: impl IntoOption<BooleanConfigOptionCapabilities>) -> Self {
4606 self.boolean = boolean.into_option();
4607 self
4608 }
4609
4610 #[must_use]
4616 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4617 self.meta = meta.into_option();
4618 self
4619 }
4620}
4621
4622#[serde_as]
4626#[skip_serializing_none]
4627#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4628#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4629#[non_exhaustive]
4630pub struct BooleanConfigOptionCapabilities {
4631 #[serde_as(deserialize_as = "DefaultOnError")]
4637 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4638 #[serde(default)]
4639 #[serde(rename = "_meta")]
4640 pub meta: Option<Meta>,
4641}
4642
4643impl BooleanConfigOptionCapabilities {
4644 #[must_use]
4646 pub fn new() -> Self {
4647 Self::default()
4648 }
4649
4650 #[must_use]
4656 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4657 self.meta = meta.into_option();
4658 self
4659 }
4660}
4661
4662#[serde_as]
4668#[skip_serializing_none]
4669#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4670#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4671#[serde(rename_all = "camelCase")]
4672#[non_exhaustive]
4673pub struct AuthCapabilities {
4674 #[serde_as(deserialize_as = "DefaultOnError")]
4680 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4681 #[serde(default)]
4682 pub terminal: bool,
4683 #[serde_as(deserialize_as = "DefaultOnError")]
4689 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4690 #[serde(default)]
4691 #[serde(rename = "_meta")]
4692 pub meta: Option<Meta>,
4693}
4694
4695impl AuthCapabilities {
4696 #[must_use]
4698 pub fn new() -> Self {
4699 Self::default()
4700 }
4701
4702 #[must_use]
4709 pub fn terminal(mut self, terminal: bool) -> Self {
4710 self.terminal = terminal;
4711 self
4712 }
4713
4714 #[must_use]
4720 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4721 self.meta = meta.into_option();
4722 self
4723 }
4724}
4725
4726#[serde_as]
4730#[skip_serializing_none]
4731#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4732#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4733#[serde(rename_all = "camelCase")]
4734#[non_exhaustive]
4735pub struct FileSystemCapabilities {
4736 #[serde_as(deserialize_as = "DefaultOnError")]
4738 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4739 #[serde(default)]
4740 pub read_text_file: bool,
4741 #[serde_as(deserialize_as = "DefaultOnError")]
4743 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4744 #[serde(default)]
4745 pub write_text_file: bool,
4746 #[serde_as(deserialize_as = "DefaultOnError")]
4752 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4753 #[serde(default)]
4754 #[serde(rename = "_meta")]
4755 pub meta: Option<Meta>,
4756}
4757
4758impl FileSystemCapabilities {
4759 #[must_use]
4761 pub fn new() -> Self {
4762 Self::default()
4763 }
4764
4765 #[must_use]
4767 pub fn read_text_file(mut self, read_text_file: bool) -> Self {
4768 self.read_text_file = read_text_file;
4769 self
4770 }
4771
4772 #[must_use]
4774 pub fn write_text_file(mut self, write_text_file: bool) -> Self {
4775 self.write_text_file = write_text_file;
4776 self
4777 }
4778
4779 #[must_use]
4785 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4786 self.meta = meta.into_option();
4787 self
4788 }
4789}
4790
4791#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4797#[non_exhaustive]
4798pub struct ClientMethodNames {
4799 pub session_request_permission: &'static str,
4801 pub session_update: &'static str,
4803 pub fs_write_text_file: &'static str,
4805 pub fs_read_text_file: &'static str,
4807 pub terminal_create: &'static str,
4809 pub terminal_output: &'static str,
4811 pub terminal_release: &'static str,
4813 pub terminal_wait_for_exit: &'static str,
4815 pub terminal_kill: &'static str,
4817 #[cfg(feature = "unstable_mcp_over_acp")]
4819 pub mcp_message: &'static str,
4820 pub elicitation_create: &'static str,
4822 pub elicitation_complete: &'static str,
4824 #[cfg(feature = "unstable_auth_status")]
4826 pub auth_status_update: &'static str,
4827}
4828
4829pub const CLIENT_METHOD_NAMES: ClientMethodNames = ClientMethodNames {
4831 session_update: SESSION_UPDATE_NOTIFICATION,
4832 session_request_permission: SESSION_REQUEST_PERMISSION_METHOD_NAME,
4833 fs_write_text_file: FS_WRITE_TEXT_FILE_METHOD_NAME,
4834 fs_read_text_file: FS_READ_TEXT_FILE_METHOD_NAME,
4835 terminal_create: TERMINAL_CREATE_METHOD_NAME,
4836 terminal_output: TERMINAL_OUTPUT_METHOD_NAME,
4837 terminal_release: TERMINAL_RELEASE_METHOD_NAME,
4838 terminal_wait_for_exit: TERMINAL_WAIT_FOR_EXIT_METHOD_NAME,
4839 terminal_kill: TERMINAL_KILL_METHOD_NAME,
4840 #[cfg(feature = "unstable_mcp_over_acp")]
4841 mcp_message: MCP_MESSAGE_METHOD_NAME,
4842 elicitation_create: ELICITATION_CREATE_METHOD_NAME,
4843 elicitation_complete: ELICITATION_COMPLETE_NOTIFICATION,
4844 #[cfg(feature = "unstable_auth_status")]
4845 auth_status_update: AUTH_STATUS_UPDATE_NOTIFICATION,
4846};
4847
4848pub(crate) const SESSION_UPDATE_NOTIFICATION: &str = "session/update";
4850pub(crate) const SESSION_REQUEST_PERMISSION_METHOD_NAME: &str = "session/request_permission";
4852pub(crate) const FS_WRITE_TEXT_FILE_METHOD_NAME: &str = "fs/write_text_file";
4854pub(crate) const FS_READ_TEXT_FILE_METHOD_NAME: &str = "fs/read_text_file";
4856pub(crate) const TERMINAL_CREATE_METHOD_NAME: &str = "terminal/create";
4858pub(crate) const TERMINAL_OUTPUT_METHOD_NAME: &str = "terminal/output";
4860pub(crate) const TERMINAL_RELEASE_METHOD_NAME: &str = "terminal/release";
4862pub(crate) const TERMINAL_WAIT_FOR_EXIT_METHOD_NAME: &str = "terminal/wait_for_exit";
4864pub(crate) const TERMINAL_KILL_METHOD_NAME: &str = "terminal/kill";
4866pub(crate) const ELICITATION_CREATE_METHOD_NAME: &str = "elicitation/create";
4868pub(crate) const ELICITATION_COMPLETE_NOTIFICATION: &str = "elicitation/complete";
4870#[cfg(feature = "unstable_auth_status")]
4872pub(crate) const AUTH_STATUS_UPDATE_NOTIFICATION: &str = "auth/status_update";
4873
4874#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4881#[derive(Clone, Debug, Serialize, Deserialize)]
4882#[serde(untagged)]
4883#[cfg_attr(feature = "schemars", schemars(inline))]
4884#[non_exhaustive]
4885pub enum AgentRequest {
4886 WriteTextFileRequest(WriteTextFileRequest),
4893 ReadTextFileRequest(ReadTextFileRequest),
4900 RequestPermissionRequest(RequestPermissionRequest),
4911 CreateTerminalRequest(CreateTerminalRequest),
4926 TerminalOutputRequest(TerminalOutputRequest),
4933 ReleaseTerminalRequest(ReleaseTerminalRequest),
4946 WaitForTerminalExitRequest(WaitForTerminalExitRequest),
4950 KillTerminalRequest(KillTerminalRequest),
4963 CreateElicitationRequest(CreateElicitationRequest),
4967 #[cfg(feature = "unstable_mcp_over_acp")]
4973 MessageMcpRequest(MessageMcpRequest),
4974 ExtMethodRequest(ExtRequest),
4982}
4983
4984impl_request_dispatch! {
4985 AgentRequest => ClientResponse {
4986 WriteTextFileRequest => WriteTextFileResponse: CLIENT_METHOD_NAMES.fs_write_text_file,
4987 ReadTextFileRequest => ReadTextFileResponse: CLIENT_METHOD_NAMES.fs_read_text_file,
4988 RequestPermissionRequest => RequestPermissionResponse: CLIENT_METHOD_NAMES.session_request_permission,
4989 CreateTerminalRequest => CreateTerminalResponse: CLIENT_METHOD_NAMES.terminal_create,
4990 TerminalOutputRequest => TerminalOutputResponse: CLIENT_METHOD_NAMES.terminal_output,
4991 ReleaseTerminalRequest => ReleaseTerminalResponse: CLIENT_METHOD_NAMES.terminal_release,
4992 WaitForTerminalExitRequest => WaitForTerminalExitResponse: CLIENT_METHOD_NAMES.terminal_wait_for_exit,
4993 KillTerminalRequest => KillTerminalResponse: CLIENT_METHOD_NAMES.terminal_kill,
4994 CreateElicitationRequest => CreateElicitationResponse: CLIENT_METHOD_NAMES.elicitation_create,
4995 #[cfg(feature = "unstable_mcp_over_acp")]
4996 MessageMcpRequest => MessageMcpResponse: CLIENT_METHOD_NAMES.mcp_message,
4997 }
4998 extension ExtMethodRequest(ExtRequest) => ExtMethodResponse;
4999}
5000
5001#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5008#[derive(Clone, Debug, Serialize, Deserialize)]
5009#[serde(untagged)]
5010#[cfg_attr(feature = "schemars", schemars(inline))]
5011#[non_exhaustive]
5012pub enum ClientResponse {
5013 WriteTextFileResponse(#[serde(default)] WriteTextFileResponse),
5015 ReadTextFileResponse(ReadTextFileResponse),
5017 RequestPermissionResponse(RequestPermissionResponse),
5019 CreateTerminalResponse(CreateTerminalResponse),
5021 TerminalOutputResponse(TerminalOutputResponse),
5023 ReleaseTerminalResponse(#[serde(default)] ReleaseTerminalResponse),
5025 WaitForTerminalExitResponse(WaitForTerminalExitResponse),
5027 KillTerminalResponse(#[serde(default)] KillTerminalResponse),
5029 CreateElicitationResponse(CreateElicitationResponse),
5031 #[cfg(feature = "unstable_mcp_over_acp")]
5033 MessageMcpResponse(MessageMcpResponse),
5034 ExtMethodResponse(ExtResponse),
5036}
5037
5038#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5045#[derive(Clone, Debug, Serialize, Deserialize)]
5046#[serde(untagged)]
5047#[expect(
5048 clippy::large_enum_variant,
5049 reason = "TODO(next major): box SessionNotification in the v1 enum"
5050)]
5051#[cfg_attr(feature = "schemars", schemars(inline))]
5052#[non_exhaustive]
5053pub enum AgentNotification {
5054 SessionNotification(SessionNotification),
5066 CompleteElicitationNotification(CompleteElicitationNotification),
5070 #[cfg(feature = "unstable_auth_status")]
5078 AuthStatusUpdateNotification(AuthStatusUpdateNotification),
5079 ExtNotification(ExtNotification),
5087}
5088
5089impl_message_dispatch! {
5090 AgentNotification {
5091 SessionNotification => CLIENT_METHOD_NAMES.session_update,
5092 CompleteElicitationNotification => CLIENT_METHOD_NAMES.elicitation_complete,
5093 #[cfg(feature = "unstable_auth_status")]
5094 AuthStatusUpdateNotification => CLIENT_METHOD_NAMES.auth_status_update,
5095 }
5096 extension ExtNotification(ExtNotification);
5097}
5098
5099#[cfg(test)]
5100mod tests {
5101 use super::*;
5102
5103 #[test]
5104 fn notice_preserves_wire_shape_nullable_fields_and_open_severity() {
5105 use serde_json::json;
5106
5107 let mut meta = Meta::new();
5108 meta.insert("source".into(), json!("fallback"));
5109 assert_eq!(
5110 serde_json::to_value(SessionUpdate::Notice(
5111 Notice::new(NoticeSeverity::Warning, "MCP server unavailable")
5112 .description("Continuing without it.")
5113 .meta(meta),
5114 ))
5115 .unwrap(),
5116 json!({
5117 "sessionUpdate": "notice",
5118 "severity": "warning",
5119 "title": "MCP server unavailable",
5120 "description": "Continuing without it.",
5121 "_meta": { "source": "fallback" }
5122 })
5123 );
5124
5125 assert_eq!(
5126 serde_json::to_value(SessionUpdate::Notice(Notice::new(
5127 NoticeSeverity::Info,
5128 "Indexing workspace",
5129 )))
5130 .unwrap(),
5131 json!({
5132 "sessionUpdate": "notice",
5133 "severity": "info",
5134 "title": "Indexing workspace"
5135 })
5136 );
5137
5138 let SessionUpdate::Notice(notice) = serde_json::from_value(json!({
5139 "sessionUpdate": "notice",
5140 "severity": "critical",
5141 "title": "Provider degraded",
5142 "description": null,
5143 "_meta": null
5144 }))
5145 .unwrap() else {
5146 panic!("expected notice");
5147 };
5148
5149 assert_eq!(
5150 notice.severity,
5151 NoticeSeverity::Other("critical".to_string())
5152 );
5153 assert_eq!(notice.description, None);
5154 assert_eq!(notice.meta, None);
5155 assert_eq!(
5156 serde_json::to_value(SessionUpdate::Notice(notice)).unwrap(),
5157 json!({
5158 "sessionUpdate": "notice",
5159 "severity": "critical",
5160 "title": "Provider degraded"
5161 })
5162 );
5163 }
5164
5165 #[test]
5166 fn notice_requires_string_severity_and_title() {
5167 use serde_json::json;
5168
5169 for malformed in [
5170 json!({
5171 "sessionUpdate": "notice",
5172 "severity": "warning",
5173 "title": 42
5174 }),
5175 json!({
5176 "sessionUpdate": "notice",
5177 "severity": 42,
5178 "title": "MCP server unavailable"
5179 }),
5180 json!({
5181 "sessionUpdate": "notice",
5182 "severity": "warning"
5183 }),
5184 json!({
5185 "sessionUpdate": "notice",
5186 "severity": "warning",
5187 "title": null
5188 }),
5189 json!({
5190 "sessionUpdate": "notice",
5191 "title": "MCP server unavailable"
5192 }),
5193 json!({
5194 "sessionUpdate": "notice",
5195 "severity": null,
5196 "title": "MCP server unavailable"
5197 }),
5198 ] {
5199 assert!(serde_json::from_str::<SessionUpdate>(&malformed.to_string()).is_err());
5200 assert!(serde_json::from_value::<SessionUpdate>(malformed).is_err());
5201 }
5202 }
5203
5204 #[test]
5205 fn notice_tolerates_invalid_optional_display_fields_and_custom_severity() {
5206 use serde_json::json;
5207
5208 let wire = json!({
5209 "sessionUpdate": "notice",
5210 "severity": "_custom",
5211 "title": "Provider degraded",
5212 "description": 42,
5213 "_meta": false
5214 });
5215 let SessionUpdate::Notice(notice) = serde_json::from_value(wire.clone()).unwrap() else {
5216 panic!("expected notice");
5217 };
5218 assert_eq!(
5220 serde_json::from_str::<SessionUpdate>(&wire.to_string()).unwrap(),
5221 SessionUpdate::Notice(notice.clone())
5222 );
5223 assert_eq!(notice.severity, NoticeSeverity::Other("_custom".into()));
5224 assert_eq!(notice.description, None);
5225 assert_eq!(notice.meta, None);
5226 assert_eq!(
5227 serde_json::to_value(notice).unwrap(),
5228 json!({"severity": "_custom", "title": "Provider degraded"})
5229 );
5230 }
5231
5232 #[cfg(feature = "schemars")]
5233 #[test]
5234 fn notice_schema_preserves_required_and_nullable_fields() {
5235 use serde_json::json;
5236
5237 let schema = serde_json::to_value(schemars::schema_for!(Notice)).unwrap();
5238 assert_eq!(schema["required"], json!(["severity", "title"]));
5239 assert_eq!(schema["properties"]["title"]["minLength"], 1);
5240 for field in ["description", "_meta"] {
5241 assert!(
5242 schema["properties"][field]["type"]
5243 .as_array()
5244 .unwrap()
5245 .contains(&json!("null"))
5246 );
5247 }
5248 let capabilities =
5249 serde_json::to_value(schemars::schema_for!(ClientSessionCapabilities)).unwrap();
5250 assert!(
5251 capabilities["properties"]["notices"]["anyOf"]
5252 .as_array()
5253 .unwrap()
5254 .contains(&json!({"type": "null"}))
5255 );
5256 assert!(
5257 !capabilities["required"]
5258 .as_array()
5259 .is_some_and(|required| required.contains(&json!("notices")))
5260 );
5261 }
5262
5263 #[test]
5264 fn notice_capability_advertises_support_only_when_present() {
5265 use serde_json::json;
5266
5267 let capabilities = ClientCapabilities::new()
5268 .session(ClientSessionCapabilities::new().notices(NoticeCapabilities::new()));
5269 let value = serde_json::to_value(&capabilities).unwrap();
5270 assert_eq!(value["session"], json!({ "notices": {} }));
5271 assert_eq!(
5272 serde_json::from_value::<ClientCapabilities>(value).unwrap(),
5273 capabilities
5274 );
5275
5276 for unsupported in [
5277 json!({}),
5278 json!({ "session": null }),
5279 json!({ "session": {} }),
5280 json!({ "session": { "notices": null } }),
5281 json!({ "session": { "notices": false } }),
5282 json!({ "session": { "notices": true } }),
5283 json!({ "session": { "notices": "supported" } }),
5284 ] {
5285 let capabilities: ClientCapabilities = serde_json::from_value(unsupported).unwrap();
5286 assert!(
5287 capabilities
5288 .session
5289 .and_then(|session| session.notices)
5290 .is_none()
5291 );
5292 }
5293
5294 assert_eq!(
5295 serde_json::to_value(
5296 ClientSessionCapabilities::new()
5297 .notices(NoticeCapabilities::new())
5298 .notices(None)
5299 )
5300 .unwrap(),
5301 json!({})
5302 );
5303 }
5304
5305 #[cfg(feature = "unstable_prompt_suggestions")]
5306 #[test]
5307 fn prompt_suggestions_update_round_trips_prompt_content_and_meta() {
5308 use crate::v1::{ResourceLink, TextContent};
5309 use serde_json::json;
5310
5311 let mut meta = Meta::new();
5312 meta.insert("rank".into(), json!(1));
5313 let update = SessionUpdate::PromptSuggestionsUpdate(PromptSuggestionsUpdate::new(vec![
5314 PromptSuggestion::new(vec![ContentBlock::Text(TextContent::new(
5315 "Run the test suite and fix what breaks",
5316 ))])
5317 .meta(meta),
5318 PromptSuggestion::new(vec![
5319 ContentBlock::Text(TextContent::new("Add tests for ")),
5320 ContentBlock::ResourceLink(ResourceLink::new(
5321 "parser.rs",
5322 "file:///home/user/project/src/parser.rs",
5323 )),
5324 ]),
5325 ]));
5326 let wire = json!({
5327 "sessionUpdate": "prompt_suggestions_update",
5328 "suggestions": [
5329 {
5330 "prompt": [
5331 { "type": "text", "text": "Run the test suite and fix what breaks" }
5332 ],
5333 "_meta": { "rank": 1 }
5334 },
5335 {
5336 "prompt": [
5337 { "type": "text", "text": "Add tests for " },
5338 {
5339 "type": "resource_link",
5340 "name": "parser.rs",
5341 "uri": "file:///home/user/project/src/parser.rs"
5342 }
5343 ]
5344 }
5345 ]
5346 });
5347 assert_eq!(serde_json::to_value(&update).unwrap(), wire);
5348 assert_eq!(
5349 serde_json::from_value::<SessionUpdate>(wire).unwrap(),
5350 update
5351 );
5352 }
5353
5354 #[cfg(feature = "unstable_prompt_suggestions")]
5355 #[test]
5356 fn prompt_suggestions_update_with_an_empty_list_withdraws_suggestions() {
5357 use serde_json::json;
5358
5359 let update = SessionUpdate::PromptSuggestionsUpdate(PromptSuggestionsUpdate::new(vec![]));
5360 let wire = json!({
5361 "sessionUpdate": "prompt_suggestions_update",
5362 "suggestions": []
5363 });
5364 assert_eq!(serde_json::to_value(&update).unwrap(), wire);
5365 assert_eq!(
5366 serde_json::from_value::<SessionUpdate>(wire).unwrap(),
5367 update
5368 );
5369
5370 for malformed in [json!(null), json!("none"), json!({ "prompt": [] })] {
5372 assert!(
5373 serde_json::from_value::<SessionUpdate>(json!({
5374 "sessionUpdate": "prompt_suggestions_update",
5375 "suggestions": malformed
5376 }))
5377 .is_err()
5378 );
5379 }
5380 assert!(
5381 serde_json::from_value::<SessionUpdate>(json!({
5382 "sessionUpdate": "prompt_suggestions_update"
5383 }))
5384 .is_err()
5385 );
5386 }
5387
5388 #[cfg(feature = "unstable_prompt_suggestions")]
5389 #[test]
5390 fn prompt_suggestions_update_skips_whole_suggestions_it_cannot_parse() {
5391 use crate::v1::TextContent;
5392 use serde_json::json;
5393
5394 let text =
5395 |text: &str| PromptSuggestion::new(vec![ContentBlock::Text(TextContent::new(text))]);
5396
5397 let update: SessionUpdate = serde_json::from_value(json!({
5400 "sessionUpdate": "prompt_suggestions_update",
5401 "suggestions": [
5402 { "prompt": [{ "type": "text", "text": "Keep the first" }] },
5403 { "text": "A suggestion without a prompt" },
5404 { "prompt": "Not a list" },
5405 { "prompt": [{ "type": "text", "text": "Open " }, { "type": "text" }] },
5406 { "prompt": [{ "type": "hologram", "data": "AAAA" }] },
5407 "not an object",
5408 { "prompt": [{ "type": "text", "text": "Keep the last" }], "_meta": false }
5409 ]
5410 }))
5411 .unwrap();
5412
5413 assert_eq!(
5414 update,
5415 SessionUpdate::PromptSuggestionsUpdate(PromptSuggestionsUpdate::new(vec![
5416 text("Keep the first"),
5417 text("Keep the last"),
5418 ]))
5419 );
5420 }
5421
5422 #[cfg(feature = "unstable_prompt_suggestions")]
5423 #[test]
5424 fn prompt_suggestions_capability_advertises_support_and_content_types() {
5425 use serde_json::json;
5426
5427 let capabilities = ClientCapabilities::new().session(
5428 ClientSessionCapabilities::new()
5429 .prompt_suggestions(PromptSuggestionsCapabilities::new()),
5430 );
5431 let value = serde_json::to_value(&capabilities).unwrap();
5432 assert_eq!(value["session"], json!({ "promptSuggestions": {} }));
5433 assert_eq!(
5434 serde_json::from_value::<ClientCapabilities>(value).unwrap(),
5435 capabilities
5436 );
5437
5438 let content_types = PromptSuggestionsCapabilities::new()
5439 .image(PromptSuggestionsImageCapabilities::new())
5440 .audio(PromptSuggestionsAudioCapabilities::new())
5441 .embedded_context(PromptSuggestionsEmbeddedContextCapabilities::new());
5442 let wire = json!({ "image": {}, "audio": {}, "embeddedContext": {} });
5443 assert_eq!(serde_json::to_value(&content_types).unwrap(), wire);
5444 assert_eq!(
5445 serde_json::from_value::<PromptSuggestionsCapabilities>(wire).unwrap(),
5446 content_types
5447 );
5448
5449 for unsupported in [
5450 json!({}),
5451 json!({ "session": null }),
5452 json!({ "session": {} }),
5453 json!({ "session": { "promptSuggestions": null } }),
5454 json!({ "session": { "promptSuggestions": false } }),
5455 json!({ "session": { "promptSuggestions": true } }),
5456 json!({ "session": { "promptSuggestions": "supported" } }),
5457 ] {
5458 let capabilities: ClientCapabilities = serde_json::from_value(unsupported).unwrap();
5459 assert!(
5460 capabilities
5461 .session
5462 .and_then(|session| session.prompt_suggestions)
5463 .is_none()
5464 );
5465 }
5466
5467 assert_eq!(
5470 serde_json::from_value::<PromptSuggestionsCapabilities>(json!({
5471 "image": true,
5472 "audio": null,
5473 "embeddedContext": {}
5474 }))
5475 .unwrap(),
5476 PromptSuggestionsCapabilities::new()
5477 .embedded_context(PromptSuggestionsEmbeddedContextCapabilities::new())
5478 );
5479 }
5480
5481 #[cfg(all(feature = "schemars", feature = "unstable_prompt_suggestions"))]
5482 #[test]
5483 fn prompt_suggestions_schema_requires_the_list_and_a_non_empty_prompt() {
5484 use serde_json::json;
5485
5486 let update = serde_json::to_value(schemars::schema_for!(PromptSuggestionsUpdate)).unwrap();
5487 assert_eq!(update["required"], json!(["suggestions"]));
5488 assert_eq!(update["properties"]["suggestions"]["type"], "array");
5489
5490 let suggestion = serde_json::to_value(schemars::schema_for!(PromptSuggestion)).unwrap();
5491 assert_eq!(suggestion["required"], json!(["prompt"]));
5492 assert_eq!(suggestion["properties"]["prompt"]["type"], "array");
5493 assert_eq!(suggestion["properties"]["prompt"]["minItems"], 1);
5494
5495 let capabilities =
5496 serde_json::to_value(schemars::schema_for!(ClientSessionCapabilities)).unwrap();
5497 assert!(
5498 capabilities["properties"]["promptSuggestions"]["anyOf"]
5499 .as_array()
5500 .unwrap()
5501 .contains(&json!({"type": "null"}))
5502 );
5503 assert!(
5504 !capabilities["required"]
5505 .as_array()
5506 .is_some_and(|required| required.contains(&json!("promptSuggestions")))
5507 );
5508
5509 let content_types =
5510 serde_json::to_value(schemars::schema_for!(PromptSuggestionsCapabilities)).unwrap();
5511 assert!(content_types.get("required").is_none());
5512 for field in ["image", "audio", "embeddedContext"] {
5513 assert!(
5514 content_types["properties"][field]["anyOf"]
5515 .as_array()
5516 .unwrap()
5517 .contains(&json!({"type": "null"}))
5518 );
5519 }
5520 }
5521
5522 #[test]
5523 fn compaction_updates_preserve_patch_and_open_status_semantics() {
5524 use serde_json::json;
5525
5526 assert_eq!(
5527 serde_json::to_value(SessionUpdate::CompactionUpdate(CompactionUpdate::new(
5528 "cmp_001",
5529 CompactionStatus::InProgress,
5530 )))
5531 .unwrap(),
5532 json!({
5533 "sessionUpdate": "compaction_update",
5534 "compactionId": "cmp_001",
5535 "status": "in_progress"
5536 })
5537 );
5538
5539 let SessionUpdate::CompactionUpdate(update) = serde_json::from_value(json!({
5540 "sessionUpdate": "compaction_update",
5541 "compactionId": "cmp_001",
5542 "status": "paused",
5543 "summary": null,
5544 "error": null
5545 }))
5546 .unwrap() else {
5547 panic!("expected compaction update");
5548 };
5549 assert_eq!(update.status, CompactionStatus::Other("paused".into()));
5550 assert!(update.summary.is_null());
5551 assert!(update.error.is_null());
5552 assert!(update.meta.is_undefined());
5553 }
5554
5555 #[test]
5556 fn compaction_chunk_and_v1_capability_serialize() {
5557 use serde_json::json;
5558
5559 assert_eq!(
5560 serde_json::to_value(SessionUpdate::CompactionSummaryChunk(
5561 CompactionSummaryChunk::new(
5562 "cmp_001",
5563 ContentBlock::Text(crate::v1::TextContent::new("retained")),
5564 ),
5565 ))
5566 .unwrap(),
5567 json!({
5568 "sessionUpdate": "compaction_summary_chunk",
5569 "compactionId": "cmp_001",
5570 "content": { "type": "text", "text": "retained" }
5571 })
5572 );
5573 assert_eq!(
5574 serde_json::to_value(
5575 ClientSessionCapabilities::new().compaction(CompactionCapabilities::new())
5576 )
5577 .unwrap(),
5578 json!({ "compaction": {} })
5579 );
5580 let absent: ClientSessionCapabilities = serde_json::from_value(json!({})).unwrap();
5581 let null: ClientSessionCapabilities =
5582 serde_json::from_value(json!({ "compaction": null })).unwrap();
5583 assert!(absent.compaction.is_none());
5584 assert!(null.compaction.is_none());
5585 }
5586
5587 #[test]
5588 fn test_subagent_updates_serialization() {
5589 use serde_json::json;
5590
5591 let announced = SessionUpdate::SubagentUpdate(SubagentUpdate::new("sess_child_1"));
5592 assert_eq!(
5593 serde_json::to_value(&announced).unwrap(),
5594 json!({
5595 "sessionUpdate": "subagent_update",
5596 "sessionId": "sess_child_1"
5597 })
5598 );
5599 assert_eq!(
5600 serde_json::from_value::<SessionUpdate>(serde_json::to_value(&announced).unwrap())
5601 .unwrap(),
5602 announced
5603 );
5604 let capable = SubagentUpdate::new("sess_child_1").capabilities(
5605 SubagentSessionCapabilities::new().cancel(SessionCancelCapabilities::new()),
5606 );
5607 assert_eq!(
5608 serde_json::to_value(capable).unwrap(),
5609 json!({
5610 "sessionId": "sess_child_1",
5611 "capabilities": {"cancel": {}}
5612 })
5613 );
5614 let minimal: SubagentUpdate =
5615 serde_json::from_value(json!({ "sessionId": "sess_child_3" })).unwrap();
5616 assert!(minimal.capabilities.is_undefined());
5617 assert!(minimal.state.is_undefined());
5618
5619 let nulls: SubagentUpdate = serde_json::from_value(json!({
5620 "sessionId": "sess_child_3",
5621 "capabilities": null,
5622 "state": null
5623 }))
5624 .unwrap();
5625 assert!(nulls.capabilities.is_null());
5626 assert!(nulls.state.is_null());
5627 assert_eq!(
5628 serde_json::to_value(nulls).unwrap(),
5629 json!({"sessionId": "sess_child_3", "capabilities": null, "state": null})
5630 );
5631 }
5632
5633 #[test]
5634 fn test_subagent_display_metadata() {
5635 use serde_json::json;
5636
5637 let update = SubagentUpdate::new("child")
5638 .title("Test investigator".to_string())
5639 .description("Investigates platform-specific test failures.".to_string());
5640 let wire = json!({
5641 "sessionId": "child",
5642 "title": "Test investigator",
5643 "description": "Investigates platform-specific test failures."
5644 });
5645 assert_eq!(serde_json::to_value(&update).unwrap(), wire);
5646 assert_eq!(
5647 serde_json::from_value::<SubagentUpdate>(wire).unwrap(),
5648 update
5649 );
5650
5651 let minimal = SubagentUpdate::new("child");
5652 assert_eq!(
5653 serde_json::to_value(&minimal).unwrap(),
5654 json!({"sessionId": "child"})
5655 );
5656 let cleared: SubagentUpdate = serde_json::from_value(json!({
5657 "sessionId": "child", "title": null, "description": null
5658 }))
5659 .unwrap();
5660 assert!(cleared.title.is_null());
5661 assert!(cleared.description.is_null());
5662 assert_eq!(
5663 serde_json::to_value(cleared).unwrap(),
5664 json!({"sessionId": "child", "title": null, "description": null})
5665 );
5666 let invalid: SubagentUpdate = serde_json::from_value(json!({
5667 "sessionId": "child", "title": false, "description": false
5668 }))
5669 .unwrap();
5670 assert_eq!(invalid, minimal);
5671
5672 let title_only: SubagentUpdate = serde_json::from_value(json!({
5673 "sessionId": "child", "title": "Updated title"
5674 }))
5675 .unwrap();
5676 assert_eq!(
5677 title_only.title.value().map(String::as_str),
5678 Some("Updated title")
5679 );
5680 assert!(title_only.description.is_undefined());
5681 }
5682
5683 #[test]
5684 fn subagent_directories_use_strict_patch_semantics() {
5685 use serde_json::json;
5686
5687 let update = SubagentUpdate::new("child")
5688 .cwd("/home/user/project/.worktrees/investigator")
5689 .additional_directories(vec![]);
5690 let wire = json!({
5691 "sessionId": "child",
5692 "cwd": "/home/user/project/.worktrees/investigator",
5693 "additionalDirectories": []
5694 });
5695 assert_eq!(serde_json::to_value(&update).unwrap(), wire);
5696 assert_eq!(
5697 serde_json::from_value::<SubagentUpdate>(wire).unwrap(),
5698 update
5699 );
5700
5701 let inherited: SubagentUpdate =
5702 serde_json::from_value(json!({"sessionId": "child"})).unwrap();
5703 assert!(inherited.cwd.is_undefined());
5704 assert!(inherited.additional_directories.is_undefined());
5705
5706 let cleared_wire = json!({
5707 "sessionId": "child", "cwd": null, "additionalDirectories": null
5708 });
5709 let cleared: SubagentUpdate = serde_json::from_value(cleared_wire.clone()).unwrap();
5710 assert!(cleared.cwd.is_null());
5711 assert!(cleared.additional_directories.is_null());
5712 assert_eq!(serde_json::to_value(cleared).unwrap(), cleared_wire);
5713
5714 for malformed in [
5715 json!({"sessionId": "child", "cwd": false}),
5716 json!({"sessionId": "child", "additionalDirectories": "/tmp/wt"}),
5717 json!({"sessionId": "child", "additionalDirectories": ["/tmp/wt", false]}),
5718 ] {
5719 assert!(
5720 serde_json::from_value::<SubagentUpdate>(malformed.clone()).is_err(),
5721 "{malformed}"
5722 );
5723 }
5724 }
5725
5726 #[test]
5727 fn subagent_patch_fields_preserve_omitted_null_and_concrete() {
5728 use serde_json::json;
5729
5730 let omitted = SubagentUpdate::new("child");
5731 for field in ["title", "description", "capabilities", "state", "_meta"] {
5732 let wire = json!({"sessionId": "child", field: null});
5733 let decoded: SubagentUpdate = serde_json::from_value(wire.clone()).unwrap();
5734 assert_eq!(serde_json::to_value(decoded).unwrap(), wire, "{field}");
5735 let malformed = json!({"sessionId": "child", field: false});
5736 let decoded: SubagentUpdate = serde_json::from_value(malformed).unwrap();
5737 assert_eq!(decoded, omitted, "{field}");
5738 }
5739 let concrete = json!({
5740 "sessionId": "child", "title": "Investigator",
5741 "description": "Tests", "capabilities": {"cancel": {}},
5742 "state": {"state": "running"}, "_meta": {"source": "parent"}
5743 });
5744 let decoded: SubagentUpdate = serde_json::from_value(concrete.clone()).unwrap();
5745 assert!(decoded.title.value().is_some());
5746 assert!(decoded.description.value().is_some());
5747 assert!(decoded.capabilities.value().is_some());
5748 assert!(decoded.state.value().is_some());
5749 assert!(decoded.meta.value().is_some());
5750 assert_eq!(serde_json::to_value(decoded).unwrap(), concrete);
5751 let cleared = SubagentUpdate::new("child")
5752 .title(None)
5753 .description(None)
5754 .capabilities(None)
5755 .state(None)
5756 .meta(None);
5757 assert_eq!(
5758 serde_json::to_value(cleared).unwrap(),
5759 json!({
5760 "sessionId": "child", "title": null, "description": null,
5761 "capabilities": null, "state": null, "_meta": null
5762 })
5763 );
5764 }
5765
5766 #[test]
5767 fn test_subagent_notification_keeps_parent_and_child_ids_nested() {
5768 use serde_json::json;
5769
5770 let notification = SessionNotification::new(
5771 "parent",
5772 SessionUpdate::SubagentUpdate(SubagentUpdate::new("child")),
5773 );
5774 let wire = json!({
5775 "sessionId": "parent",
5776 "update": {
5777 "sessionUpdate": "subagent_update",
5778 "sessionId": "child"
5779 }
5780 });
5781 assert_eq!(serde_json::to_value(¬ification).unwrap(), wire);
5782 assert_eq!(
5783 serde_json::from_value::<SessionNotification>(wire).unwrap(),
5784 notification
5785 );
5786 for malformed in [
5788 json!({"sessionId": "parent", "update": {"sessionUpdate": "subagent_update"}}),
5789 json!({"update": {"sessionUpdate": "subagent_update", "sessionId": "child"}}),
5790 ] {
5791 assert!(serde_json::from_value::<SessionNotification>(malformed).is_err());
5792 }
5793 }
5794
5795 #[test]
5796 fn test_subagent_states_round_trip() {
5797 use serde_json::json;
5798
5799 for (wire_state, expected) in [
5800 (
5801 json!({"state": "running"}),
5802 StateUpdate::Running(RunningStateUpdate::new()),
5803 ),
5804 (
5805 json!({"state": "idle", "stopReason": "end_turn"}),
5806 StateUpdate::Idle(IdleStateUpdate::new().stop_reason(IdleStopReason::EndTurn)),
5807 ),
5808 (
5809 json!({"state": "requires_action"}),
5810 StateUpdate::RequiresAction(RequiresActionStateUpdate::new()),
5811 ),
5812 (
5813 json!({"state": "unknown"}),
5814 StateUpdate::Unknown(UnknownStateUpdate::new()),
5815 ),
5816 (
5817 json!({"state": "_waiting", "detail": {"ticket": 7}}),
5818 StateUpdate::Other(OtherStateUpdate::new(
5819 "_waiting",
5820 [("detail".into(), json!({"ticket": 7}))].into(),
5821 )),
5822 ),
5823 (
5824 json!({"state": "paused", "retryAt": 42}),
5825 StateUpdate::Other(OtherStateUpdate::new(
5826 "paused",
5827 [("retryAt".into(), json!(42))].into(),
5828 )),
5829 ),
5830 ] {
5831 let wire = json!({
5832 "sessionUpdate": "subagent_update",
5833 "sessionId": "sess_child",
5834 "state": wire_state
5835 });
5836 let parsed: SessionUpdate = serde_json::from_value(wire.clone()).unwrap();
5837 let SessionUpdate::SubagentUpdate(update) = &parsed else {
5838 panic!("expected subagent update");
5839 };
5840 assert_eq!(update.state.value(), Some(&expected));
5841 assert_eq!(serde_json::to_value(parsed).unwrap(), wire);
5842 }
5843
5844 for reason in [
5845 "end_turn",
5846 "max_tokens",
5847 "max_turn_requests",
5848 "refusal",
5849 "cancelled",
5850 ] {
5851 let state: StateUpdate = serde_json::from_value(json!({
5852 "state": "idle", "stopReason": reason
5853 }))
5854 .unwrap();
5855 assert_eq!(serde_json::to_value(state).unwrap()["stopReason"], reason);
5856 }
5857
5858 for state in [
5861 StateUpdate::Running(RunningStateUpdate::new()),
5862 StateUpdate::RequiresAction(RequiresActionStateUpdate::new()),
5863 StateUpdate::Unknown(UnknownStateUpdate::new()),
5864 StateUpdate::Running(RunningStateUpdate::new()),
5865 StateUpdate::Idle(IdleStateUpdate::new().stop_reason(IdleStopReason::EndTurn)),
5866 StateUpdate::Unknown(UnknownStateUpdate::new()),
5867 StateUpdate::Running(RunningStateUpdate::new()),
5868 ] {
5869 let update = SubagentUpdate::new("sess_child").state(state.clone());
5870 let wire = serde_json::to_value(&update).unwrap();
5871 assert_eq!(wire["sessionId"], "sess_child");
5872 assert_eq!(
5873 serde_json::from_value::<SubagentUpdate>(wire)
5874 .unwrap()
5875 .state,
5876 MaybeUndefined::Value(state)
5877 );
5878 }
5879 assert_eq!(
5880 serde_json::to_value(
5881 SubagentUpdate::new("sess_child").state(StateUpdate::Idle(IdleStateUpdate::new()))
5882 )
5883 .unwrap()["state"],
5884 json!({"state": "idle"})
5885 );
5886 }
5887
5888 #[test]
5889 fn subagent_idle_snapshot_reports_child_failure() {
5890 use serde_json::json;
5891
5892 let update = SubagentUpdate::new("sess_child").state(StateUpdate::Idle(
5893 IdleStateUpdate::new().stop_reason(IdleStopReason::from(
5894 ErrorStopReason::new().error(Error::auth_required()),
5895 )),
5896 ));
5897 let wire = json!({
5898 "sessionId": "sess_child",
5899 "state": {
5900 "state": "idle",
5901 "stopReason": "error",
5902 "error": { "code": -32000, "message": "Authentication required" }
5903 }
5904 });
5905 assert_eq!(serde_json::to_value(&update).unwrap(), wire);
5906 assert_eq!(
5907 serde_json::from_value::<SubagentUpdate>(wire).unwrap(),
5908 update
5909 );
5910
5911 let without_details = StateUpdate::Idle(
5913 IdleStateUpdate::new().stop_reason(IdleStopReason::from(ErrorStopReason::new())),
5914 );
5915 for error in [None, Some(json!(null)), Some(json!("failed"))] {
5916 let mut wire = json!({ "state": "idle", "stopReason": "error" });
5917 if let Some(error) = error {
5918 wire["error"] = error;
5919 }
5920 assert_eq!(
5921 serde_json::from_value::<StateUpdate>(wire).unwrap(),
5922 without_details
5923 );
5924 }
5925
5926 let parsed: StateUpdate = serde_json::from_value(json!({
5929 "state": "idle",
5930 "stopReason": "end_turn",
5931 "error": { "code": -32603, "message": "Internal error" }
5932 }))
5933 .unwrap();
5934 assert_eq!(
5935 parsed,
5936 StateUpdate::Idle(IdleStateUpdate::new().stop_reason(IdleStopReason::EndTurn))
5937 );
5938
5939 let meta: Meta = [("source".into(), json!("worker"))].into_iter().collect();
5942 for stop_reason in [None, Some(json!(null)), Some(json!(true))] {
5943 let mut wire = json!({ "state": "idle", "_meta": { "source": "worker" } });
5944 if let Some(stop_reason) = stop_reason {
5945 wire["stopReason"] = stop_reason;
5946 }
5947 assert_eq!(
5948 serde_json::from_value::<StateUpdate>(wire).unwrap(),
5949 StateUpdate::Idle(IdleStateUpdate::new().meta(meta.clone()))
5950 );
5951 }
5952
5953 for stop_reason in ["_paused", "not_a_reason"] {
5956 let wire = json!({
5957 "state": "idle",
5958 "stopReason": stop_reason,
5959 "resumeAfter": 30,
5960 "_meta": { "source": "worker" }
5961 });
5962 let parsed: StateUpdate = serde_json::from_value(wire.clone()).unwrap();
5963 assert_eq!(
5964 parsed,
5965 StateUpdate::Idle(
5966 IdleStateUpdate::new()
5967 .stop_reason(IdleStopReason::Other(OtherStopReason::new(
5968 stop_reason,
5969 [("resumeAfter".into(), json!(30))].into_iter().collect(),
5970 )))
5971 .meta(meta.clone())
5972 )
5973 );
5974 assert_eq!(serde_json::to_value(&parsed).unwrap(), wire);
5975 }
5976 }
5977
5978 #[test]
5979 fn subagent_known_stop_reasons_are_never_read_as_other() {
5980 use serde_json::json;
5981
5982 let known = [
5983 IdleStopReason::EndTurn,
5984 IdleStopReason::MaxTokens,
5985 IdleStopReason::MaxTurnRequests,
5986 IdleStopReason::Refusal,
5987 IdleStopReason::Cancelled,
5988 IdleStopReason::Error(ErrorStopReason::new()),
5989 ];
5990 for stop_reason in &known {
5992 match stop_reason {
5993 IdleStopReason::EndTurn
5994 | IdleStopReason::MaxTokens
5995 | IdleStopReason::MaxTurnRequests
5996 | IdleStopReason::Refusal
5997 | IdleStopReason::Cancelled
5998 | IdleStopReason::Error(_)
5999 | IdleStopReason::Other(_) => {}
6000 }
6001 }
6002
6003 for stop_reason in known {
6004 let state = StateUpdate::Idle(IdleStateUpdate::new().stop_reason(stop_reason));
6005 let wire = serde_json::to_value(&state).unwrap();
6006 assert_eq!(
6007 serde_json::from_value::<StateUpdate>(wire.clone()).unwrap(),
6008 state
6009 );
6010 assert!(
6011 serde_json::from_value::<OtherStopReason>(
6012 json!({ "stopReason": wire["stopReason"] })
6013 )
6014 .is_err(),
6015 "{} must not be accepted as a custom stop reason",
6016 wire["stopReason"]
6017 );
6018 }
6019 }
6020
6021 #[test]
6022 fn subagent_unknown_stop_reason_leaves_usage_on_the_snapshot() {
6023 use serde_json::json;
6024
6025 let usage = json!({ "totalTokens": 10, "inputTokens": 6, "outputTokens": 4 });
6026 let wire = json!({ "state": "idle", "stopReason": "_paused", "usage": usage });
6027 let StateUpdate::Idle(idle) = serde_json::from_value(wire).unwrap() else {
6028 panic!("expected idle state snapshot");
6029 };
6030 let Some(IdleStopReason::Other(other)) = &idle.stop_reason else {
6031 panic!("expected a custom stop reason");
6032 };
6033 assert!(other.fields.is_empty());
6034
6035 #[cfg(feature = "unstable_end_turn_token_usage")]
6036 {
6037 assert!(idle.usage.is_some());
6038 assert_eq!(serde_json::to_value(&idle).unwrap()["usage"], usage);
6039 }
6040 #[cfg(not(feature = "unstable_end_turn_token_usage"))]
6043 assert!(serde_json::to_value(&idle).unwrap().get("usage").is_none());
6044 }
6045
6046 #[test]
6047 fn test_subagent_unknown_activity_metadata_and_capabilities() {
6048 use serde_json::json;
6049
6050 let update = SubagentUpdate::new("child").state(StateUpdate::Unknown(
6051 UnknownStateUpdate::new().meta(
6052 [("source".into(), json!("worker"))]
6053 .into_iter()
6054 .collect::<Meta>(),
6055 ),
6056 ));
6057 let wire = json!({
6058 "sessionId": "child",
6059 "state": {
6060 "state": "unknown",
6061 "_meta": { "source": "worker" }
6062 }
6063 });
6064 assert_eq!(serde_json::to_value(&update).unwrap(), wire);
6065 assert_eq!(
6066 serde_json::from_value::<SubagentUpdate>(wire).unwrap(),
6067 update
6068 );
6069 assert!(update.capabilities.is_undefined());
6071
6072 for meta in [json!(null), json!(false)] {
6073 let state: StateUpdate = serde_json::from_value(json!({
6074 "state": "unknown",
6075 "_meta": meta
6076 }))
6077 .unwrap();
6078 assert_eq!(state, StateUpdate::Unknown(UnknownStateUpdate::new()));
6079 assert_eq!(
6080 serde_json::to_value(state).unwrap(),
6081 json!({"state": "unknown"})
6082 );
6083 }
6084 assert!(serde_json::from_value::<OtherStateUpdate>(json!({"state": "unknown"})).is_err());
6086 }
6087
6088 #[test]
6089 fn test_subagent_malformed_optional_state() {
6090 use serde_json::json;
6091
6092 for malformed in [json!("running"), json!({}), json!({"state": 4})] {
6093 assert!(serde_json::from_value::<StateUpdate>(malformed.clone()).is_err());
6094 let update: SubagentUpdate = serde_json::from_value(json!({
6095 "sessionId": "child", "state": malformed
6096 }))
6097 .unwrap();
6098 assert!(update.state.is_undefined());
6099 }
6100 let bad_reason: StateUpdate =
6101 serde_json::from_value(json!({"state": "idle", "stopReason": false})).unwrap();
6102 assert_eq!(bad_reason, StateUpdate::Idle(IdleStateUpdate::new()));
6103 let null_reason: StateUpdate =
6104 serde_json::from_value(json!({"state": "idle", "stopReason": null})).unwrap();
6105 assert_eq!(null_reason, StateUpdate::Idle(IdleStateUpdate::new()));
6106 }
6107
6108 #[cfg(feature = "unstable_protocol_v2")]
6109 #[test]
6110 fn test_subagent_state_v2_wire_parity() {
6111 use serde_json::json;
6112
6113 for wire in [
6114 json!({"state": "running"}),
6115 json!({"state": "idle", "stopReason": "cancelled"}),
6116 json!({"state": "requires_action"}),
6117 json!({"state": "unknown"}),
6118 json!({"state": "unknown", "_meta": {"source": "worker"}}),
6119 json!({"state": "_waiting", "detail": {"ticket": 7}}),
6120 ] {
6121 let v1: StateUpdate = serde_json::from_value(wire.clone()).unwrap();
6122 let v2: crate::v2::StateUpdate = serde_json::from_value(wire.clone()).unwrap();
6123 assert_eq!(serde_json::to_value(v1).unwrap(), wire);
6124 assert_eq!(serde_json::to_value(v2).unwrap(), wire);
6125 }
6126 }
6127
6128 #[test]
6129 fn test_subagent_capability_semantics() {
6130 use serde_json::json;
6131
6132 let capabilities =
6133 serde_json::to_value(ClientCapabilities::new().subagents(SubagentCapabilities::new()))
6134 .unwrap();
6135 assert_eq!(capabilities["subagents"], json!({}));
6136
6137 let omitted: ClientCapabilities = serde_json::from_value(json!({})).unwrap();
6138 assert!(omitted.subagents.is_none());
6139
6140 let null: ClientCapabilities =
6141 serde_json::from_value(json!({ "subagents": null })).unwrap();
6142 assert!(null.subagents.is_none());
6143 assert_eq!(null, omitted);
6144 let serialized = serde_json::to_value(null).unwrap();
6145 assert_eq!(serialized, serde_json::to_value(omitted).unwrap());
6146 assert!(serialized.get("subagents").is_none());
6147
6148 for wire in [
6149 json!({}),
6150 json!({"cancel": null}),
6151 json!({"cancel": true}),
6152 json!({"cancel": false}),
6153 ] {
6154 let child: SubagentSessionCapabilities = serde_json::from_value(wire).unwrap();
6155 assert!(child.cancel.is_none());
6156 assert_eq!(serde_json::to_value(child).unwrap(), json!({}));
6157 }
6158 let enabled = SubagentSessionCapabilities::new().cancel(SessionCancelCapabilities::new());
6159 assert_eq!(
6160 serde_json::to_value(&enabled).unwrap(),
6161 json!({"cancel": {}})
6162 );
6163 assert_eq!(
6164 serde_json::from_value::<SubagentSessionCapabilities>(json!({"cancel": {}})).unwrap(),
6165 enabled
6166 );
6167 let meta: Meta = [("source".into(), json!("worker"))].into_iter().collect();
6168 let with_meta =
6169 SubagentSessionCapabilities::new().cancel(SessionCancelCapabilities::new().meta(meta));
6170 let wire = json!({"cancel": {"_meta": {"source": "worker"}}});
6171 assert_eq!(serde_json::to_value(&with_meta).unwrap(), wire);
6172 assert_eq!(
6173 serde_json::from_value::<SubagentSessionCapabilities>(wire).unwrap(),
6174 with_meta
6175 );
6176 let removed = SubagentSessionCapabilities::new();
6178 assert_eq!(serde_json::to_value(&removed).unwrap(), json!({}));
6179 assert!(removed.cancel.is_none());
6180 assert!(enabled.cancel.is_some());
6181 assert!(enabled.cancel(None).cancel.is_none());
6182 let replacement = SubagentUpdate::new("child").capabilities(removed);
6183 assert_eq!(
6184 serde_json::to_value(replacement).unwrap(),
6185 json!({"sessionId": "child", "capabilities": {}})
6186 );
6187 }
6188
6189 #[cfg(feature = "schemars")]
6190 #[test]
6191 fn test_subagent_capability_schema_is_optional_and_nullable() {
6192 use serde_json::json;
6193
6194 let schema = serde_json::to_value(schemars::schema_for!(ClientCapabilities)).unwrap();
6195 let variants = schema["properties"]["subagents"]["anyOf"]
6196 .as_array()
6197 .expect("subagents must allow the capability object or null");
6198 assert!(variants.contains(&json!({"type": "null"})));
6199 assert!(
6200 !schema["required"]
6201 .as_array()
6202 .is_some_and(|required| required.contains(&json!("subagents")))
6203 );
6204 let child =
6205 serde_json::to_value(schemars::schema_for!(SubagentSessionCapabilities)).unwrap();
6206 let variants = child["properties"]["cancel"]["anyOf"]
6207 .as_array()
6208 .expect("cancel must allow the capability object or null");
6209 assert!(variants.contains(&json!({"type": "null"})));
6210 assert!(
6211 variants
6212 .iter()
6213 .any(|variant| variant["type"] == "object" || variant.get("$ref").is_some())
6214 );
6215 assert!(!variants.iter().any(|variant| variant["type"] == "boolean"));
6216 let cancel =
6217 serde_json::to_value(schemars::schema_for!(SessionCancelCapabilities)).unwrap();
6218 assert_eq!(cancel["type"], "object");
6219 assert!(
6220 !child["required"]
6221 .as_array()
6222 .is_some_and(|required| required.contains(&json!("cancel")))
6223 );
6224 }
6225
6226 #[test]
6227 fn test_elicitation_capability_semantics() {
6228 use serde_json::json;
6229
6230 let unsupported: ClientCapabilities = serde_json::from_value(json!({})).unwrap();
6231 assert!(unsupported.elicitation.is_none());
6232
6233 let null: ClientCapabilities =
6234 serde_json::from_value(json!({ "elicitation": null })).unwrap();
6235 assert!(null.elicitation.is_none());
6236
6237 let malformed: ClientCapabilities =
6238 serde_json::from_value(json!({ "elicitation": false })).unwrap();
6239 assert!(malformed.elicitation.is_none());
6240
6241 let empty: ClientCapabilities =
6242 serde_json::from_value(json!({ "elicitation": {} })).unwrap();
6243 let empty = empty.elicitation.expect("present capability");
6244 assert!(!empty.supports_form());
6245 assert!(!empty.supports_url());
6246
6247 let form_only: ClientCapabilities = serde_json::from_value(json!({
6248 "elicitation": { "form": {} }
6249 }))
6250 .unwrap();
6251 let form_only = form_only.elicitation.expect("advertised capability");
6252 assert!(form_only.supports_form());
6253 assert!(!form_only.supports_url());
6254
6255 let url_only: ClientCapabilities = serde_json::from_value(json!({
6256 "elicitation": { "url": {} }
6257 }))
6258 .unwrap();
6259 let url_only = url_only.elicitation.expect("advertised capability");
6260 assert!(!url_only.supports_form());
6261 assert!(url_only.supports_url());
6262
6263 let both: ClientCapabilities = serde_json::from_value(json!({
6264 "elicitation": { "form": {}, "url": {} }
6265 }))
6266 .unwrap();
6267 let both = both.elicitation.expect("advertised capability");
6268 assert!(both.supports_form());
6269 assert!(both.supports_url());
6270 }
6271
6272 #[test]
6273 fn test_elicitation_method_routing_and_envelopes() {
6274 use serde_json::json;
6275
6276 assert_eq!(CLIENT_METHOD_NAMES.elicitation_create, "elicitation/create");
6277 assert_eq!(
6278 CLIENT_METHOD_NAMES.elicitation_complete,
6279 "elicitation/complete"
6280 );
6281
6282 let request = AgentRequest::CreateElicitationRequest(CreateElicitationRequest::new(
6283 crate::v1::ElicitationFormMode::new(
6284 crate::v1::ElicitationSessionScope::new("sess_1"),
6285 crate::v1::ElicitationSchema::new(),
6286 ),
6287 "Choose a value",
6288 ));
6289 assert_eq!(request.method(), "elicitation/create");
6290 let method = Arc::from(request.method());
6291 let request = crate::v1::JsonRpcMessage::wrap(crate::v1::Request {
6292 id: crate::v1::RequestId::Number(7),
6293 method,
6294 params: Some(request),
6295 });
6296 assert_eq!(
6297 serde_json::to_value(request).unwrap(),
6298 json!({
6299 "jsonrpc": "2.0",
6300 "id": 7,
6301 "method": "elicitation/create",
6302 "params": {
6303 "mode": "form",
6304 "sessionId": "sess_1",
6305 "message": "Choose a value",
6306 "requestedSchema": { "type": "object", "properties": {} }
6307 }
6308 })
6309 );
6310
6311 let notification = AgentNotification::CompleteElicitationNotification(
6312 CompleteElicitationNotification::new("elic_1"),
6313 );
6314 assert_eq!(notification.method(), "elicitation/complete");
6315 let method = Arc::from(notification.method());
6316 let notification = crate::v1::JsonRpcMessage::wrap(crate::v1::Notification {
6317 method,
6318 params: Some(notification),
6319 });
6320 assert_eq!(
6321 serde_json::to_value(notification).unwrap(),
6322 json!({
6323 "jsonrpc": "2.0",
6324 "method": "elicitation/complete",
6325 "params": { "elicitationId": "elic_1" }
6326 })
6327 );
6328 }
6329
6330 #[test]
6331 fn test_client_capabilities_default_on_malformed_values() {
6332 use serde_json::json;
6333
6334 let capabilities: ClientCapabilities = serde_json::from_value(json!({
6335 "fs": {
6336 "readTextFile": "yes",
6337 "writeTextFile": true
6338 },
6339 "terminal": {}
6340 }))
6341 .unwrap();
6342
6343 assert!(!capabilities.fs.read_text_file);
6344 assert!(capabilities.fs.write_text_file);
6345 assert!(!capabilities.terminal);
6346
6347 let capabilities: ClientCapabilities = serde_json::from_value(json!({
6348 "fs": false
6349 }))
6350 .unwrap();
6351 assert_eq!(capabilities.fs, FileSystemCapabilities::default());
6352
6353 {
6354 let capabilities: ClientCapabilities = serde_json::from_value(json!({
6355 "auth": false
6356 }))
6357 .unwrap();
6358 assert_eq!(capabilities.auth, AuthCapabilities::default());
6359
6360 let capabilities: AuthCapabilities = serde_json::from_value(json!({
6361 "terminal": {}
6362 }))
6363 .unwrap();
6364 assert!(!capabilities.terminal);
6365 }
6366 }
6367
6368 #[test]
6369 fn test_serialization_behavior() {
6370 use serde_json::json;
6371
6372 assert_eq!(
6373 serde_json::from_value::<SessionInfoUpdate>(json!({})).unwrap(),
6374 SessionInfoUpdate {
6375 title: MaybeUndefined::Undefined,
6376 updated_at: MaybeUndefined::Undefined,
6377 meta: None
6378 }
6379 );
6380 assert_eq!(
6381 serde_json::from_value::<SessionInfoUpdate>(json!({"title": null, "updatedAt": null}))
6382 .unwrap(),
6383 SessionInfoUpdate {
6384 title: MaybeUndefined::Null,
6385 updated_at: MaybeUndefined::Null,
6386 meta: None
6387 }
6388 );
6389 assert_eq!(
6390 serde_json::from_value::<SessionInfoUpdate>(
6391 json!({"title": "title", "updatedAt": "timestamp"})
6392 )
6393 .unwrap(),
6394 SessionInfoUpdate {
6395 title: MaybeUndefined::Value("title".to_string()),
6396 updated_at: MaybeUndefined::Value("timestamp".to_string()),
6397 meta: None
6398 }
6399 );
6400
6401 assert_eq!(
6402 serde_json::to_value(SessionInfoUpdate::new()).unwrap(),
6403 json!({})
6404 );
6405 assert_eq!(
6406 serde_json::to_value(SessionInfoUpdate::new().title("title")).unwrap(),
6407 json!({"title": "title"})
6408 );
6409 assert_eq!(
6410 serde_json::to_value(SessionInfoUpdate::new().title(None)).unwrap(),
6411 json!({"title": null})
6412 );
6413 assert_eq!(
6414 serde_json::to_value(
6415 SessionInfoUpdate::new()
6416 .title("title")
6417 .title(MaybeUndefined::Undefined)
6418 )
6419 .unwrap(),
6420 json!({})
6421 );
6422 }
6423
6424 #[test]
6425 fn test_content_chunk_message_id_serialization() {
6426 use serde_json::json;
6427
6428 assert_eq!(
6429 serde_json::to_value(SessionUpdate::AgentMessageChunk(ContentChunk::new(
6430 ContentBlock::Text(crate::v1::TextContent::new("Hello"))
6431 )))
6432 .unwrap(),
6433 json!({
6434 "sessionUpdate": "agent_message_chunk",
6435 "content": {
6436 "type": "text",
6437 "text": "Hello"
6438 }
6439 })
6440 );
6441
6442 assert_eq!(
6443 serde_json::to_value(SessionUpdate::AgentMessageChunk(
6444 ContentChunk::new(ContentBlock::Text(crate::v1::TextContent::new("Hello")))
6445 .message_id("msg_agent_c42b9")
6446 ))
6447 .unwrap(),
6448 json!({
6449 "sessionUpdate": "agent_message_chunk",
6450 "messageId": "msg_agent_c42b9",
6451 "content": {
6452 "type": "text",
6453 "text": "Hello"
6454 }
6455 })
6456 );
6457
6458 let SessionUpdate::AgentMessageChunk(chunk) = serde_json::from_value(json!({
6459 "sessionUpdate": "agent_message_chunk",
6460 "messageId": null,
6461 "content": {
6462 "type": "text",
6463 "text": "Hello"
6464 }
6465 }))
6466 .unwrap() else {
6467 panic!("expected agent message chunk");
6468 };
6469
6470 assert_eq!(chunk.message_id, None);
6471 }
6472
6473 #[test]
6474 fn test_usage_update_serialization() {
6475 use serde_json::json;
6476
6477 assert_eq!(
6478 serde_json::to_value(SessionUpdate::UsageUpdate(UsageUpdate::new(
6479 53_000, 200_000
6480 )))
6481 .unwrap(),
6482 json!({
6483 "sessionUpdate": "usage_update",
6484 "used": 53000,
6485 "size": 200_000
6486 })
6487 );
6488
6489 assert_eq!(
6490 serde_json::to_value(SessionUpdate::UsageUpdate(
6491 UsageUpdate::new(53_000, 200_000).cost(Cost::new(0.045, "USD"))
6492 ))
6493 .unwrap(),
6494 json!({
6495 "sessionUpdate": "usage_update",
6496 "used": 53000,
6497 "size": 200_000,
6498 "cost": {
6499 "amount": 0.045,
6500 "currency": "USD"
6501 }
6502 })
6503 );
6504
6505 let SessionUpdate::UsageUpdate(update) = serde_json::from_value(json!({
6506 "sessionUpdate": "usage_update",
6507 "used": 53000,
6508 "size": 200_000,
6509 "cost": null
6510 }))
6511 .unwrap() else {
6512 panic!("expected usage update");
6513 };
6514
6515 assert_eq!(update.cost, None);
6516 }
6517
6518 #[test]
6519 fn test_client_capabilities_boolean_config_options_serialization() {
6520 use serde_json::json;
6521
6522 let capabilities = ClientCapabilities::new().session(
6523 ClientSessionCapabilities::new().config_options(
6524 SessionConfigOptionsCapabilities::new()
6525 .boolean(BooleanConfigOptionCapabilities::new()),
6526 ),
6527 );
6528 let json = serde_json::to_value(&capabilities).unwrap();
6529
6530 assert_eq!(json["session"]["configOptions"]["boolean"], json!({}));
6531
6532 let omitted: ClientCapabilities = serde_json::from_value(json!({})).unwrap();
6533 assert!(omitted.session.is_none());
6534
6535 let null_session: ClientCapabilities = serde_json::from_value(json!({
6536 "session": null
6537 }))
6538 .unwrap();
6539 assert!(null_session.session.is_none());
6540
6541 let null_config_options: ClientCapabilities = serde_json::from_value(json!({
6542 "session": {
6543 "configOptions": null
6544 }
6545 }))
6546 .unwrap();
6547 assert!(
6548 null_config_options
6549 .session
6550 .and_then(|session| session.config_options)
6551 .is_none()
6552 );
6553
6554 let null_boolean: ClientCapabilities = serde_json::from_value(json!({
6555 "session": {
6556 "configOptions": {
6557 "boolean": null
6558 }
6559 }
6560 }))
6561 .unwrap();
6562 assert!(
6563 null_boolean
6564 .session
6565 .and_then(|session| session.config_options)
6566 .and_then(|config_options| config_options.boolean)
6567 .is_none()
6568 );
6569 }
6570
6571 #[test]
6572 fn test_plan_operations_serialization() {
6573 use serde_json::json;
6574
6575 use crate::v1::{PlanEntry, PlanEntryPriority, PlanEntryStatus, PlanUpdateContent};
6576
6577 let plan_update = SessionUpdate::PlanUpdate(PlanUpdate::new(PlanUpdateContent::items(
6578 "plan-1",
6579 vec![PlanEntry::new(
6580 "Step 1",
6581 PlanEntryPriority::High,
6582 PlanEntryStatus::Pending,
6583 )],
6584 )));
6585
6586 assert_eq!(
6587 serde_json::to_value(plan_update).unwrap(),
6588 json!({
6589 "sessionUpdate": "plan_update",
6590 "plan": {
6591 "type": "items",
6592 "planId": "plan-1",
6593 "entries": [
6594 {
6595 "content": "Step 1",
6596 "priority": "high",
6597 "status": "pending"
6598 }
6599 ]
6600 }
6601 })
6602 );
6603
6604 assert_eq!(
6605 serde_json::to_value(SessionUpdate::PlanRemoved(PlanRemoved::new("plan-1"))).unwrap(),
6606 json!({
6607 "sessionUpdate": "plan_removed",
6608 "planId": "plan-1"
6609 })
6610 );
6611
6612 let markdown = json!({
6613 "sessionUpdate": "plan_update",
6614 "plan": {
6615 "type": "markdown", "planId": "plan-1",
6616 "content": "# Next steps", "path": "/workspace/plan.md"
6617 }
6618 });
6619 let update: SessionUpdate = serde_json::from_value(markdown.clone()).unwrap();
6620 assert_eq!(serde_json::to_value(update).unwrap(), markdown);
6621
6622 let capabilities = ClientCapabilities::new().plan(PlanCapabilities::new());
6623 let json = serde_json::to_value(&capabilities).unwrap();
6624 assert_eq!(json["plan"], json!({}));
6625
6626 assert_eq!(
6627 serde_json::from_value::<ClientCapabilities>(json!({ "plan": null }))
6628 .unwrap()
6629 .plan,
6630 None
6631 );
6632 }
6633
6634 #[cfg(feature = "unstable_mcp_over_acp")]
6635 #[test]
6636 fn test_agent_mcp_request_method_names() {
6637 use serde_json::json;
6638
6639 let params: serde_json::Map<String, serde_json::Value> =
6640 [("cursor".to_string(), json!("abc"))].into_iter().collect();
6641
6642 assert_eq!(CLIENT_METHOD_NAMES.mcp_message, "mcp/message");
6643 assert_eq!(
6644 AgentRequest::MessageMcpRequest(MessageMcpRequest::new(
6645 "server-1",
6646 "req-1",
6647 "tools/list"
6648 ))
6649 .method(),
6650 "mcp/message"
6651 );
6652 assert_eq!(
6653 serde_json::to_value(
6654 MessageMcpRequest::new("server-1", "req-1", "tools/list").params(params)
6655 )
6656 .unwrap(),
6657 json!({
6658 "serverId": "server-1",
6659 "requestId": "req-1",
6660 "method": "tools/list",
6661 "params": { "cursor": "abc" }
6662 })
6663 );
6664
6665 let request_with_null_params: MessageMcpRequest = serde_json::from_value(json!({
6666 "serverId": "server-1",
6667 "requestId": "req-1",
6668 "method": "tools/list",
6669 "params": null,
6670 "_meta": null
6671 }))
6672 .unwrap();
6673 assert_eq!(request_with_null_params.params, None);
6674 assert_eq!(request_with_null_params.meta, None);
6675 for key in ["serverId", "requestId", "method"] {
6676 let mut value =
6677 json!({"serverId":"server-1", "requestId":"req-1", "method":"tools/list"});
6678 value.as_object_mut().unwrap().remove(key);
6679 assert!(serde_json::from_value::<MessageMcpRequest>(value).is_err());
6680 }
6681 for key in ["serverId", "requestId", "method"] {
6682 let mut value =
6683 json!({"serverId":"server-1", "requestId":"req-1", "method":"tools/list"});
6684 value[key] = serde_json::Value::Null;
6685 assert!(serde_json::from_value::<MessageMcpRequest>(value).is_err());
6686 }
6687 }
6688
6689 #[test]
6690 fn request_permission_request_rejects_malformed_options() {
6691 use serde_json::json;
6692
6693 assert!(
6694 serde_json::from_value::<RequestPermissionRequest>(json!({
6695 "sessionId": "sess-1",
6696 "toolCall": {"toolCallId": "tc-1"},
6697 "options": "not-an-array"
6698 }))
6699 .is_err()
6700 );
6701 assert!(
6702 serde_json::from_value::<RequestPermissionRequest>(json!({
6703 "sessionId": "sess-1",
6704 "toolCall": {"toolCallId": "tc-1"},
6705 "options": [{"optionId": "allow"}]
6706 }))
6707 .is_err()
6708 );
6709 }
6710
6711 #[test]
6712 fn create_terminal_request_rejects_malformed_fields() {
6713 use serde_json::json;
6714
6715 let request = |field: &str, value: serde_json::Value| {
6716 let mut request = json!({"sessionId": "sess-1", "command": "npx"});
6717 request[field] = value;
6718 serde_json::from_value::<CreateTerminalRequest>(request)
6719 };
6720
6721 for (field, value) in [
6723 ("args", json!(["serve", "--port", 3000])),
6724 ("args", json!("serve --port 3000")),
6725 ("env", json!([{"name": "PORT", "value": 3000}])),
6726 ("env", json!({"PORT": "3000"})),
6727 ("cwd", json!({"path": "/repo"})),
6728 ("outputByteLimit", json!("1048576")),
6729 ] {
6730 assert!(request(field, value.clone()).is_err(), "{field}: {value}");
6731 }
6732
6733 for field in ["args", "env", "cwd", "outputByteLimit"] {
6734 assert_eq!(
6735 request(field, serde_json::Value::Null).unwrap(),
6736 CreateTerminalRequest::new("sess-1", "npx"),
6737 "{field}"
6738 );
6739 }
6740 }
6741
6742 #[test]
6743 fn read_text_file_request_rejects_malformed_range() {
6744 use serde_json::json;
6745
6746 let request = |field: &str, value: serde_json::Value| {
6747 let mut request = json!({"sessionId": "sess-1", "path": "/repo/src/main.rs"});
6748 request[field] = value;
6749 serde_json::from_value::<ReadTextFileRequest>(request)
6750 };
6751
6752 for field in ["line", "limit"] {
6754 assert!(request(field, json!("120")).is_err(), "{field}");
6755 assert!(request(field, json!(-1)).is_err(), "{field}");
6756 assert_eq!(
6757 request(field, serde_json::Value::Null).unwrap(),
6758 ReadTextFileRequest::new("sess-1", "/repo/src/main.rs"),
6759 "{field}"
6760 );
6761 }
6762 }
6763
6764 #[cfg(feature = "unstable_session_cursors")]
6765 #[test]
6766 fn cursor_updates_round_trip_and_patch_capabilities() {
6767 use serde_json::json;
6768
6769 let update = SessionUpdate::CursorUpdate(
6770 CursorUpdate::new("cur_1")
6771 .capabilities(CursorCapabilities::new())
6772 .anchor(CursorAnchor::UserMessage(CursorMessageAnchor::new(
6773 "msg_user_2",
6774 CursorAnchorPosition::Before,
6775 ))),
6776 );
6777 let wire = json!({
6778 "sessionUpdate": "cursor_update",
6779 "cursorId": "cur_1",
6780 "capabilities": {},
6781 "anchor": { "type": "user_message", "messageId": "msg_user_2", "position": "before" }
6782 });
6783 assert_eq!(serde_json::to_value(&update).unwrap(), wire);
6784 assert_eq!(
6785 serde_json::from_value::<SessionUpdate>(wire).unwrap(),
6786 update
6787 );
6788
6789 let SessionUpdate::CursorUpdate(omitted) = serde_json::from_value(json!({
6791 "sessionUpdate": "cursor_update",
6792 "cursorId": "cur_1"
6793 }))
6794 .unwrap() else {
6795 panic!("expected cursor update");
6796 };
6797 assert!(omitted.capabilities.is_undefined());
6798 assert_eq!(omitted.anchor, None);
6799 assert!(omitted.meta.is_undefined());
6800 assert_eq!(
6801 serde_json::to_value(SessionUpdate::CursorUpdate(CursorUpdate::new("cur_1"))).unwrap(),
6802 json!({ "sessionUpdate": "cursor_update", "cursorId": "cur_1" })
6803 );
6804
6805 let SessionUpdate::CursorUpdate(cleared) = serde_json::from_value(json!({
6807 "sessionUpdate": "cursor_update",
6808 "cursorId": "cur_1",
6809 "capabilities": null,
6810 "anchor": null
6811 }))
6812 .unwrap() else {
6813 panic!("expected cursor update");
6814 };
6815 assert!(cleared.capabilities.is_null());
6816 assert_eq!(cleared.anchor, None);
6817 assert_eq!(
6818 serde_json::to_value(SessionUpdate::CursorUpdate(
6819 CursorUpdate::new("cur_1").capabilities(None)
6820 ))
6821 .unwrap(),
6822 json!({ "sessionUpdate": "cursor_update", "cursorId": "cur_1", "capabilities": null })
6823 );
6824 }
6825
6826 #[cfg(feature = "unstable_session_cursors")]
6827 #[test]
6828 fn cursor_anchors_cover_each_entity_type_and_preserve_unknown_ones() {
6829 use serde_json::json;
6830
6831 for (anchor, wire) in [
6832 (
6833 CursorAnchor::AgentMessage(CursorMessageAnchor::new(
6834 "msg_agent_1",
6835 CursorAnchorPosition::After,
6836 )),
6837 json!({ "type": "agent_message", "messageId": "msg_agent_1", "position": "after" }),
6838 ),
6839 (
6840 CursorAnchor::AgentThought(CursorMessageAnchor::new(
6841 "msg_agent_1",
6842 CursorAnchorPosition::After,
6843 )),
6844 json!({ "type": "agent_thought", "messageId": "msg_agent_1", "position": "after" }),
6845 ),
6846 (
6847 CursorAnchor::SessionMessage(CursorMessageAnchor::new(
6848 "msg_session_1",
6849 CursorAnchorPosition::Before,
6850 )),
6851 json!({ "type": "session_message", "messageId": "msg_session_1", "position": "before" }),
6852 ),
6853 (
6854 CursorAnchor::ToolCall(CursorToolCallAnchor::new(
6855 "call_1",
6856 CursorAnchorPosition::After,
6857 )),
6858 json!({ "type": "tool_call", "toolCallId": "call_1", "position": "after" }),
6859 ),
6860 (
6861 CursorAnchor::Compaction(CursorCompactionAnchor::new(
6862 "cmp_1",
6863 CursorAnchorPosition::Before,
6864 )),
6865 json!({ "type": "compaction", "compactionId": "cmp_1", "position": "before" }),
6866 ),
6867 ] {
6868 assert_eq!(serde_json::to_value(&anchor).unwrap(), wire);
6869 assert_eq!(
6870 serde_json::from_value::<CursorAnchor>(wire).unwrap(),
6871 anchor
6872 );
6873 }
6874
6875 let wire = json!({ "type": "_acme_marker", "markerId": "mk_1", "position": "after" });
6877 let other = serde_json::from_value::<CursorAnchor>(wire.clone()).unwrap();
6878 assert!(matches!(other, CursorAnchor::Other(_)));
6879 assert_eq!(serde_json::to_value(&other).unwrap(), wire);
6880
6881 let wire =
6883 json!({ "type": "user_message", "messageId": "msg_user_2", "position": "inside" });
6884 let future = serde_json::from_value::<CursorAnchor>(wire.clone()).unwrap();
6885 assert_eq!(
6886 future,
6887 CursorAnchor::UserMessage(CursorMessageAnchor::new(
6888 "msg_user_2",
6889 CursorAnchorPosition::Other("inside".into()),
6890 ))
6891 );
6892 assert_eq!(serde_json::to_value(&future).unwrap(), wire);
6893 }
6894
6895 #[cfg(feature = "unstable_session_cursors")]
6896 #[test]
6897 fn malformed_cursor_anchor_fails_the_update() {
6898 use serde_json::json;
6899
6900 for anchor in [
6902 json!({ "type": "user_message", "position": "before" }),
6903 json!({ "type": "tool_call", "toolCallId": 7, "position": "after" }),
6904 json!({ "type": "compaction", "compactionId": "cmp_1" }),
6905 json!({ "messageId": "msg_user_2", "position": "before" }),
6906 json!("before"),
6907 ] {
6908 assert!(
6909 serde_json::from_value::<SessionUpdate>(json!({
6910 "sessionUpdate": "cursor_update",
6911 "cursorId": "cur_1",
6912 "anchor": anchor
6913 }))
6914 .is_err(),
6915 "{anchor}"
6916 );
6917 }
6918 assert!(
6919 serde_json::from_value::<SessionUpdate>(json!({ "sessionUpdate": "cursor_update" }))
6920 .is_err()
6921 );
6922 }
6923
6924 #[cfg(feature = "unstable_session_cursors")]
6925 #[test]
6926 fn malformed_cursor_capabilities_are_not_advertised() {
6927 use serde_json::json;
6928
6929 let SessionUpdate::CursorUpdate(update) = serde_json::from_value(json!({
6931 "sessionUpdate": "cursor_update",
6932 "cursorId": "cur_1",
6933 "capabilities": "fork"
6934 }))
6935 .unwrap() else {
6936 panic!("expected cursor update");
6937 };
6938 assert!(update.capabilities.is_undefined());
6939
6940 assert_eq!(
6942 serde_json::from_value::<CursorCapabilities>(json!({ "futureMethod": {} })).unwrap(),
6943 CursorCapabilities::new()
6944 );
6945
6946 #[cfg(feature = "unstable_session_fork")]
6947 {
6948 assert_eq!(
6949 serde_json::to_value(CursorCapabilities::new().fork(CursorForkCapabilities::new()))
6950 .unwrap(),
6951 json!({ "fork": {} })
6952 );
6953 assert_eq!(
6954 serde_json::from_value::<CursorCapabilities>(json!({ "fork": {} }))
6955 .unwrap()
6956 .fork,
6957 Some(CursorForkCapabilities::new())
6958 );
6959 for fork in [json!(null), json!(true), json!("yes")] {
6960 assert_eq!(
6961 serde_json::from_value::<CursorCapabilities>(json!({ "fork": fork }))
6962 .unwrap()
6963 .fork,
6964 None
6965 );
6966 }
6967 }
6968 }
6969
6970 #[cfg(feature = "unstable_session_cursors")]
6971 #[test]
6972 fn client_session_cursors_capability_is_optional_and_lenient() {
6973 use serde_json::json;
6974
6975 assert_eq!(
6976 serde_json::to_value(
6977 ClientSessionCapabilities::new().cursors(SessionCursorsCapabilities::new())
6978 )
6979 .unwrap(),
6980 json!({ "cursors": {} })
6981 );
6982 assert_eq!(
6983 serde_json::from_value::<ClientSessionCapabilities>(json!({ "cursors": {} }))
6984 .unwrap()
6985 .cursors,
6986 Some(SessionCursorsCapabilities::new())
6987 );
6988 for wire in [
6989 json!({}),
6990 json!({ "cursors": null }),
6991 json!({ "cursors": "yes" }),
6992 ] {
6993 assert_eq!(
6994 serde_json::from_value::<ClientSessionCapabilities>(wire)
6995 .unwrap()
6996 .cursors,
6997 None
6998 );
6999 }
7000 }
7001}