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]
4885#[allow(clippy::large_enum_variant)]
4886pub enum AgentRequest {
4887 WriteTextFileRequest(WriteTextFileRequest),
4894 ReadTextFileRequest(ReadTextFileRequest),
4901 RequestPermissionRequest(RequestPermissionRequest),
4912 CreateTerminalRequest(CreateTerminalRequest),
4927 TerminalOutputRequest(TerminalOutputRequest),
4934 ReleaseTerminalRequest(ReleaseTerminalRequest),
4947 WaitForTerminalExitRequest(WaitForTerminalExitRequest),
4951 KillTerminalRequest(KillTerminalRequest),
4964 CreateElicitationRequest(CreateElicitationRequest),
4968 #[cfg(feature = "unstable_mcp_over_acp")]
4974 MessageMcpRequest(MessageMcpRequest),
4975 ExtMethodRequest(ExtRequest),
4983}
4984
4985impl_request_dispatch! {
4986 AgentRequest => ClientResponse {
4987 WriteTextFileRequest => WriteTextFileResponse: CLIENT_METHOD_NAMES.fs_write_text_file,
4988 ReadTextFileRequest => ReadTextFileResponse: CLIENT_METHOD_NAMES.fs_read_text_file,
4989 RequestPermissionRequest => RequestPermissionResponse: CLIENT_METHOD_NAMES.session_request_permission,
4990 CreateTerminalRequest => CreateTerminalResponse: CLIENT_METHOD_NAMES.terminal_create,
4991 TerminalOutputRequest => TerminalOutputResponse: CLIENT_METHOD_NAMES.terminal_output,
4992 ReleaseTerminalRequest => ReleaseTerminalResponse: CLIENT_METHOD_NAMES.terminal_release,
4993 WaitForTerminalExitRequest => WaitForTerminalExitResponse: CLIENT_METHOD_NAMES.terminal_wait_for_exit,
4994 KillTerminalRequest => KillTerminalResponse: CLIENT_METHOD_NAMES.terminal_kill,
4995 CreateElicitationRequest => CreateElicitationResponse: CLIENT_METHOD_NAMES.elicitation_create,
4996 #[cfg(feature = "unstable_mcp_over_acp")]
4997 MessageMcpRequest => MessageMcpResponse: CLIENT_METHOD_NAMES.mcp_message,
4998 }
4999 extension ExtMethodRequest(ExtRequest) => ExtMethodResponse;
5000}
5001
5002#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5009#[derive(Clone, Debug, Serialize, Deserialize)]
5010#[serde(untagged)]
5011#[cfg_attr(feature = "schemars", schemars(inline))]
5012#[non_exhaustive]
5013pub enum ClientResponse {
5014 WriteTextFileResponse(#[serde(default)] WriteTextFileResponse),
5016 ReadTextFileResponse(ReadTextFileResponse),
5018 RequestPermissionResponse(RequestPermissionResponse),
5020 CreateTerminalResponse(CreateTerminalResponse),
5022 TerminalOutputResponse(TerminalOutputResponse),
5024 ReleaseTerminalResponse(#[serde(default)] ReleaseTerminalResponse),
5026 WaitForTerminalExitResponse(WaitForTerminalExitResponse),
5028 KillTerminalResponse(#[serde(default)] KillTerminalResponse),
5030 CreateElicitationResponse(CreateElicitationResponse),
5032 #[cfg(feature = "unstable_mcp_over_acp")]
5034 MessageMcpResponse(MessageMcpResponse),
5035 ExtMethodResponse(ExtResponse),
5037}
5038
5039#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5046#[derive(Clone, Debug, Serialize, Deserialize)]
5047#[serde(untagged)]
5048#[expect(clippy::large_enum_variant)]
5049#[cfg_attr(feature = "schemars", schemars(inline))]
5050#[non_exhaustive]
5051pub enum AgentNotification {
5052 SessionNotification(SessionNotification),
5064 CompleteElicitationNotification(CompleteElicitationNotification),
5068 #[cfg(feature = "unstable_auth_status")]
5076 AuthStatusUpdateNotification(AuthStatusUpdateNotification),
5077 ExtNotification(ExtNotification),
5085}
5086
5087impl_message_dispatch! {
5088 AgentNotification {
5089 SessionNotification => CLIENT_METHOD_NAMES.session_update,
5090 CompleteElicitationNotification => CLIENT_METHOD_NAMES.elicitation_complete,
5091 #[cfg(feature = "unstable_auth_status")]
5092 AuthStatusUpdateNotification => CLIENT_METHOD_NAMES.auth_status_update,
5093 }
5094 extension ExtNotification(ExtNotification);
5095}
5096
5097#[cfg(test)]
5098mod tests {
5099 use super::*;
5100
5101 #[test]
5102 fn notice_preserves_wire_shape_nullable_fields_and_open_severity() {
5103 use serde_json::json;
5104
5105 let mut meta = Meta::new();
5106 meta.insert("source".into(), json!("fallback"));
5107 assert_eq!(
5108 serde_json::to_value(SessionUpdate::Notice(
5109 Notice::new(NoticeSeverity::Warning, "MCP server unavailable")
5110 .description("Continuing without it.")
5111 .meta(meta),
5112 ))
5113 .unwrap(),
5114 json!({
5115 "sessionUpdate": "notice",
5116 "severity": "warning",
5117 "title": "MCP server unavailable",
5118 "description": "Continuing without it.",
5119 "_meta": { "source": "fallback" }
5120 })
5121 );
5122
5123 assert_eq!(
5124 serde_json::to_value(SessionUpdate::Notice(Notice::new(
5125 NoticeSeverity::Info,
5126 "Indexing workspace",
5127 )))
5128 .unwrap(),
5129 json!({
5130 "sessionUpdate": "notice",
5131 "severity": "info",
5132 "title": "Indexing workspace"
5133 })
5134 );
5135
5136 let SessionUpdate::Notice(notice) = serde_json::from_value(json!({
5137 "sessionUpdate": "notice",
5138 "severity": "critical",
5139 "title": "Provider degraded",
5140 "description": null,
5141 "_meta": null
5142 }))
5143 .unwrap() else {
5144 panic!("expected notice");
5145 };
5146
5147 assert_eq!(
5148 notice.severity,
5149 NoticeSeverity::Other("critical".to_string())
5150 );
5151 assert_eq!(notice.description, None);
5152 assert_eq!(notice.meta, None);
5153 assert_eq!(
5154 serde_json::to_value(SessionUpdate::Notice(notice)).unwrap(),
5155 json!({
5156 "sessionUpdate": "notice",
5157 "severity": "critical",
5158 "title": "Provider degraded"
5159 })
5160 );
5161 }
5162
5163 #[test]
5164 fn notice_requires_string_severity_and_title() {
5165 use serde_json::json;
5166
5167 for malformed in [
5168 json!({
5169 "sessionUpdate": "notice",
5170 "severity": "warning",
5171 "title": 42
5172 }),
5173 json!({
5174 "sessionUpdate": "notice",
5175 "severity": 42,
5176 "title": "MCP server unavailable"
5177 }),
5178 json!({
5179 "sessionUpdate": "notice",
5180 "severity": "warning"
5181 }),
5182 json!({
5183 "sessionUpdate": "notice",
5184 "severity": "warning",
5185 "title": null
5186 }),
5187 json!({
5188 "sessionUpdate": "notice",
5189 "title": "MCP server unavailable"
5190 }),
5191 json!({
5192 "sessionUpdate": "notice",
5193 "severity": null,
5194 "title": "MCP server unavailable"
5195 }),
5196 ] {
5197 assert!(serde_json::from_str::<SessionUpdate>(&malformed.to_string()).is_err());
5198 assert!(serde_json::from_value::<SessionUpdate>(malformed).is_err());
5199 }
5200 }
5201
5202 #[test]
5203 fn notice_tolerates_invalid_optional_display_fields_and_custom_severity() {
5204 use serde_json::json;
5205
5206 let wire = json!({
5207 "sessionUpdate": "notice",
5208 "severity": "_custom",
5209 "title": "Provider degraded",
5210 "description": 42,
5211 "_meta": false
5212 });
5213 let SessionUpdate::Notice(notice) = serde_json::from_value(wire.clone()).unwrap() else {
5214 panic!("expected notice");
5215 };
5216 assert_eq!(
5218 serde_json::from_str::<SessionUpdate>(&wire.to_string()).unwrap(),
5219 SessionUpdate::Notice(notice.clone())
5220 );
5221 assert_eq!(notice.severity, NoticeSeverity::Other("_custom".into()));
5222 assert_eq!(notice.description, None);
5223 assert_eq!(notice.meta, None);
5224 assert_eq!(
5225 serde_json::to_value(notice).unwrap(),
5226 json!({"severity": "_custom", "title": "Provider degraded"})
5227 );
5228 }
5229
5230 #[cfg(feature = "schemars")]
5231 #[test]
5232 fn notice_schema_preserves_required_and_nullable_fields() {
5233 use serde_json::json;
5234
5235 let schema = serde_json::to_value(schemars::schema_for!(Notice)).unwrap();
5236 assert_eq!(schema["required"], json!(["severity", "title"]));
5237 assert_eq!(schema["properties"]["title"]["minLength"], 1);
5238 for field in ["description", "_meta"] {
5239 assert!(
5240 schema["properties"][field]["type"]
5241 .as_array()
5242 .unwrap()
5243 .contains(&json!("null"))
5244 );
5245 }
5246 let capabilities =
5247 serde_json::to_value(schemars::schema_for!(ClientSessionCapabilities)).unwrap();
5248 assert!(
5249 capabilities["properties"]["notices"]["anyOf"]
5250 .as_array()
5251 .unwrap()
5252 .contains(&json!({"type": "null"}))
5253 );
5254 assert!(
5255 !capabilities["required"]
5256 .as_array()
5257 .is_some_and(|required| required.contains(&json!("notices")))
5258 );
5259 }
5260
5261 #[test]
5262 fn notice_capability_advertises_support_only_when_present() {
5263 use serde_json::json;
5264
5265 let capabilities = ClientCapabilities::new()
5266 .session(ClientSessionCapabilities::new().notices(NoticeCapabilities::new()));
5267 let value = serde_json::to_value(&capabilities).unwrap();
5268 assert_eq!(value["session"], json!({ "notices": {} }));
5269 assert_eq!(
5270 serde_json::from_value::<ClientCapabilities>(value).unwrap(),
5271 capabilities
5272 );
5273
5274 for unsupported in [
5275 json!({}),
5276 json!({ "session": null }),
5277 json!({ "session": {} }),
5278 json!({ "session": { "notices": null } }),
5279 json!({ "session": { "notices": false } }),
5280 json!({ "session": { "notices": true } }),
5281 json!({ "session": { "notices": "supported" } }),
5282 ] {
5283 let capabilities: ClientCapabilities = serde_json::from_value(unsupported).unwrap();
5284 assert!(
5285 capabilities
5286 .session
5287 .and_then(|session| session.notices)
5288 .is_none()
5289 );
5290 }
5291
5292 assert_eq!(
5293 serde_json::to_value(
5294 ClientSessionCapabilities::new()
5295 .notices(NoticeCapabilities::new())
5296 .notices(None)
5297 )
5298 .unwrap(),
5299 json!({})
5300 );
5301 }
5302
5303 #[cfg(feature = "unstable_prompt_suggestions")]
5304 #[test]
5305 fn prompt_suggestions_update_round_trips_prompt_content_and_meta() {
5306 use crate::v1::{ResourceLink, TextContent};
5307 use serde_json::json;
5308
5309 let mut meta = Meta::new();
5310 meta.insert("rank".into(), json!(1));
5311 let update = SessionUpdate::PromptSuggestionsUpdate(PromptSuggestionsUpdate::new(vec![
5312 PromptSuggestion::new(vec![ContentBlock::Text(TextContent::new(
5313 "Run the test suite and fix what breaks",
5314 ))])
5315 .meta(meta),
5316 PromptSuggestion::new(vec![
5317 ContentBlock::Text(TextContent::new("Add tests for ")),
5318 ContentBlock::ResourceLink(ResourceLink::new(
5319 "parser.rs",
5320 "file:///home/user/project/src/parser.rs",
5321 )),
5322 ]),
5323 ]));
5324 let wire = json!({
5325 "sessionUpdate": "prompt_suggestions_update",
5326 "suggestions": [
5327 {
5328 "prompt": [
5329 { "type": "text", "text": "Run the test suite and fix what breaks" }
5330 ],
5331 "_meta": { "rank": 1 }
5332 },
5333 {
5334 "prompt": [
5335 { "type": "text", "text": "Add tests for " },
5336 {
5337 "type": "resource_link",
5338 "name": "parser.rs",
5339 "uri": "file:///home/user/project/src/parser.rs"
5340 }
5341 ]
5342 }
5343 ]
5344 });
5345 assert_eq!(serde_json::to_value(&update).unwrap(), wire);
5346 assert_eq!(
5347 serde_json::from_value::<SessionUpdate>(wire).unwrap(),
5348 update
5349 );
5350 }
5351
5352 #[cfg(feature = "unstable_prompt_suggestions")]
5353 #[test]
5354 fn prompt_suggestions_update_with_an_empty_list_withdraws_suggestions() {
5355 use serde_json::json;
5356
5357 let update = SessionUpdate::PromptSuggestionsUpdate(PromptSuggestionsUpdate::new(vec![]));
5358 let wire = json!({
5359 "sessionUpdate": "prompt_suggestions_update",
5360 "suggestions": []
5361 });
5362 assert_eq!(serde_json::to_value(&update).unwrap(), wire);
5363 assert_eq!(
5364 serde_json::from_value::<SessionUpdate>(wire).unwrap(),
5365 update
5366 );
5367
5368 for malformed in [json!(null), json!("none"), json!({ "prompt": [] })] {
5370 assert!(
5371 serde_json::from_value::<SessionUpdate>(json!({
5372 "sessionUpdate": "prompt_suggestions_update",
5373 "suggestions": malformed
5374 }))
5375 .is_err()
5376 );
5377 }
5378 assert!(
5379 serde_json::from_value::<SessionUpdate>(json!({
5380 "sessionUpdate": "prompt_suggestions_update"
5381 }))
5382 .is_err()
5383 );
5384 }
5385
5386 #[cfg(feature = "unstable_prompt_suggestions")]
5387 #[test]
5388 fn prompt_suggestions_update_skips_whole_suggestions_it_cannot_parse() {
5389 use crate::v1::TextContent;
5390 use serde_json::json;
5391
5392 let text =
5393 |text: &str| PromptSuggestion::new(vec![ContentBlock::Text(TextContent::new(text))]);
5394
5395 let update: SessionUpdate = serde_json::from_value(json!({
5398 "sessionUpdate": "prompt_suggestions_update",
5399 "suggestions": [
5400 { "prompt": [{ "type": "text", "text": "Keep the first" }] },
5401 { "text": "A suggestion without a prompt" },
5402 { "prompt": "Not a list" },
5403 { "prompt": [{ "type": "text", "text": "Open " }, { "type": "text" }] },
5404 { "prompt": [{ "type": "hologram", "data": "AAAA" }] },
5405 "not an object",
5406 { "prompt": [{ "type": "text", "text": "Keep the last" }], "_meta": false }
5407 ]
5408 }))
5409 .unwrap();
5410
5411 assert_eq!(
5412 update,
5413 SessionUpdate::PromptSuggestionsUpdate(PromptSuggestionsUpdate::new(vec![
5414 text("Keep the first"),
5415 text("Keep the last"),
5416 ]))
5417 );
5418 }
5419
5420 #[cfg(feature = "unstable_prompt_suggestions")]
5421 #[test]
5422 fn prompt_suggestions_capability_advertises_support_and_content_types() {
5423 use serde_json::json;
5424
5425 let capabilities = ClientCapabilities::new().session(
5426 ClientSessionCapabilities::new()
5427 .prompt_suggestions(PromptSuggestionsCapabilities::new()),
5428 );
5429 let value = serde_json::to_value(&capabilities).unwrap();
5430 assert_eq!(value["session"], json!({ "promptSuggestions": {} }));
5431 assert_eq!(
5432 serde_json::from_value::<ClientCapabilities>(value).unwrap(),
5433 capabilities
5434 );
5435
5436 let content_types = PromptSuggestionsCapabilities::new()
5437 .image(PromptSuggestionsImageCapabilities::new())
5438 .audio(PromptSuggestionsAudioCapabilities::new())
5439 .embedded_context(PromptSuggestionsEmbeddedContextCapabilities::new());
5440 let wire = json!({ "image": {}, "audio": {}, "embeddedContext": {} });
5441 assert_eq!(serde_json::to_value(&content_types).unwrap(), wire);
5442 assert_eq!(
5443 serde_json::from_value::<PromptSuggestionsCapabilities>(wire).unwrap(),
5444 content_types
5445 );
5446
5447 for unsupported in [
5448 json!({}),
5449 json!({ "session": null }),
5450 json!({ "session": {} }),
5451 json!({ "session": { "promptSuggestions": null } }),
5452 json!({ "session": { "promptSuggestions": false } }),
5453 json!({ "session": { "promptSuggestions": true } }),
5454 json!({ "session": { "promptSuggestions": "supported" } }),
5455 ] {
5456 let capabilities: ClientCapabilities = serde_json::from_value(unsupported).unwrap();
5457 assert!(
5458 capabilities
5459 .session
5460 .and_then(|session| session.prompt_suggestions)
5461 .is_none()
5462 );
5463 }
5464
5465 assert_eq!(
5468 serde_json::from_value::<PromptSuggestionsCapabilities>(json!({
5469 "image": true,
5470 "audio": null,
5471 "embeddedContext": {}
5472 }))
5473 .unwrap(),
5474 PromptSuggestionsCapabilities::new()
5475 .embedded_context(PromptSuggestionsEmbeddedContextCapabilities::new())
5476 );
5477 }
5478
5479 #[cfg(all(feature = "schemars", feature = "unstable_prompt_suggestions"))]
5480 #[test]
5481 fn prompt_suggestions_schema_requires_the_list_and_a_non_empty_prompt() {
5482 use serde_json::json;
5483
5484 let update = serde_json::to_value(schemars::schema_for!(PromptSuggestionsUpdate)).unwrap();
5485 assert_eq!(update["required"], json!(["suggestions"]));
5486 assert_eq!(update["properties"]["suggestions"]["type"], "array");
5487
5488 let suggestion = serde_json::to_value(schemars::schema_for!(PromptSuggestion)).unwrap();
5489 assert_eq!(suggestion["required"], json!(["prompt"]));
5490 assert_eq!(suggestion["properties"]["prompt"]["type"], "array");
5491 assert_eq!(suggestion["properties"]["prompt"]["minItems"], 1);
5492
5493 let capabilities =
5494 serde_json::to_value(schemars::schema_for!(ClientSessionCapabilities)).unwrap();
5495 assert!(
5496 capabilities["properties"]["promptSuggestions"]["anyOf"]
5497 .as_array()
5498 .unwrap()
5499 .contains(&json!({"type": "null"}))
5500 );
5501 assert!(
5502 !capabilities["required"]
5503 .as_array()
5504 .is_some_and(|required| required.contains(&json!("promptSuggestions")))
5505 );
5506
5507 let content_types =
5508 serde_json::to_value(schemars::schema_for!(PromptSuggestionsCapabilities)).unwrap();
5509 assert!(content_types.get("required").is_none());
5510 for field in ["image", "audio", "embeddedContext"] {
5511 assert!(
5512 content_types["properties"][field]["anyOf"]
5513 .as_array()
5514 .unwrap()
5515 .contains(&json!({"type": "null"}))
5516 );
5517 }
5518 }
5519
5520 #[test]
5521 fn compaction_updates_preserve_patch_and_open_status_semantics() {
5522 use serde_json::json;
5523
5524 assert_eq!(
5525 serde_json::to_value(SessionUpdate::CompactionUpdate(CompactionUpdate::new(
5526 "cmp_001",
5527 CompactionStatus::InProgress,
5528 )))
5529 .unwrap(),
5530 json!({
5531 "sessionUpdate": "compaction_update",
5532 "compactionId": "cmp_001",
5533 "status": "in_progress"
5534 })
5535 );
5536
5537 let SessionUpdate::CompactionUpdate(update) = serde_json::from_value(json!({
5538 "sessionUpdate": "compaction_update",
5539 "compactionId": "cmp_001",
5540 "status": "paused",
5541 "summary": null,
5542 "error": null
5543 }))
5544 .unwrap() else {
5545 panic!("expected compaction update");
5546 };
5547 assert_eq!(update.status, CompactionStatus::Other("paused".into()));
5548 assert!(update.summary.is_null());
5549 assert!(update.error.is_null());
5550 assert!(update.meta.is_undefined());
5551 }
5552
5553 #[test]
5554 fn compaction_chunk_and_v1_capability_serialize() {
5555 use serde_json::json;
5556
5557 assert_eq!(
5558 serde_json::to_value(SessionUpdate::CompactionSummaryChunk(
5559 CompactionSummaryChunk::new(
5560 "cmp_001",
5561 ContentBlock::Text(crate::v1::TextContent::new("retained")),
5562 ),
5563 ))
5564 .unwrap(),
5565 json!({
5566 "sessionUpdate": "compaction_summary_chunk",
5567 "compactionId": "cmp_001",
5568 "content": { "type": "text", "text": "retained" }
5569 })
5570 );
5571 assert_eq!(
5572 serde_json::to_value(
5573 ClientSessionCapabilities::new().compaction(CompactionCapabilities::new())
5574 )
5575 .unwrap(),
5576 json!({ "compaction": {} })
5577 );
5578 let absent: ClientSessionCapabilities = serde_json::from_value(json!({})).unwrap();
5579 let null: ClientSessionCapabilities =
5580 serde_json::from_value(json!({ "compaction": null })).unwrap();
5581 assert!(absent.compaction.is_none());
5582 assert!(null.compaction.is_none());
5583 }
5584
5585 #[test]
5586 fn test_subagent_updates_serialization() {
5587 use serde_json::json;
5588
5589 let announced = SessionUpdate::SubagentUpdate(SubagentUpdate::new("sess_child_1"));
5590 assert_eq!(
5591 serde_json::to_value(&announced).unwrap(),
5592 json!({
5593 "sessionUpdate": "subagent_update",
5594 "sessionId": "sess_child_1"
5595 })
5596 );
5597 assert_eq!(
5598 serde_json::from_value::<SessionUpdate>(serde_json::to_value(&announced).unwrap())
5599 .unwrap(),
5600 announced
5601 );
5602 let capable = SubagentUpdate::new("sess_child_1").capabilities(
5603 SubagentSessionCapabilities::new().cancel(SessionCancelCapabilities::new()),
5604 );
5605 assert_eq!(
5606 serde_json::to_value(capable).unwrap(),
5607 json!({
5608 "sessionId": "sess_child_1",
5609 "capabilities": {"cancel": {}}
5610 })
5611 );
5612 let minimal: SubagentUpdate =
5613 serde_json::from_value(json!({ "sessionId": "sess_child_3" })).unwrap();
5614 assert!(minimal.capabilities.is_undefined());
5615 assert!(minimal.state.is_undefined());
5616
5617 let nulls: SubagentUpdate = serde_json::from_value(json!({
5618 "sessionId": "sess_child_3",
5619 "capabilities": null,
5620 "state": null
5621 }))
5622 .unwrap();
5623 assert!(nulls.capabilities.is_null());
5624 assert!(nulls.state.is_null());
5625 assert_eq!(
5626 serde_json::to_value(nulls).unwrap(),
5627 json!({"sessionId": "sess_child_3", "capabilities": null, "state": null})
5628 );
5629 }
5630
5631 #[test]
5632 fn test_subagent_display_metadata() {
5633 use serde_json::json;
5634
5635 let update = SubagentUpdate::new("child")
5636 .title("Test investigator".to_string())
5637 .description("Investigates platform-specific test failures.".to_string());
5638 let wire = json!({
5639 "sessionId": "child",
5640 "title": "Test investigator",
5641 "description": "Investigates platform-specific test failures."
5642 });
5643 assert_eq!(serde_json::to_value(&update).unwrap(), wire);
5644 assert_eq!(
5645 serde_json::from_value::<SubagentUpdate>(wire).unwrap(),
5646 update
5647 );
5648
5649 let minimal = SubagentUpdate::new("child");
5650 assert_eq!(
5651 serde_json::to_value(&minimal).unwrap(),
5652 json!({"sessionId": "child"})
5653 );
5654 let cleared: SubagentUpdate = serde_json::from_value(json!({
5655 "sessionId": "child", "title": null, "description": null
5656 }))
5657 .unwrap();
5658 assert!(cleared.title.is_null());
5659 assert!(cleared.description.is_null());
5660 assert_eq!(
5661 serde_json::to_value(cleared).unwrap(),
5662 json!({"sessionId": "child", "title": null, "description": null})
5663 );
5664 let invalid: SubagentUpdate = serde_json::from_value(json!({
5665 "sessionId": "child", "title": false, "description": false
5666 }))
5667 .unwrap();
5668 assert_eq!(invalid, minimal);
5669
5670 let title_only: SubagentUpdate = serde_json::from_value(json!({
5671 "sessionId": "child", "title": "Updated title"
5672 }))
5673 .unwrap();
5674 assert_eq!(
5675 title_only.title.value().map(String::as_str),
5676 Some("Updated title")
5677 );
5678 assert!(title_only.description.is_undefined());
5679 }
5680
5681 #[test]
5682 fn subagent_directories_use_strict_patch_semantics() {
5683 use serde_json::json;
5684
5685 let update = SubagentUpdate::new("child")
5686 .cwd("/home/user/project/.worktrees/investigator")
5687 .additional_directories(vec![]);
5688 let wire = json!({
5689 "sessionId": "child",
5690 "cwd": "/home/user/project/.worktrees/investigator",
5691 "additionalDirectories": []
5692 });
5693 assert_eq!(serde_json::to_value(&update).unwrap(), wire);
5694 assert_eq!(
5695 serde_json::from_value::<SubagentUpdate>(wire).unwrap(),
5696 update
5697 );
5698
5699 let inherited: SubagentUpdate =
5700 serde_json::from_value(json!({"sessionId": "child"})).unwrap();
5701 assert!(inherited.cwd.is_undefined());
5702 assert!(inherited.additional_directories.is_undefined());
5703
5704 let cleared_wire = json!({
5705 "sessionId": "child", "cwd": null, "additionalDirectories": null
5706 });
5707 let cleared: SubagentUpdate = serde_json::from_value(cleared_wire.clone()).unwrap();
5708 assert!(cleared.cwd.is_null());
5709 assert!(cleared.additional_directories.is_null());
5710 assert_eq!(serde_json::to_value(cleared).unwrap(), cleared_wire);
5711
5712 for malformed in [
5713 json!({"sessionId": "child", "cwd": false}),
5714 json!({"sessionId": "child", "additionalDirectories": "/tmp/wt"}),
5715 json!({"sessionId": "child", "additionalDirectories": ["/tmp/wt", false]}),
5716 ] {
5717 assert!(
5718 serde_json::from_value::<SubagentUpdate>(malformed.clone()).is_err(),
5719 "{malformed}"
5720 );
5721 }
5722 }
5723
5724 #[test]
5725 fn subagent_patch_fields_preserve_omitted_null_and_concrete() {
5726 use serde_json::json;
5727
5728 let omitted = SubagentUpdate::new("child");
5729 for field in ["title", "description", "capabilities", "state", "_meta"] {
5730 let wire = json!({"sessionId": "child", field: null});
5731 let decoded: SubagentUpdate = serde_json::from_value(wire.clone()).unwrap();
5732 assert_eq!(serde_json::to_value(decoded).unwrap(), wire, "{field}");
5733 let malformed = json!({"sessionId": "child", field: false});
5734 let decoded: SubagentUpdate = serde_json::from_value(malformed).unwrap();
5735 assert_eq!(decoded, omitted, "{field}");
5736 }
5737 let concrete = json!({
5738 "sessionId": "child", "title": "Investigator",
5739 "description": "Tests", "capabilities": {"cancel": {}},
5740 "state": {"state": "running"}, "_meta": {"source": "parent"}
5741 });
5742 let decoded: SubagentUpdate = serde_json::from_value(concrete.clone()).unwrap();
5743 assert!(decoded.title.value().is_some());
5744 assert!(decoded.description.value().is_some());
5745 assert!(decoded.capabilities.value().is_some());
5746 assert!(decoded.state.value().is_some());
5747 assert!(decoded.meta.value().is_some());
5748 assert_eq!(serde_json::to_value(decoded).unwrap(), concrete);
5749 let cleared = SubagentUpdate::new("child")
5750 .title(None)
5751 .description(None)
5752 .capabilities(None)
5753 .state(None)
5754 .meta(None);
5755 assert_eq!(
5756 serde_json::to_value(cleared).unwrap(),
5757 json!({
5758 "sessionId": "child", "title": null, "description": null,
5759 "capabilities": null, "state": null, "_meta": null
5760 })
5761 );
5762 }
5763
5764 #[test]
5765 fn test_subagent_notification_keeps_parent_and_child_ids_nested() {
5766 use serde_json::json;
5767
5768 let notification = SessionNotification::new(
5769 "parent",
5770 SessionUpdate::SubagentUpdate(SubagentUpdate::new("child")),
5771 );
5772 let wire = json!({
5773 "sessionId": "parent",
5774 "update": {
5775 "sessionUpdate": "subagent_update",
5776 "sessionId": "child"
5777 }
5778 });
5779 assert_eq!(serde_json::to_value(¬ification).unwrap(), wire);
5780 assert_eq!(
5781 serde_json::from_value::<SessionNotification>(wire).unwrap(),
5782 notification
5783 );
5784 for malformed in [
5786 json!({"sessionId": "parent", "update": {"sessionUpdate": "subagent_update"}}),
5787 json!({"update": {"sessionUpdate": "subagent_update", "sessionId": "child"}}),
5788 ] {
5789 assert!(serde_json::from_value::<SessionNotification>(malformed).is_err());
5790 }
5791 }
5792
5793 #[test]
5794 fn test_subagent_states_round_trip() {
5795 use serde_json::json;
5796
5797 for (wire_state, expected) in [
5798 (
5799 json!({"state": "running"}),
5800 StateUpdate::Running(RunningStateUpdate::new()),
5801 ),
5802 (
5803 json!({"state": "idle", "stopReason": "end_turn"}),
5804 StateUpdate::Idle(IdleStateUpdate::new().stop_reason(IdleStopReason::EndTurn)),
5805 ),
5806 (
5807 json!({"state": "requires_action"}),
5808 StateUpdate::RequiresAction(RequiresActionStateUpdate::new()),
5809 ),
5810 (
5811 json!({"state": "unknown"}),
5812 StateUpdate::Unknown(UnknownStateUpdate::new()),
5813 ),
5814 (
5815 json!({"state": "_waiting", "detail": {"ticket": 7}}),
5816 StateUpdate::Other(OtherStateUpdate::new(
5817 "_waiting",
5818 [("detail".into(), json!({"ticket": 7}))].into(),
5819 )),
5820 ),
5821 (
5822 json!({"state": "paused", "retryAt": 42}),
5823 StateUpdate::Other(OtherStateUpdate::new(
5824 "paused",
5825 [("retryAt".into(), json!(42))].into(),
5826 )),
5827 ),
5828 ] {
5829 let wire = json!({
5830 "sessionUpdate": "subagent_update",
5831 "sessionId": "sess_child",
5832 "state": wire_state
5833 });
5834 let parsed: SessionUpdate = serde_json::from_value(wire.clone()).unwrap();
5835 let SessionUpdate::SubagentUpdate(update) = &parsed else {
5836 panic!("expected subagent update");
5837 };
5838 assert_eq!(update.state.value(), Some(&expected));
5839 assert_eq!(serde_json::to_value(parsed).unwrap(), wire);
5840 }
5841
5842 for reason in [
5843 "end_turn",
5844 "max_tokens",
5845 "max_turn_requests",
5846 "refusal",
5847 "cancelled",
5848 ] {
5849 let state: StateUpdate = serde_json::from_value(json!({
5850 "state": "idle", "stopReason": reason
5851 }))
5852 .unwrap();
5853 assert_eq!(serde_json::to_value(state).unwrap()["stopReason"], reason);
5854 }
5855
5856 for state in [
5859 StateUpdate::Running(RunningStateUpdate::new()),
5860 StateUpdate::RequiresAction(RequiresActionStateUpdate::new()),
5861 StateUpdate::Unknown(UnknownStateUpdate::new()),
5862 StateUpdate::Running(RunningStateUpdate::new()),
5863 StateUpdate::Idle(IdleStateUpdate::new().stop_reason(IdleStopReason::EndTurn)),
5864 StateUpdate::Unknown(UnknownStateUpdate::new()),
5865 StateUpdate::Running(RunningStateUpdate::new()),
5866 ] {
5867 let update = SubagentUpdate::new("sess_child").state(state.clone());
5868 let wire = serde_json::to_value(&update).unwrap();
5869 assert_eq!(wire["sessionId"], "sess_child");
5870 assert_eq!(
5871 serde_json::from_value::<SubagentUpdate>(wire)
5872 .unwrap()
5873 .state,
5874 MaybeUndefined::Value(state)
5875 );
5876 }
5877 assert_eq!(
5878 serde_json::to_value(
5879 SubagentUpdate::new("sess_child").state(StateUpdate::Idle(IdleStateUpdate::new()))
5880 )
5881 .unwrap()["state"],
5882 json!({"state": "idle"})
5883 );
5884 }
5885
5886 #[test]
5887 fn subagent_idle_snapshot_reports_child_failure() {
5888 use serde_json::json;
5889
5890 let update = SubagentUpdate::new("sess_child").state(StateUpdate::Idle(
5891 IdleStateUpdate::new().stop_reason(IdleStopReason::from(
5892 ErrorStopReason::new().error(Error::auth_required()),
5893 )),
5894 ));
5895 let wire = json!({
5896 "sessionId": "sess_child",
5897 "state": {
5898 "state": "idle",
5899 "stopReason": "error",
5900 "error": { "code": -32000, "message": "Authentication required" }
5901 }
5902 });
5903 assert_eq!(serde_json::to_value(&update).unwrap(), wire);
5904 assert_eq!(
5905 serde_json::from_value::<SubagentUpdate>(wire).unwrap(),
5906 update
5907 );
5908
5909 let without_details = StateUpdate::Idle(
5911 IdleStateUpdate::new().stop_reason(IdleStopReason::from(ErrorStopReason::new())),
5912 );
5913 for error in [None, Some(json!(null)), Some(json!("failed"))] {
5914 let mut wire = json!({ "state": "idle", "stopReason": "error" });
5915 if let Some(error) = error {
5916 wire["error"] = error;
5917 }
5918 assert_eq!(
5919 serde_json::from_value::<StateUpdate>(wire).unwrap(),
5920 without_details
5921 );
5922 }
5923
5924 let parsed: StateUpdate = serde_json::from_value(json!({
5927 "state": "idle",
5928 "stopReason": "end_turn",
5929 "error": { "code": -32603, "message": "Internal error" }
5930 }))
5931 .unwrap();
5932 assert_eq!(
5933 parsed,
5934 StateUpdate::Idle(IdleStateUpdate::new().stop_reason(IdleStopReason::EndTurn))
5935 );
5936
5937 let meta: Meta = [("source".into(), json!("worker"))].into_iter().collect();
5940 for stop_reason in [None, Some(json!(null)), Some(json!(true))] {
5941 let mut wire = json!({ "state": "idle", "_meta": { "source": "worker" } });
5942 if let Some(stop_reason) = stop_reason {
5943 wire["stopReason"] = stop_reason;
5944 }
5945 assert_eq!(
5946 serde_json::from_value::<StateUpdate>(wire).unwrap(),
5947 StateUpdate::Idle(IdleStateUpdate::new().meta(meta.clone()))
5948 );
5949 }
5950
5951 for stop_reason in ["_paused", "not_a_reason"] {
5954 let wire = json!({
5955 "state": "idle",
5956 "stopReason": stop_reason,
5957 "resumeAfter": 30,
5958 "_meta": { "source": "worker" }
5959 });
5960 let parsed: StateUpdate = serde_json::from_value(wire.clone()).unwrap();
5961 assert_eq!(
5962 parsed,
5963 StateUpdate::Idle(
5964 IdleStateUpdate::new()
5965 .stop_reason(IdleStopReason::Other(OtherStopReason::new(
5966 stop_reason,
5967 [("resumeAfter".into(), json!(30))].into_iter().collect(),
5968 )))
5969 .meta(meta.clone())
5970 )
5971 );
5972 assert_eq!(serde_json::to_value(&parsed).unwrap(), wire);
5973 }
5974 }
5975
5976 #[test]
5977 fn subagent_known_stop_reasons_are_never_read_as_other() {
5978 use serde_json::json;
5979
5980 let known = [
5981 IdleStopReason::EndTurn,
5982 IdleStopReason::MaxTokens,
5983 IdleStopReason::MaxTurnRequests,
5984 IdleStopReason::Refusal,
5985 IdleStopReason::Cancelled,
5986 IdleStopReason::Error(ErrorStopReason::new()),
5987 ];
5988 for stop_reason in &known {
5990 match stop_reason {
5991 IdleStopReason::EndTurn
5992 | IdleStopReason::MaxTokens
5993 | IdleStopReason::MaxTurnRequests
5994 | IdleStopReason::Refusal
5995 | IdleStopReason::Cancelled
5996 | IdleStopReason::Error(_)
5997 | IdleStopReason::Other(_) => {}
5998 }
5999 }
6000
6001 for stop_reason in known {
6002 let state = StateUpdate::Idle(IdleStateUpdate::new().stop_reason(stop_reason));
6003 let wire = serde_json::to_value(&state).unwrap();
6004 assert_eq!(
6005 serde_json::from_value::<StateUpdate>(wire.clone()).unwrap(),
6006 state
6007 );
6008 assert!(
6009 serde_json::from_value::<OtherStopReason>(
6010 json!({ "stopReason": wire["stopReason"] })
6011 )
6012 .is_err(),
6013 "{} must not be accepted as a custom stop reason",
6014 wire["stopReason"]
6015 );
6016 }
6017 }
6018
6019 #[test]
6020 fn subagent_unknown_stop_reason_leaves_usage_on_the_snapshot() {
6021 use serde_json::json;
6022
6023 let usage = json!({ "totalTokens": 10, "inputTokens": 6, "outputTokens": 4 });
6024 let wire = json!({ "state": "idle", "stopReason": "_paused", "usage": usage });
6025 let StateUpdate::Idle(idle) = serde_json::from_value(wire).unwrap() else {
6026 panic!("expected idle state snapshot");
6027 };
6028 let Some(IdleStopReason::Other(other)) = &idle.stop_reason else {
6029 panic!("expected a custom stop reason");
6030 };
6031 assert!(other.fields.is_empty());
6032
6033 #[cfg(feature = "unstable_end_turn_token_usage")]
6034 {
6035 assert!(idle.usage.is_some());
6036 assert_eq!(serde_json::to_value(&idle).unwrap()["usage"], usage);
6037 }
6038 #[cfg(not(feature = "unstable_end_turn_token_usage"))]
6041 assert!(serde_json::to_value(&idle).unwrap().get("usage").is_none());
6042 }
6043
6044 #[test]
6045 fn test_subagent_unknown_activity_metadata_and_capabilities() {
6046 use serde_json::json;
6047
6048 let update = SubagentUpdate::new("child").state(StateUpdate::Unknown(
6049 UnknownStateUpdate::new().meta(
6050 [("source".into(), json!("worker"))]
6051 .into_iter()
6052 .collect::<Meta>(),
6053 ),
6054 ));
6055 let wire = json!({
6056 "sessionId": "child",
6057 "state": {
6058 "state": "unknown",
6059 "_meta": { "source": "worker" }
6060 }
6061 });
6062 assert_eq!(serde_json::to_value(&update).unwrap(), wire);
6063 assert_eq!(
6064 serde_json::from_value::<SubagentUpdate>(wire).unwrap(),
6065 update
6066 );
6067 assert!(update.capabilities.is_undefined());
6069
6070 for meta in [json!(null), json!(false)] {
6071 let state: StateUpdate = serde_json::from_value(json!({
6072 "state": "unknown",
6073 "_meta": meta
6074 }))
6075 .unwrap();
6076 assert_eq!(state, StateUpdate::Unknown(UnknownStateUpdate::new()));
6077 assert_eq!(
6078 serde_json::to_value(state).unwrap(),
6079 json!({"state": "unknown"})
6080 );
6081 }
6082 assert!(serde_json::from_value::<OtherStateUpdate>(json!({"state": "unknown"})).is_err());
6084 }
6085
6086 #[test]
6087 fn test_subagent_malformed_optional_state() {
6088 use serde_json::json;
6089
6090 for malformed in [json!("running"), json!({}), json!({"state": 4})] {
6091 assert!(serde_json::from_value::<StateUpdate>(malformed.clone()).is_err());
6092 let update: SubagentUpdate = serde_json::from_value(json!({
6093 "sessionId": "child", "state": malformed
6094 }))
6095 .unwrap();
6096 assert!(update.state.is_undefined());
6097 }
6098 let bad_reason: StateUpdate =
6099 serde_json::from_value(json!({"state": "idle", "stopReason": false})).unwrap();
6100 assert_eq!(bad_reason, StateUpdate::Idle(IdleStateUpdate::new()));
6101 let null_reason: StateUpdate =
6102 serde_json::from_value(json!({"state": "idle", "stopReason": null})).unwrap();
6103 assert_eq!(null_reason, StateUpdate::Idle(IdleStateUpdate::new()));
6104 }
6105
6106 #[cfg(feature = "unstable_protocol_v2")]
6107 #[test]
6108 fn test_subagent_state_v2_wire_parity() {
6109 use serde_json::json;
6110
6111 for wire in [
6112 json!({"state": "running"}),
6113 json!({"state": "idle", "stopReason": "cancelled"}),
6114 json!({"state": "requires_action"}),
6115 json!({"state": "unknown"}),
6116 json!({"state": "unknown", "_meta": {"source": "worker"}}),
6117 json!({"state": "_waiting", "detail": {"ticket": 7}}),
6118 ] {
6119 let v1: StateUpdate = serde_json::from_value(wire.clone()).unwrap();
6120 let v2: crate::v2::StateUpdate = serde_json::from_value(wire.clone()).unwrap();
6121 assert_eq!(serde_json::to_value(v1).unwrap(), wire);
6122 assert_eq!(serde_json::to_value(v2).unwrap(), wire);
6123 }
6124 }
6125
6126 #[test]
6127 fn test_subagent_capability_semantics() {
6128 use serde_json::json;
6129
6130 let capabilities =
6131 serde_json::to_value(ClientCapabilities::new().subagents(SubagentCapabilities::new()))
6132 .unwrap();
6133 assert_eq!(capabilities["subagents"], json!({}));
6134
6135 let omitted: ClientCapabilities = serde_json::from_value(json!({})).unwrap();
6136 assert!(omitted.subagents.is_none());
6137
6138 let null: ClientCapabilities =
6139 serde_json::from_value(json!({ "subagents": null })).unwrap();
6140 assert!(null.subagents.is_none());
6141 assert_eq!(null, omitted);
6142 let serialized = serde_json::to_value(null).unwrap();
6143 assert_eq!(serialized, serde_json::to_value(omitted).unwrap());
6144 assert!(serialized.get("subagents").is_none());
6145
6146 for wire in [
6147 json!({}),
6148 json!({"cancel": null}),
6149 json!({"cancel": true}),
6150 json!({"cancel": false}),
6151 ] {
6152 let child: SubagentSessionCapabilities = serde_json::from_value(wire).unwrap();
6153 assert!(child.cancel.is_none());
6154 assert_eq!(serde_json::to_value(child).unwrap(), json!({}));
6155 }
6156 let enabled = SubagentSessionCapabilities::new().cancel(SessionCancelCapabilities::new());
6157 assert_eq!(
6158 serde_json::to_value(&enabled).unwrap(),
6159 json!({"cancel": {}})
6160 );
6161 assert_eq!(
6162 serde_json::from_value::<SubagentSessionCapabilities>(json!({"cancel": {}})).unwrap(),
6163 enabled
6164 );
6165 let meta: Meta = [("source".into(), json!("worker"))].into_iter().collect();
6166 let with_meta =
6167 SubagentSessionCapabilities::new().cancel(SessionCancelCapabilities::new().meta(meta));
6168 let wire = json!({"cancel": {"_meta": {"source": "worker"}}});
6169 assert_eq!(serde_json::to_value(&with_meta).unwrap(), wire);
6170 assert_eq!(
6171 serde_json::from_value::<SubagentSessionCapabilities>(wire).unwrap(),
6172 with_meta
6173 );
6174 let removed = SubagentSessionCapabilities::new();
6176 assert_eq!(serde_json::to_value(&removed).unwrap(), json!({}));
6177 assert!(removed.cancel.is_none());
6178 assert!(enabled.cancel.is_some());
6179 assert!(enabled.cancel(None).cancel.is_none());
6180 let replacement = SubagentUpdate::new("child").capabilities(removed);
6181 assert_eq!(
6182 serde_json::to_value(replacement).unwrap(),
6183 json!({"sessionId": "child", "capabilities": {}})
6184 );
6185 }
6186
6187 #[cfg(feature = "schemars")]
6188 #[test]
6189 fn test_subagent_capability_schema_is_optional_and_nullable() {
6190 use serde_json::json;
6191
6192 let schema = serde_json::to_value(schemars::schema_for!(ClientCapabilities)).unwrap();
6193 let variants = schema["properties"]["subagents"]["anyOf"]
6194 .as_array()
6195 .expect("subagents must allow the capability object or null");
6196 assert!(variants.contains(&json!({"type": "null"})));
6197 assert!(
6198 !schema["required"]
6199 .as_array()
6200 .is_some_and(|required| required.contains(&json!("subagents")))
6201 );
6202 let child =
6203 serde_json::to_value(schemars::schema_for!(SubagentSessionCapabilities)).unwrap();
6204 let variants = child["properties"]["cancel"]["anyOf"]
6205 .as_array()
6206 .expect("cancel must allow the capability object or null");
6207 assert!(variants.contains(&json!({"type": "null"})));
6208 assert!(
6209 variants
6210 .iter()
6211 .any(|variant| variant["type"] == "object" || variant.get("$ref").is_some())
6212 );
6213 assert!(!variants.iter().any(|variant| variant["type"] == "boolean"));
6214 let cancel =
6215 serde_json::to_value(schemars::schema_for!(SessionCancelCapabilities)).unwrap();
6216 assert_eq!(cancel["type"], "object");
6217 assert!(
6218 !child["required"]
6219 .as_array()
6220 .is_some_and(|required| required.contains(&json!("cancel")))
6221 );
6222 }
6223
6224 #[test]
6225 fn test_elicitation_capability_semantics() {
6226 use serde_json::json;
6227
6228 let unsupported: ClientCapabilities = serde_json::from_value(json!({})).unwrap();
6229 assert!(unsupported.elicitation.is_none());
6230
6231 let null: ClientCapabilities =
6232 serde_json::from_value(json!({ "elicitation": null })).unwrap();
6233 assert!(null.elicitation.is_none());
6234
6235 let malformed: ClientCapabilities =
6236 serde_json::from_value(json!({ "elicitation": false })).unwrap();
6237 assert!(malformed.elicitation.is_none());
6238
6239 let empty: ClientCapabilities =
6240 serde_json::from_value(json!({ "elicitation": {} })).unwrap();
6241 let empty = empty.elicitation.expect("present capability");
6242 assert!(!empty.supports_form());
6243 assert!(!empty.supports_url());
6244
6245 let form_only: ClientCapabilities = serde_json::from_value(json!({
6246 "elicitation": { "form": {} }
6247 }))
6248 .unwrap();
6249 let form_only = form_only.elicitation.expect("advertised capability");
6250 assert!(form_only.supports_form());
6251 assert!(!form_only.supports_url());
6252
6253 let url_only: ClientCapabilities = serde_json::from_value(json!({
6254 "elicitation": { "url": {} }
6255 }))
6256 .unwrap();
6257 let url_only = url_only.elicitation.expect("advertised capability");
6258 assert!(!url_only.supports_form());
6259 assert!(url_only.supports_url());
6260
6261 let both: ClientCapabilities = serde_json::from_value(json!({
6262 "elicitation": { "form": {}, "url": {} }
6263 }))
6264 .unwrap();
6265 let both = both.elicitation.expect("advertised capability");
6266 assert!(both.supports_form());
6267 assert!(both.supports_url());
6268 }
6269
6270 #[test]
6271 fn test_elicitation_method_routing_and_envelopes() {
6272 use serde_json::json;
6273
6274 assert_eq!(CLIENT_METHOD_NAMES.elicitation_create, "elicitation/create");
6275 assert_eq!(
6276 CLIENT_METHOD_NAMES.elicitation_complete,
6277 "elicitation/complete"
6278 );
6279
6280 let request = AgentRequest::CreateElicitationRequest(CreateElicitationRequest::new(
6281 crate::v1::ElicitationFormMode::new(
6282 crate::v1::ElicitationSessionScope::new("sess_1"),
6283 crate::v1::ElicitationSchema::new(),
6284 ),
6285 "Choose a value",
6286 ));
6287 assert_eq!(request.method(), "elicitation/create");
6288 let method = Arc::from(request.method());
6289 let request = crate::v1::JsonRpcMessage::wrap(crate::v1::Request {
6290 id: crate::v1::RequestId::Number(7),
6291 method,
6292 params: Some(request),
6293 });
6294 assert_eq!(
6295 serde_json::to_value(request).unwrap(),
6296 json!({
6297 "jsonrpc": "2.0",
6298 "id": 7,
6299 "method": "elicitation/create",
6300 "params": {
6301 "mode": "form",
6302 "sessionId": "sess_1",
6303 "message": "Choose a value",
6304 "requestedSchema": { "type": "object", "properties": {} }
6305 }
6306 })
6307 );
6308
6309 let notification = AgentNotification::CompleteElicitationNotification(
6310 CompleteElicitationNotification::new("elic_1"),
6311 );
6312 assert_eq!(notification.method(), "elicitation/complete");
6313 let method = Arc::from(notification.method());
6314 let notification = crate::v1::JsonRpcMessage::wrap(crate::v1::Notification {
6315 method,
6316 params: Some(notification),
6317 });
6318 assert_eq!(
6319 serde_json::to_value(notification).unwrap(),
6320 json!({
6321 "jsonrpc": "2.0",
6322 "method": "elicitation/complete",
6323 "params": { "elicitationId": "elic_1" }
6324 })
6325 );
6326 }
6327
6328 #[test]
6329 fn test_client_capabilities_default_on_malformed_values() {
6330 use serde_json::json;
6331
6332 let capabilities: ClientCapabilities = serde_json::from_value(json!({
6333 "fs": {
6334 "readTextFile": "yes",
6335 "writeTextFile": true
6336 },
6337 "terminal": {}
6338 }))
6339 .unwrap();
6340
6341 assert!(!capabilities.fs.read_text_file);
6342 assert!(capabilities.fs.write_text_file);
6343 assert!(!capabilities.terminal);
6344
6345 let capabilities: ClientCapabilities = serde_json::from_value(json!({
6346 "fs": false
6347 }))
6348 .unwrap();
6349 assert_eq!(capabilities.fs, FileSystemCapabilities::default());
6350
6351 {
6352 let capabilities: ClientCapabilities = serde_json::from_value(json!({
6353 "auth": false
6354 }))
6355 .unwrap();
6356 assert_eq!(capabilities.auth, AuthCapabilities::default());
6357
6358 let capabilities: AuthCapabilities = serde_json::from_value(json!({
6359 "terminal": {}
6360 }))
6361 .unwrap();
6362 assert!(!capabilities.terminal);
6363 }
6364 }
6365
6366 #[test]
6367 fn test_serialization_behavior() {
6368 use serde_json::json;
6369
6370 assert_eq!(
6371 serde_json::from_value::<SessionInfoUpdate>(json!({})).unwrap(),
6372 SessionInfoUpdate {
6373 title: MaybeUndefined::Undefined,
6374 updated_at: MaybeUndefined::Undefined,
6375 meta: None
6376 }
6377 );
6378 assert_eq!(
6379 serde_json::from_value::<SessionInfoUpdate>(json!({"title": null, "updatedAt": null}))
6380 .unwrap(),
6381 SessionInfoUpdate {
6382 title: MaybeUndefined::Null,
6383 updated_at: MaybeUndefined::Null,
6384 meta: None
6385 }
6386 );
6387 assert_eq!(
6388 serde_json::from_value::<SessionInfoUpdate>(
6389 json!({"title": "title", "updatedAt": "timestamp"})
6390 )
6391 .unwrap(),
6392 SessionInfoUpdate {
6393 title: MaybeUndefined::Value("title".to_string()),
6394 updated_at: MaybeUndefined::Value("timestamp".to_string()),
6395 meta: None
6396 }
6397 );
6398
6399 assert_eq!(
6400 serde_json::to_value(SessionInfoUpdate::new()).unwrap(),
6401 json!({})
6402 );
6403 assert_eq!(
6404 serde_json::to_value(SessionInfoUpdate::new().title("title")).unwrap(),
6405 json!({"title": "title"})
6406 );
6407 assert_eq!(
6408 serde_json::to_value(SessionInfoUpdate::new().title(None)).unwrap(),
6409 json!({"title": null})
6410 );
6411 assert_eq!(
6412 serde_json::to_value(
6413 SessionInfoUpdate::new()
6414 .title("title")
6415 .title(MaybeUndefined::Undefined)
6416 )
6417 .unwrap(),
6418 json!({})
6419 );
6420 }
6421
6422 #[test]
6423 fn test_content_chunk_message_id_serialization() {
6424 use serde_json::json;
6425
6426 assert_eq!(
6427 serde_json::to_value(SessionUpdate::AgentMessageChunk(ContentChunk::new(
6428 ContentBlock::Text(crate::v1::TextContent::new("Hello"))
6429 )))
6430 .unwrap(),
6431 json!({
6432 "sessionUpdate": "agent_message_chunk",
6433 "content": {
6434 "type": "text",
6435 "text": "Hello"
6436 }
6437 })
6438 );
6439
6440 assert_eq!(
6441 serde_json::to_value(SessionUpdate::AgentMessageChunk(
6442 ContentChunk::new(ContentBlock::Text(crate::v1::TextContent::new("Hello")))
6443 .message_id("msg_agent_c42b9")
6444 ))
6445 .unwrap(),
6446 json!({
6447 "sessionUpdate": "agent_message_chunk",
6448 "messageId": "msg_agent_c42b9",
6449 "content": {
6450 "type": "text",
6451 "text": "Hello"
6452 }
6453 })
6454 );
6455
6456 let SessionUpdate::AgentMessageChunk(chunk) = serde_json::from_value(json!({
6457 "sessionUpdate": "agent_message_chunk",
6458 "messageId": null,
6459 "content": {
6460 "type": "text",
6461 "text": "Hello"
6462 }
6463 }))
6464 .unwrap() else {
6465 panic!("expected agent message chunk");
6466 };
6467
6468 assert_eq!(chunk.message_id, None);
6469 }
6470
6471 #[test]
6472 fn test_usage_update_serialization() {
6473 use serde_json::json;
6474
6475 assert_eq!(
6476 serde_json::to_value(SessionUpdate::UsageUpdate(UsageUpdate::new(
6477 53_000, 200_000
6478 )))
6479 .unwrap(),
6480 json!({
6481 "sessionUpdate": "usage_update",
6482 "used": 53000,
6483 "size": 200_000
6484 })
6485 );
6486
6487 assert_eq!(
6488 serde_json::to_value(SessionUpdate::UsageUpdate(
6489 UsageUpdate::new(53_000, 200_000).cost(Cost::new(0.045, "USD"))
6490 ))
6491 .unwrap(),
6492 json!({
6493 "sessionUpdate": "usage_update",
6494 "used": 53000,
6495 "size": 200_000,
6496 "cost": {
6497 "amount": 0.045,
6498 "currency": "USD"
6499 }
6500 })
6501 );
6502
6503 let SessionUpdate::UsageUpdate(update) = serde_json::from_value(json!({
6504 "sessionUpdate": "usage_update",
6505 "used": 53000,
6506 "size": 200_000,
6507 "cost": null
6508 }))
6509 .unwrap() else {
6510 panic!("expected usage update");
6511 };
6512
6513 assert_eq!(update.cost, None);
6514 }
6515
6516 #[test]
6517 fn test_client_capabilities_boolean_config_options_serialization() {
6518 use serde_json::json;
6519
6520 let capabilities = ClientCapabilities::new().session(
6521 ClientSessionCapabilities::new().config_options(
6522 SessionConfigOptionsCapabilities::new()
6523 .boolean(BooleanConfigOptionCapabilities::new()),
6524 ),
6525 );
6526 let json = serde_json::to_value(&capabilities).unwrap();
6527
6528 assert_eq!(json["session"]["configOptions"]["boolean"], json!({}));
6529
6530 let omitted: ClientCapabilities = serde_json::from_value(json!({})).unwrap();
6531 assert!(omitted.session.is_none());
6532
6533 let null_session: ClientCapabilities = serde_json::from_value(json!({
6534 "session": null
6535 }))
6536 .unwrap();
6537 assert!(null_session.session.is_none());
6538
6539 let null_config_options: ClientCapabilities = serde_json::from_value(json!({
6540 "session": {
6541 "configOptions": null
6542 }
6543 }))
6544 .unwrap();
6545 assert!(
6546 null_config_options
6547 .session
6548 .and_then(|session| session.config_options)
6549 .is_none()
6550 );
6551
6552 let null_boolean: ClientCapabilities = serde_json::from_value(json!({
6553 "session": {
6554 "configOptions": {
6555 "boolean": null
6556 }
6557 }
6558 }))
6559 .unwrap();
6560 assert!(
6561 null_boolean
6562 .session
6563 .and_then(|session| session.config_options)
6564 .and_then(|config_options| config_options.boolean)
6565 .is_none()
6566 );
6567 }
6568
6569 #[test]
6570 fn test_plan_operations_serialization() {
6571 use serde_json::json;
6572
6573 use crate::v1::{PlanEntry, PlanEntryPriority, PlanEntryStatus, PlanUpdateContent};
6574
6575 let plan_update = SessionUpdate::PlanUpdate(PlanUpdate::new(PlanUpdateContent::items(
6576 "plan-1",
6577 vec![PlanEntry::new(
6578 "Step 1",
6579 PlanEntryPriority::High,
6580 PlanEntryStatus::Pending,
6581 )],
6582 )));
6583
6584 assert_eq!(
6585 serde_json::to_value(plan_update).unwrap(),
6586 json!({
6587 "sessionUpdate": "plan_update",
6588 "plan": {
6589 "type": "items",
6590 "planId": "plan-1",
6591 "entries": [
6592 {
6593 "content": "Step 1",
6594 "priority": "high",
6595 "status": "pending"
6596 }
6597 ]
6598 }
6599 })
6600 );
6601
6602 assert_eq!(
6603 serde_json::to_value(SessionUpdate::PlanRemoved(PlanRemoved::new("plan-1"))).unwrap(),
6604 json!({
6605 "sessionUpdate": "plan_removed",
6606 "planId": "plan-1"
6607 })
6608 );
6609
6610 let markdown = json!({
6611 "sessionUpdate": "plan_update",
6612 "plan": {
6613 "type": "markdown", "planId": "plan-1",
6614 "content": "# Next steps", "path": "/workspace/plan.md"
6615 }
6616 });
6617 let update: SessionUpdate = serde_json::from_value(markdown.clone()).unwrap();
6618 assert_eq!(serde_json::to_value(update).unwrap(), markdown);
6619
6620 let capabilities = ClientCapabilities::new().plan(PlanCapabilities::new());
6621 let json = serde_json::to_value(&capabilities).unwrap();
6622 assert_eq!(json["plan"], json!({}));
6623
6624 assert_eq!(
6625 serde_json::from_value::<ClientCapabilities>(json!({ "plan": null }))
6626 .unwrap()
6627 .plan,
6628 None
6629 );
6630 }
6631
6632 #[cfg(feature = "unstable_mcp_over_acp")]
6633 #[test]
6634 fn test_agent_mcp_request_method_names() {
6635 use serde_json::json;
6636
6637 let params: serde_json::Map<String, serde_json::Value> =
6638 [("cursor".to_string(), json!("abc"))].into_iter().collect();
6639
6640 assert_eq!(CLIENT_METHOD_NAMES.mcp_message, "mcp/message");
6641 assert_eq!(
6642 AgentRequest::MessageMcpRequest(MessageMcpRequest::new(
6643 "server-1",
6644 "req-1",
6645 "tools/list"
6646 ))
6647 .method(),
6648 "mcp/message"
6649 );
6650 assert_eq!(
6651 serde_json::to_value(
6652 MessageMcpRequest::new("server-1", "req-1", "tools/list").params(params)
6653 )
6654 .unwrap(),
6655 json!({
6656 "serverId": "server-1",
6657 "requestId": "req-1",
6658 "method": "tools/list",
6659 "params": { "cursor": "abc" }
6660 })
6661 );
6662
6663 let request_with_null_params: MessageMcpRequest = serde_json::from_value(json!({
6664 "serverId": "server-1",
6665 "requestId": "req-1",
6666 "method": "tools/list",
6667 "params": null,
6668 "_meta": null
6669 }))
6670 .unwrap();
6671 assert_eq!(request_with_null_params.params, None);
6672 assert_eq!(request_with_null_params.meta, None);
6673 for key in ["serverId", "requestId", "method"] {
6674 let mut value =
6675 json!({"serverId":"server-1", "requestId":"req-1", "method":"tools/list"});
6676 value.as_object_mut().unwrap().remove(key);
6677 assert!(serde_json::from_value::<MessageMcpRequest>(value).is_err());
6678 }
6679 for key in ["serverId", "requestId", "method"] {
6680 let mut value =
6681 json!({"serverId":"server-1", "requestId":"req-1", "method":"tools/list"});
6682 value[key] = serde_json::Value::Null;
6683 assert!(serde_json::from_value::<MessageMcpRequest>(value).is_err());
6684 }
6685 }
6686
6687 #[test]
6688 fn request_permission_request_rejects_malformed_options() {
6689 use serde_json::json;
6690
6691 assert!(
6692 serde_json::from_value::<RequestPermissionRequest>(json!({
6693 "sessionId": "sess-1",
6694 "toolCall": {"toolCallId": "tc-1"},
6695 "options": "not-an-array"
6696 }))
6697 .is_err()
6698 );
6699 assert!(
6700 serde_json::from_value::<RequestPermissionRequest>(json!({
6701 "sessionId": "sess-1",
6702 "toolCall": {"toolCallId": "tc-1"},
6703 "options": [{"optionId": "allow"}]
6704 }))
6705 .is_err()
6706 );
6707 }
6708
6709 #[test]
6710 fn create_terminal_request_rejects_malformed_fields() {
6711 use serde_json::json;
6712
6713 let request = |field: &str, value: serde_json::Value| {
6714 let mut request = json!({"sessionId": "sess-1", "command": "npx"});
6715 request[field] = value;
6716 serde_json::from_value::<CreateTerminalRequest>(request)
6717 };
6718
6719 for (field, value) in [
6721 ("args", json!(["serve", "--port", 3000])),
6722 ("args", json!("serve --port 3000")),
6723 ("env", json!([{"name": "PORT", "value": 3000}])),
6724 ("env", json!({"PORT": "3000"})),
6725 ("cwd", json!({"path": "/repo"})),
6726 ("outputByteLimit", json!("1048576")),
6727 ] {
6728 assert!(request(field, value.clone()).is_err(), "{field}: {value}");
6729 }
6730
6731 for field in ["args", "env", "cwd", "outputByteLimit"] {
6732 assert_eq!(
6733 request(field, serde_json::Value::Null).unwrap(),
6734 CreateTerminalRequest::new("sess-1", "npx"),
6735 "{field}"
6736 );
6737 }
6738 }
6739
6740 #[test]
6741 fn read_text_file_request_rejects_malformed_range() {
6742 use serde_json::json;
6743
6744 let request = |field: &str, value: serde_json::Value| {
6745 let mut request = json!({"sessionId": "sess-1", "path": "/repo/src/main.rs"});
6746 request[field] = value;
6747 serde_json::from_value::<ReadTextFileRequest>(request)
6748 };
6749
6750 for field in ["line", "limit"] {
6752 assert!(request(field, json!("120")).is_err(), "{field}");
6753 assert!(request(field, json!(-1)).is_err(), "{field}");
6754 assert_eq!(
6755 request(field, serde_json::Value::Null).unwrap(),
6756 ReadTextFileRequest::new("sess-1", "/repo/src/main.rs"),
6757 "{field}"
6758 );
6759 }
6760 }
6761
6762 #[cfg(feature = "unstable_session_cursors")]
6763 #[test]
6764 fn cursor_updates_round_trip_and_patch_capabilities() {
6765 use serde_json::json;
6766
6767 let update = SessionUpdate::CursorUpdate(
6768 CursorUpdate::new("cur_1")
6769 .capabilities(CursorCapabilities::new())
6770 .anchor(CursorAnchor::UserMessage(CursorMessageAnchor::new(
6771 "msg_user_2",
6772 CursorAnchorPosition::Before,
6773 ))),
6774 );
6775 let wire = json!({
6776 "sessionUpdate": "cursor_update",
6777 "cursorId": "cur_1",
6778 "capabilities": {},
6779 "anchor": { "type": "user_message", "messageId": "msg_user_2", "position": "before" }
6780 });
6781 assert_eq!(serde_json::to_value(&update).unwrap(), wire);
6782 assert_eq!(
6783 serde_json::from_value::<SessionUpdate>(wire).unwrap(),
6784 update
6785 );
6786
6787 let SessionUpdate::CursorUpdate(omitted) = serde_json::from_value(json!({
6789 "sessionUpdate": "cursor_update",
6790 "cursorId": "cur_1"
6791 }))
6792 .unwrap() else {
6793 panic!("expected cursor update");
6794 };
6795 assert!(omitted.capabilities.is_undefined());
6796 assert_eq!(omitted.anchor, None);
6797 assert!(omitted.meta.is_undefined());
6798 assert_eq!(
6799 serde_json::to_value(SessionUpdate::CursorUpdate(CursorUpdate::new("cur_1"))).unwrap(),
6800 json!({ "sessionUpdate": "cursor_update", "cursorId": "cur_1" })
6801 );
6802
6803 let SessionUpdate::CursorUpdate(cleared) = serde_json::from_value(json!({
6805 "sessionUpdate": "cursor_update",
6806 "cursorId": "cur_1",
6807 "capabilities": null,
6808 "anchor": null
6809 }))
6810 .unwrap() else {
6811 panic!("expected cursor update");
6812 };
6813 assert!(cleared.capabilities.is_null());
6814 assert_eq!(cleared.anchor, None);
6815 assert_eq!(
6816 serde_json::to_value(SessionUpdate::CursorUpdate(
6817 CursorUpdate::new("cur_1").capabilities(None)
6818 ))
6819 .unwrap(),
6820 json!({ "sessionUpdate": "cursor_update", "cursorId": "cur_1", "capabilities": null })
6821 );
6822 }
6823
6824 #[cfg(feature = "unstable_session_cursors")]
6825 #[test]
6826 fn cursor_anchors_cover_each_entity_type_and_preserve_unknown_ones() {
6827 use serde_json::json;
6828
6829 for (anchor, wire) in [
6830 (
6831 CursorAnchor::AgentMessage(CursorMessageAnchor::new(
6832 "msg_agent_1",
6833 CursorAnchorPosition::After,
6834 )),
6835 json!({ "type": "agent_message", "messageId": "msg_agent_1", "position": "after" }),
6836 ),
6837 (
6838 CursorAnchor::AgentThought(CursorMessageAnchor::new(
6839 "msg_agent_1",
6840 CursorAnchorPosition::After,
6841 )),
6842 json!({ "type": "agent_thought", "messageId": "msg_agent_1", "position": "after" }),
6843 ),
6844 (
6845 CursorAnchor::SessionMessage(CursorMessageAnchor::new(
6846 "msg_session_1",
6847 CursorAnchorPosition::Before,
6848 )),
6849 json!({ "type": "session_message", "messageId": "msg_session_1", "position": "before" }),
6850 ),
6851 (
6852 CursorAnchor::ToolCall(CursorToolCallAnchor::new(
6853 "call_1",
6854 CursorAnchorPosition::After,
6855 )),
6856 json!({ "type": "tool_call", "toolCallId": "call_1", "position": "after" }),
6857 ),
6858 (
6859 CursorAnchor::Compaction(CursorCompactionAnchor::new(
6860 "cmp_1",
6861 CursorAnchorPosition::Before,
6862 )),
6863 json!({ "type": "compaction", "compactionId": "cmp_1", "position": "before" }),
6864 ),
6865 ] {
6866 assert_eq!(serde_json::to_value(&anchor).unwrap(), wire);
6867 assert_eq!(
6868 serde_json::from_value::<CursorAnchor>(wire).unwrap(),
6869 anchor
6870 );
6871 }
6872
6873 let wire = json!({ "type": "_acme_marker", "markerId": "mk_1", "position": "after" });
6875 let other = serde_json::from_value::<CursorAnchor>(wire.clone()).unwrap();
6876 assert!(matches!(other, CursorAnchor::Other(_)));
6877 assert_eq!(serde_json::to_value(&other).unwrap(), wire);
6878
6879 let wire =
6881 json!({ "type": "user_message", "messageId": "msg_user_2", "position": "inside" });
6882 let future = serde_json::from_value::<CursorAnchor>(wire.clone()).unwrap();
6883 assert_eq!(
6884 future,
6885 CursorAnchor::UserMessage(CursorMessageAnchor::new(
6886 "msg_user_2",
6887 CursorAnchorPosition::Other("inside".into()),
6888 ))
6889 );
6890 assert_eq!(serde_json::to_value(&future).unwrap(), wire);
6891 }
6892
6893 #[cfg(feature = "unstable_session_cursors")]
6894 #[test]
6895 fn malformed_cursor_anchor_fails_the_update() {
6896 use serde_json::json;
6897
6898 for anchor in [
6900 json!({ "type": "user_message", "position": "before" }),
6901 json!({ "type": "tool_call", "toolCallId": 7, "position": "after" }),
6902 json!({ "type": "compaction", "compactionId": "cmp_1" }),
6903 json!({ "messageId": "msg_user_2", "position": "before" }),
6904 json!("before"),
6905 ] {
6906 assert!(
6907 serde_json::from_value::<SessionUpdate>(json!({
6908 "sessionUpdate": "cursor_update",
6909 "cursorId": "cur_1",
6910 "anchor": anchor
6911 }))
6912 .is_err(),
6913 "{anchor}"
6914 );
6915 }
6916 assert!(
6917 serde_json::from_value::<SessionUpdate>(json!({ "sessionUpdate": "cursor_update" }))
6918 .is_err()
6919 );
6920 }
6921
6922 #[cfg(feature = "unstable_session_cursors")]
6923 #[test]
6924 fn malformed_cursor_capabilities_are_not_advertised() {
6925 use serde_json::json;
6926
6927 let SessionUpdate::CursorUpdate(update) = serde_json::from_value(json!({
6929 "sessionUpdate": "cursor_update",
6930 "cursorId": "cur_1",
6931 "capabilities": "fork"
6932 }))
6933 .unwrap() else {
6934 panic!("expected cursor update");
6935 };
6936 assert!(update.capabilities.is_undefined());
6937
6938 assert_eq!(
6940 serde_json::from_value::<CursorCapabilities>(json!({ "futureMethod": {} })).unwrap(),
6941 CursorCapabilities::new()
6942 );
6943
6944 #[cfg(feature = "unstable_session_fork")]
6945 {
6946 assert_eq!(
6947 serde_json::to_value(CursorCapabilities::new().fork(CursorForkCapabilities::new()))
6948 .unwrap(),
6949 json!({ "fork": {} })
6950 );
6951 assert_eq!(
6952 serde_json::from_value::<CursorCapabilities>(json!({ "fork": {} }))
6953 .unwrap()
6954 .fork,
6955 Some(CursorForkCapabilities::new())
6956 );
6957 for fork in [json!(null), json!(true), json!("yes")] {
6958 assert_eq!(
6959 serde_json::from_value::<CursorCapabilities>(json!({ "fork": fork }))
6960 .unwrap()
6961 .fork,
6962 None
6963 );
6964 }
6965 }
6966 }
6967
6968 #[cfg(feature = "unstable_session_cursors")]
6969 #[test]
6970 fn client_session_cursors_capability_is_optional_and_lenient() {
6971 use serde_json::json;
6972
6973 assert_eq!(
6974 serde_json::to_value(
6975 ClientSessionCapabilities::new().cursors(SessionCursorsCapabilities::new())
6976 )
6977 .unwrap(),
6978 json!({ "cursors": {} })
6979 );
6980 assert_eq!(
6981 serde_json::from_value::<ClientSessionCapabilities>(json!({ "cursors": {} }))
6982 .unwrap()
6983 .cursors,
6984 Some(SessionCursorsCapabilities::new())
6985 );
6986 for wire in [
6987 json!({}),
6988 json!({ "cursors": null }),
6989 json!({ "cursors": "yes" }),
6990 ] {
6991 assert_eq!(
6992 serde_json::from_value::<ClientSessionCapabilities>(wire)
6993 .unwrap()
6994 .cursors,
6995 None
6996 );
6997 }
6998 }
6999}