1use std::{path::PathBuf, sync::Arc};
7
8use derive_more::{Display, From};
9#[cfg(all(
10 feature = "schemars",
11 any(feature = "unstable_subagents", feature = "unstable_session_cursors")
12))]
13use schemars::Schema;
14use serde::{Deserialize, Serialize};
15use serde_with::{DefaultOnError, DefaultOnNull, VecSkipError, serde_as, skip_serializing_none};
16#[cfg(any(feature = "unstable_subagents", feature = "unstable_session_cursors"))]
17use std::collections::BTreeMap;
18
19#[cfg(feature = "unstable_auth_status")]
20use super::AuthStatusUpdateNotification;
21#[cfg(feature = "unstable_subagents")]
22use super::Error;
23#[cfg(feature = "unstable_session_cursors")]
24use super::ToolCallId;
25#[cfg(all(
26 feature = "unstable_subagents",
27 feature = "unstable_end_turn_token_usage"
28))]
29use super::Usage;
30use super::{
31 CompleteElicitationNotification, CreateElicitationRequest, CreateElicitationResponse,
32 ElicitationCapabilities,
33};
34use crate::{IntoMaybeUndefined, IntoOption, MaybeUndefined};
35
36use super::{
37 ContentBlock, EnvVariable, ExtNotification, ExtRequest, ExtResponse, Meta, Plan,
38 SessionConfigOption, SessionId, SessionModeId, ToolCall, ToolCallUpdate,
39};
40#[cfg(feature = "unstable_plan_operations")]
41use super::{PlanCapabilities, PlanRemoved, PlanUpdate};
42
43#[cfg(feature = "unstable_mcp_over_acp")]
44use super::mcp::{MCP_MESSAGE_METHOD_NAME, MessageMcpRequest, MessageMcpResponse};
45
46#[serde_as]
54#[skip_serializing_none]
55#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
56#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
57#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = SESSION_UPDATE_NOTIFICATION)))]
58#[serde(rename_all = "camelCase")]
59#[non_exhaustive]
60pub struct SessionNotification {
61 pub session_id: SessionId,
63 pub update: SessionUpdate,
65 #[serde_as(deserialize_as = "DefaultOnError")]
71 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
72 #[serde(default)]
73 #[serde(rename = "_meta")]
74 pub meta: Option<Meta>,
75}
76
77impl SessionNotification {
78 #[must_use]
80 pub fn new(session_id: impl Into<SessionId>, update: SessionUpdate) -> Self {
81 Self {
82 session_id: session_id.into(),
83 update,
84 meta: None,
85 }
86 }
87
88 #[must_use]
94 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
95 self.meta = meta.into_option();
96 self
97 }
98}
99
100#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
106#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
107#[serde(tag = "sessionUpdate", rename_all = "snake_case")]
108#[cfg_attr(feature = "schemars", schemars(extend("discriminator" = {"propertyName": "sessionUpdate"})))]
109#[non_exhaustive]
110pub enum SessionUpdate {
111 UserMessageChunk(ContentChunk),
113 AgentMessageChunk(ContentChunk),
115 AgentThoughtChunk(ContentChunk),
117 ToolCall(ToolCall),
119 ToolCallUpdate(ToolCallUpdate),
121 Plan(Plan),
124 #[cfg(feature = "unstable_plan_operations")]
130 PlanUpdate(PlanUpdate),
131 #[cfg(feature = "unstable_plan_operations")]
137 PlanRemoved(PlanRemoved),
138 AvailableCommandsUpdate(AvailableCommandsUpdate),
140 CurrentModeUpdate(CurrentModeUpdate),
144 ConfigOptionUpdate(ConfigOptionUpdate),
146 SessionInfoUpdate(SessionInfoUpdate),
148 UsageUpdate(UsageUpdate),
150 Notice(Notice),
155 CompactionUpdate(CompactionUpdate),
160 CompactionSummaryChunk(CompactionSummaryChunk),
165 #[cfg(feature = "unstable_prompt_suggestions")]
174 PromptSuggestionsUpdate(PromptSuggestionsUpdate),
175 #[cfg(feature = "unstable_session_cursors")]
184 CursorUpdate(CursorUpdate),
185 #[cfg(feature = "unstable_subagents")]
192 SubagentUpdate(SubagentUpdate),
193 #[cfg(feature = "unstable_subagents")]
200 SessionMessage(SessionMessage),
201 #[cfg(feature = "unstable_subagents")]
207 SessionMessageChunk(SessionMessageChunk),
208}
209
210#[cfg(feature = "unstable_subagents")]
219#[serde_as]
220#[skip_serializing_none]
221#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
222#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
223#[serde(rename_all = "camelCase")]
224#[non_exhaustive]
225pub struct SessionMessageChunk {
226 pub message_id: MessageId,
228 pub content: ContentBlock,
230 #[serde_as(deserialize_as = "DefaultOnError")]
234 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
235 #[serde(default, rename = "_meta")]
236 pub meta: Option<Meta>,
237}
238
239#[cfg(feature = "unstable_subagents")]
240impl SessionMessageChunk {
241 #[must_use]
243 pub fn new(message_id: impl Into<MessageId>, content: ContentBlock) -> Self {
244 Self {
245 message_id: message_id.into(),
246 content,
247 meta: None,
248 }
249 }
250
251 #[must_use]
253 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
254 self.meta = meta.into_option();
255 self
256 }
257}
258
259#[cfg(feature = "unstable_subagents")]
265#[serde_as]
266#[skip_serializing_none]
267#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
268#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
269#[serde(rename_all = "camelCase")]
270#[non_exhaustive]
271pub struct SessionMessage {
272 pub message_id: MessageId,
274 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
278 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
279 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
280 pub sender_session_id: MaybeUndefined<SessionId>,
281 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
285 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
286 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
287 pub recipient_session_id: MaybeUndefined<SessionId>,
288 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
294 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
295 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
296 pub sender_message_id: MaybeUndefined<MessageId>,
297 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
303 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
304 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
305 pub recipient_message_id: MaybeUndefined<MessageId>,
306 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<VecSkipError<_>>>")]
309 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
310 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
311 pub content: MaybeUndefined<Vec<ContentBlock>>,
312 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
316 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
317 #[serde(
318 default,
319 rename = "_meta",
320 skip_serializing_if = "MaybeUndefined::is_undefined"
321 )]
322 pub meta: MaybeUndefined<Meta>,
323}
324
325#[cfg(feature = "unstable_subagents")]
326impl SessionMessage {
327 #[must_use]
329 pub fn new(message_id: impl Into<MessageId>) -> Self {
330 Self {
331 message_id: message_id.into(),
332 sender_session_id: MaybeUndefined::Undefined,
333 recipient_session_id: MaybeUndefined::Undefined,
334 sender_message_id: MaybeUndefined::Undefined,
335 recipient_message_id: MaybeUndefined::Undefined,
336 content: MaybeUndefined::Undefined,
337 meta: MaybeUndefined::Undefined,
338 }
339 }
340
341 #[must_use]
343 pub fn sender_session_id(
344 mut self,
345 sender_session_id: impl IntoMaybeUndefined<SessionId>,
346 ) -> Self {
347 self.sender_session_id = sender_session_id.into_maybe_undefined();
348 self
349 }
350
351 #[must_use]
353 pub fn recipient_session_id(
354 mut self,
355 recipient_session_id: impl IntoMaybeUndefined<SessionId>,
356 ) -> Self {
357 self.recipient_session_id = recipient_session_id.into_maybe_undefined();
358 self
359 }
360
361 #[must_use]
363 pub fn sender_message_id(
364 mut self,
365 sender_message_id: impl IntoMaybeUndefined<MessageId>,
366 ) -> Self {
367 self.sender_message_id = sender_message_id.into_maybe_undefined();
368 self
369 }
370
371 #[must_use]
373 pub fn recipient_message_id(
374 mut self,
375 recipient_message_id: impl IntoMaybeUndefined<MessageId>,
376 ) -> Self {
377 self.recipient_message_id = recipient_message_id.into_maybe_undefined();
378 self
379 }
380
381 #[must_use]
383 pub fn content(mut self, content: impl IntoMaybeUndefined<Vec<ContentBlock>>) -> Self {
384 self.content = content.into_maybe_undefined();
385 self
386 }
387
388 #[must_use]
390 pub fn meta(mut self, meta: impl IntoMaybeUndefined<Meta>) -> Self {
391 self.meta = meta.into_maybe_undefined();
392 self
393 }
394}
395
396#[cfg(all(test, feature = "unstable_subagents"))]
397mod session_message_tests {
398 use super::*;
399 use serde_json::{Value, json};
400
401 #[test]
402 fn envelopes_preserve_participants_and_multimodal_content() {
403 let content = json!([
404 {"type": "text", "text": "Please inspect this"},
405 {"type": "image", "data": "aGVsbG8=", "mimeType": "image/png"}
406 ]);
407 for (transcript, sender, recipient, id) in [
408 ("parent", "parent", "child", "sent-1"),
409 ("child", "parent", "child", "received-9"),
410 ("child", "child", "parent", "sent-2"),
411 ] {
412 let wire = json!({"sessionId": transcript, "update": {
413 "sessionUpdate": "session_message", "messageId": id,
414 "senderSessionId": sender, "recipientSessionId": recipient, "content": content
415 }});
416 let decoded: SessionNotification = serde_json::from_value(wire.clone()).unwrap();
417 assert_eq!(serde_json::to_value(&decoded).unwrap(), wire);
418 assert!(matches!(decoded.update, SessionUpdate::SessionMessage(_)));
419 let message = SessionMessage::new(id)
420 .sender_session_id(SessionId::new(sender))
421 .recipient_session_id(SessionId::new(recipient))
422 .content(vec![]);
423 assert_eq!(serde_json::to_value(message).unwrap()["content"], json!([]));
424 }
425 }
426
427 #[test]
428 fn message_upserts_validate_ids_and_patch_fields() {
429 let base = json!({"sessionUpdate": "session_message", "messageId": "m1",
430 "senderSessionId": "parent", "recipientSessionId": "child", "content": []});
431 {
432 let key = "messageId";
433 let mut missing = base.clone();
434 missing.as_object_mut().unwrap().remove(key);
435 assert!(
436 serde_json::from_value::<SessionUpdate>(missing).is_err(),
437 "{key}"
438 );
439 let mut null = base.clone();
440 null[key] = Value::Null;
441 assert!(
442 serde_json::from_value::<SessionUpdate>(null).is_err(),
443 "{key}"
444 );
445 let mut non_string = base.clone();
446 non_string[key] = json!(42);
447 assert!(
448 serde_json::from_value::<SessionUpdate>(non_string).is_err(),
449 "{key}"
450 );
451 }
452 for content in [None, Some(json!({}))] {
453 let mut wire = base.clone();
454 wire.as_object_mut().unwrap().remove("content");
455 if let Some(content) = content {
456 wire["content"] = content;
457 }
458 let decoded: SessionUpdate = serde_json::from_value(wire).unwrap();
459 let encoded = serde_json::to_value(decoded).unwrap();
460 let mut unchanged = base.clone();
461 unchanged.as_object_mut().unwrap().remove("content");
462 assert_eq!(encoded, unchanged);
463 }
464 let clear = SessionMessage::new("m1")
465 .sender_session_id(SessionId::new("parent"))
466 .recipient_session_id(SessionId::new("child"))
467 .content(None)
468 .meta(None);
469 let mut clear_wire = base.clone();
470 clear_wire["content"] = Value::Null;
471 clear_wire["_meta"] = Value::Null;
472 assert_eq!(
473 serde_json::to_value(&clear).unwrap()["content"],
474 Value::Null
475 );
476 let clear_update: SessionUpdate = serde_json::from_value(clear_wire.clone()).unwrap();
477 assert_eq!(serde_json::to_value(clear_update).unwrap(), clear_wire);
478 assert!(clear.content.is_null());
479 assert!(clear.meta.is_null());
480 for meta in [None, Some(Value::Null), Some(json!({"tag": "value"}))] {
481 let mut wire = base.clone();
482 if let Some(meta) = meta {
483 wire["_meta"] = meta;
484 }
485 let decoded: SessionUpdate = serde_json::from_value(wire.clone()).unwrap();
486 let encoded = serde_json::to_value(decoded).unwrap();
487 assert_eq!(encoded, wire);
488 }
489 let metadata_only = json!({"sessionUpdate": "session_message",
490 "messageId": "m1", "senderSessionId": "parent",
491 "recipientSessionId": "child", "_meta": {"tag": "value"}});
492 let decoded: SessionUpdate = serde_json::from_value(metadata_only.clone()).unwrap();
493 assert_eq!(serde_json::to_value(decoded).unwrap(), metadata_only);
494 let unset = SessionMessage::new("m1");
495 assert_eq!(
496 serde_json::to_value(&unset).unwrap(),
497 json!({"messageId": "m1"})
498 );
499 assert!(unset.content.is_undefined());
500 assert!(unset.meta.is_undefined());
501 let reset = SessionMessage::new("m1").content(vec![]);
502 assert_eq!(serde_json::to_value(reset).unwrap()["content"], json!([]));
503 let malformed: SessionMessage = serde_json::from_value(json!({
504 "messageId": "m1", "senderSessionId": "parent", "recipientSessionId": "child",
505 "content": false, "_meta": false
506 }))
507 .unwrap();
508 assert!(malformed.content.is_undefined());
509 assert!(malformed.meta.is_undefined());
510 }
511
512 #[test]
513 fn first_chunk_and_upsert_share_transcript_local_identity() {
514 for (transcript, id) in [("parent", "sent-1"), ("child", "received-9")] {
515 let wire = json!({"sessionId": transcript, "update": {
516 "sessionUpdate": "session_message_chunk", "messageId": id,
517 "content": {"type": "text", "text": "first"}
518 }});
519 let decoded: SessionNotification = serde_json::from_value(wire.clone()).unwrap();
520 assert_eq!(serde_json::to_value(decoded).unwrap(), wire);
521 let upsert = SessionMessage::new(id)
522 .sender_session_id(SessionId::new("parent"))
523 .recipient_session_id(SessionId::new("child"));
524 let chunk = SessionMessageChunk::new(
525 id,
526 ContentBlock::Text(crate::v1::TextContent::new("first")),
527 );
528 assert_eq!(chunk.message_id, upsert.message_id);
529 assert_eq!(
530 serde_json::to_value(SessionUpdate::SessionMessageChunk(chunk)).unwrap(),
531 wire["update"]
532 );
533 }
534 let wire = json!({"sessionId": "child", "update": {
535 "sessionUpdate": "session_message_chunk", "messageId": "received-9",
536 "content": {"type": "text", "text": "first"}
537 }});
538 let base = wire["update"].clone();
539 for key in ["messageId", "content"] {
540 let mut missing = base.clone();
541 missing.as_object_mut().unwrap().remove(key);
542 assert!(
543 serde_json::from_value::<SessionUpdate>(missing).is_err(),
544 "{key}"
545 );
546 let mut null = base.clone();
547 null[key] = Value::Null;
548 assert!(
549 serde_json::from_value::<SessionUpdate>(null).is_err(),
550 "{key}"
551 );
552 let mut non_string = base.clone();
553 non_string[key] = json!(42);
554 assert!(
555 serde_json::from_value::<SessionUpdate>(non_string).is_err(),
556 "{key}"
557 );
558 }
559 for meta in [None, Some(Value::Null), Some(json!({"chunk": true}))] {
560 let mut value = base.clone();
561 if let Some(meta) = meta {
562 value["_meta"] = meta;
563 }
564 let decoded: SessionUpdate = serde_json::from_value(value.clone()).unwrap();
565 let encoded = serde_json::to_value(decoded).unwrap();
566 if value["_meta"].is_null() {
567 assert_eq!(encoded, base);
568 } else {
569 assert_eq!(encoded, value);
570 }
571 }
572 let with_identity = json!({"sessionUpdate": "session_message_chunk", "messageId": "m1",
574 "senderSessionId": "parent", "recipientSessionId": "child",
575 "senderMessageId": "sent-1", "recipientMessageId": "received-1",
576 "content": {"type": "text", "text": "hello"}});
577 let decoded: SessionUpdate = serde_json::from_value(with_identity).unwrap();
578 assert_eq!(
579 serde_json::to_value(decoded).unwrap(),
580 json!({"sessionUpdate": "session_message_chunk", "messageId": "m1",
581 "content": {"type": "text", "text": "hello"}})
582 );
583 }
584
585 #[cfg(feature = "schemars")]
586 #[test]
587 fn schema_requires_ids_and_chunk_content() {
588 let schema = serde_json::to_value(schemars::schema_for!(SessionMessage)).unwrap();
589 let required = schema["required"].as_array().unwrap();
590 assert_eq!(required, &vec![json!("messageId")]);
591 let chunk = serde_json::to_value(schemars::schema_for!(SessionMessageChunk)).unwrap();
592 let required = chunk["required"].as_array().unwrap();
593 assert_eq!(required.len(), 2);
594 assert!(required.contains(&json!("messageId")));
595 assert!(required.contains(&json!("content")));
596 }
597
598 #[test]
599 fn endpoints_can_arrive_late_or_be_omitted_from_later_events() {
600 let block = ContentBlock::Text(crate::v1::TextContent::new("hello"));
601 let minimal = SessionMessage::new("m1");
602 let first = SessionMessageChunk::new("m1", block.clone());
603 assert_eq!(
604 serde_json::to_value(&minimal).unwrap(),
605 json!({"messageId": "m1"})
606 );
607 assert_eq!(
608 serde_json::to_value(&first).unwrap(),
609 json!({"messageId": "m1", "content": {"type": "text", "text": "hello"}})
610 );
611 let enriched = SessionMessage::new("m1")
612 .sender_session_id(SessionId::new("parent"))
613 .recipient_session_id(SessionId::new("child"));
614 assert_eq!(
615 enriched.sender_session_id,
616 MaybeUndefined::Value(SessionId::new("parent"))
617 );
618 assert_eq!(
619 enriched.recipient_session_id,
620 MaybeUndefined::Value(SessionId::new("child"))
621 );
622 let later = SessionMessage::new("m1").sender_session_id(SessionId::new("parent"));
623 assert_eq!(
624 later.sender_session_id,
625 MaybeUndefined::Value(SessionId::new("parent"))
626 );
627 assert_eq!(later.recipient_session_id, MaybeUndefined::Undefined);
628 let more = SessionMessageChunk::new("m1", block);
629 for update in [
630 SessionUpdate::SessionMessage(minimal),
631 SessionUpdate::SessionMessageChunk(first),
632 SessionUpdate::SessionMessage(enriched),
633 SessionUpdate::SessionMessage(later),
634 SessionUpdate::SessionMessageChunk(more),
635 ] {
636 let wire = serde_json::to_value(&update).unwrap();
637 let decoded: SessionUpdate = serde_json::from_value(wire.clone()).unwrap();
638 assert_eq!(serde_json::to_value(decoded).unwrap(), wire);
639 }
640 }
641
642 #[test]
643 fn null_endpoints_clear_invalid_are_absent_but_message_id_is_required() {
644 let mut base = json!({"sessionUpdate": "session_message", "messageId": "m1",
645 "senderSessionId": null, "recipientSessionId": 42});
646 let decoded: SessionUpdate = serde_json::from_value(base.clone()).unwrap();
647 let encoded = serde_json::to_value(decoded).unwrap();
648 base.as_object_mut().unwrap().remove("recipientSessionId");
649 assert_eq!(encoded, base);
650 for bad in [Value::Null, json!(42)] {
651 let mut invalid = base.clone();
652 invalid["messageId"] = bad;
653 assert!(serde_json::from_value::<SessionUpdate>(invalid).is_err());
654 }
655 }
656
657 #[test]
658 fn message_references_link_views_and_can_arrive_late() {
659 let block = ContentBlock::Text(crate::v1::TextContent::new("hello"));
660 let incoming = SessionMessage::new("received-1")
661 .sender_session_id(SessionId::new("parent"))
662 .recipient_session_id(SessionId::new("child"))
663 .sender_message_id(MessageId::new("sent-1"))
664 .content(vec![block]);
665 let outgoing =
667 SessionMessage::new("sent-1").recipient_message_id(MessageId::new("received-1"));
668 for (update, wire) in [
669 (
670 SessionUpdate::SessionMessage(incoming),
671 json!({"sessionUpdate": "session_message", "messageId": "received-1",
672 "senderSessionId": "parent", "recipientSessionId": "child",
673 "senderMessageId": "sent-1", "content": [{"type": "text", "text": "hello"}]}),
674 ),
675 (
676 SessionUpdate::SessionMessage(outgoing),
677 json!({"sessionUpdate": "session_message", "messageId": "sent-1",
678 "recipientMessageId": "received-1"}),
679 ),
680 ] {
681 assert_eq!(serde_json::to_value(&update).unwrap(), wire);
682 let decoded: SessionUpdate = serde_json::from_value(wire.clone()).unwrap();
683 assert_eq!(decoded, update);
684 }
685
686 let mut wire = json!({"sessionUpdate": "session_message", "messageId": "m1",
687 "senderMessageId": null, "recipientMessageId": 42});
688 let decoded: SessionUpdate = serde_json::from_value(wire.clone()).unwrap();
689 wire.as_object_mut().unwrap().remove("recipientMessageId");
690 assert_eq!(
691 serde_json::to_value(decoded).unwrap(),
692 wire,
693 "null clears a reference and a malformed one is not supplied"
694 );
695 }
696}
697
698#[cfg(all(test, not(feature = "unstable_subagents")))]
699mod disabled_session_message_tests {
700 use super::*;
701 use serde_json::json;
702
703 #[test]
704 fn message_updates_require_subagents_gate() {
705 for (kind, content) in [
706 ("session_message", json!([])),
707 (
708 "session_message_chunk",
709 json!({"type": "text", "text": "hello"}),
710 ),
711 ] {
712 let wire = json!({"sessionUpdate": kind, "messageId": "m1", "content": content});
713 assert!(serde_json::from_value::<SessionUpdate>(wire).is_err());
714 }
715 }
716}
717
718#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
720#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
721#[serde(rename_all = "snake_case")]
722#[non_exhaustive]
723pub enum NoticeSeverity {
724 Info,
726 Warning,
728 Error,
730 #[serde(untagged)]
735 Other(String),
736}
737
738#[serde_as]
748#[skip_serializing_none]
749#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
750#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
751#[serde(rename_all = "camelCase")]
752#[non_exhaustive]
753pub struct Notice {
754 pub severity: NoticeSeverity,
756 #[cfg_attr(feature = "schemars", schemars(length(min = 1)))]
758 pub title: String,
759 #[serde_as(deserialize_as = "DefaultOnError")]
763 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
764 #[serde(default)]
765 pub description: Option<String>,
766 #[serde_as(deserialize_as = "DefaultOnError")]
770 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
771 #[serde(default, rename = "_meta")]
772 pub meta: Option<Meta>,
773}
774
775impl Notice {
776 #[must_use]
778 pub fn new(severity: NoticeSeverity, title: impl Into<String>) -> Self {
779 Self {
780 severity,
781 title: title.into(),
782 description: None,
783 meta: None,
784 }
785 }
786
787 #[must_use]
789 pub fn description(mut self, description: impl IntoOption<String>) -> Self {
790 self.description = description.into_option();
791 self
792 }
793
794 #[must_use]
796 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
797 self.meta = meta.into_option();
798 self
799 }
800}
801
802#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
804#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
805#[serde(transparent)]
806#[from(Arc<str>, String, &'static str)]
807#[non_exhaustive]
808pub struct CompactionId(pub Arc<str>);
809
810impl CompactionId {
811 #[must_use]
813 pub fn new(id: impl Into<Arc<str>>) -> Self {
814 Self(id.into())
815 }
816}
817
818#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
820#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
821#[serde(rename_all = "snake_case")]
822#[non_exhaustive]
823pub enum CompactionStatus {
824 #[default]
826 InProgress,
827 Completed,
829 Failed,
831 Cancelled,
833 #[serde(untagged)]
838 Other(String),
839}
840
841#[serde_as]
850#[skip_serializing_none]
851#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
852#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
853#[serde(rename_all = "camelCase")]
854#[non_exhaustive]
855pub struct CompactionUpdate {
856 pub compaction_id: CompactionId,
858 pub status: CompactionStatus,
860 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<VecSkipError<_>>>")]
862 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
863 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
864 pub summary: MaybeUndefined<Vec<ContentBlock>>,
865 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
867 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
868 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
869 pub error: MaybeUndefined<String>,
870 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
872 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
873 #[serde(
874 rename = "_meta",
875 default,
876 skip_serializing_if = "MaybeUndefined::is_undefined"
877 )]
878 pub meta: MaybeUndefined<Meta>,
879}
880
881impl CompactionUpdate {
882 #[must_use]
884 pub fn new(compaction_id: impl Into<CompactionId>, status: CompactionStatus) -> Self {
885 Self {
886 compaction_id: compaction_id.into(),
887 status,
888 summary: MaybeUndefined::Undefined,
889 error: MaybeUndefined::Undefined,
890 meta: MaybeUndefined::Undefined,
891 }
892 }
893
894 #[must_use]
896 pub fn summary(mut self, summary: impl IntoMaybeUndefined<Vec<ContentBlock>>) -> Self {
897 self.summary = summary.into_maybe_undefined();
898 self
899 }
900
901 #[must_use]
903 pub fn error(mut self, error: impl IntoMaybeUndefined<String>) -> Self {
904 self.error = error.into_maybe_undefined();
905 self
906 }
907
908 #[must_use]
910 pub fn meta(mut self, meta: impl IntoMaybeUndefined<Meta>) -> Self {
911 self.meta = meta.into_maybe_undefined();
912 self
913 }
914}
915
916#[serde_as]
921#[skip_serializing_none]
922#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
923#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
924#[serde(rename_all = "camelCase")]
925#[non_exhaustive]
926pub struct CompactionSummaryChunk {
927 pub compaction_id: CompactionId,
929 pub content: ContentBlock,
931 #[serde_as(deserialize_as = "DefaultOnError")]
933 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
934 #[serde(default, rename = "_meta")]
935 pub meta: Option<Meta>,
936}
937
938impl CompactionSummaryChunk {
939 #[must_use]
941 pub fn new(compaction_id: impl Into<CompactionId>, content: ContentBlock) -> Self {
942 Self {
943 compaction_id: compaction_id.into(),
944 content,
945 meta: None,
946 }
947 }
948
949 #[must_use]
951 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
952 self.meta = meta.into_option();
953 self
954 }
955}
956
957#[cfg(feature = "unstable_session_cursors")]
970#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
971#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
972#[serde(transparent)]
973#[from(forward)]
974#[non_exhaustive]
975pub struct CursorId(pub Arc<str>);
976
977#[cfg(feature = "unstable_session_cursors")]
978impl CursorId {
979 #[must_use]
981 pub fn new(id: impl Into<Self>) -> Self {
982 id.into()
983 }
984}
985
986#[cfg(feature = "unstable_session_cursors")]
1003#[serde_as]
1004#[skip_serializing_none]
1005#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1006#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1007#[serde(rename_all = "camelCase")]
1008#[non_exhaustive]
1009pub struct CursorUpdate {
1010 pub cursor_id: CursorId,
1012 #[serde_as(deserialize_as = "DefaultOnError")]
1017 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1018 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
1019 pub capabilities: MaybeUndefined<CursorCapabilities>,
1020 #[serde(default)]
1026 pub anchor: Option<CursorAnchor>,
1027 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
1029 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1030 #[serde(
1031 rename = "_meta",
1032 default,
1033 skip_serializing_if = "MaybeUndefined::is_undefined"
1034 )]
1035 pub meta: MaybeUndefined<Meta>,
1036}
1037
1038#[cfg(feature = "unstable_session_cursors")]
1039impl CursorUpdate {
1040 #[must_use]
1042 pub fn new(cursor_id: impl Into<CursorId>) -> Self {
1043 Self {
1044 cursor_id: cursor_id.into(),
1045 capabilities: MaybeUndefined::Undefined,
1046 anchor: None,
1047 meta: MaybeUndefined::Undefined,
1048 }
1049 }
1050
1051 #[must_use]
1053 pub fn capabilities(
1054 mut self,
1055 capabilities: impl IntoMaybeUndefined<CursorCapabilities>,
1056 ) -> Self {
1057 self.capabilities = capabilities.into_maybe_undefined();
1058 self
1059 }
1060
1061 #[must_use]
1063 pub fn anchor(mut self, anchor: impl IntoOption<CursorAnchor>) -> Self {
1064 self.anchor = anchor.into_option();
1065 self
1066 }
1067
1068 #[must_use]
1070 pub fn meta(mut self, meta: impl IntoMaybeUndefined<Meta>) -> Self {
1071 self.meta = meta.into_maybe_undefined();
1072 self
1073 }
1074}
1075
1076#[cfg(feature = "unstable_session_cursors")]
1087#[serde_as]
1088#[skip_serializing_none]
1089#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1090#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1091#[serde(rename_all = "camelCase")]
1092#[non_exhaustive]
1093pub struct CursorCapabilities {
1094 #[cfg(feature = "unstable_session_fork")]
1099 #[serde_as(deserialize_as = "DefaultOnError")]
1100 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1101 #[serde(default)]
1102 pub fork: Option<CursorForkCapabilities>,
1103 #[serde_as(deserialize_as = "DefaultOnError")]
1109 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1110 #[serde(default)]
1111 #[serde(rename = "_meta")]
1112 pub meta: Option<Meta>,
1113}
1114
1115#[cfg(feature = "unstable_session_cursors")]
1116impl CursorCapabilities {
1117 #[must_use]
1119 pub fn new() -> Self {
1120 Self::default()
1121 }
1122
1123 #[cfg(feature = "unstable_session_fork")]
1125 #[must_use]
1126 pub fn fork(mut self, fork: impl IntoOption<CursorForkCapabilities>) -> Self {
1127 self.fork = fork.into_option();
1128 self
1129 }
1130
1131 #[must_use]
1137 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1138 self.meta = meta.into_option();
1139 self
1140 }
1141}
1142
1143#[cfg(all(
1151 feature = "unstable_session_cursors",
1152 feature = "unstable_session_fork"
1153))]
1154#[serde_as]
1155#[skip_serializing_none]
1156#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1157#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1158#[non_exhaustive]
1159pub struct CursorForkCapabilities {
1160 #[serde_as(deserialize_as = "DefaultOnError")]
1166 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1167 #[serde(default)]
1168 #[serde(rename = "_meta")]
1169 pub meta: Option<Meta>,
1170}
1171
1172#[cfg(all(
1173 feature = "unstable_session_cursors",
1174 feature = "unstable_session_fork"
1175))]
1176impl CursorForkCapabilities {
1177 #[must_use]
1179 pub fn new() -> Self {
1180 Self::default()
1181 }
1182
1183 #[must_use]
1189 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1190 self.meta = meta.into_option();
1191 self
1192 }
1193}
1194
1195#[cfg(feature = "unstable_session_cursors")]
1207#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1208#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1209#[serde(tag = "type", rename_all = "snake_case")]
1210#[non_exhaustive]
1211pub enum CursorAnchor {
1212 UserMessage(CursorMessageAnchor),
1214 AgentMessage(CursorMessageAnchor),
1216 AgentThought(CursorMessageAnchor),
1218 #[cfg(feature = "unstable_subagents")]
1220 SessionMessage(CursorMessageAnchor),
1221 ToolCall(CursorToolCallAnchor),
1223 Compaction(CursorCompactionAnchor),
1225 #[serde(untagged)]
1234 Other(OtherCursorAnchor),
1235}
1236
1237#[cfg(feature = "unstable_session_cursors")]
1243#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1244#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1245#[serde(rename_all = "snake_case")]
1246#[non_exhaustive]
1247pub enum CursorAnchorPosition {
1248 Before,
1251 After,
1254 #[serde(untagged)]
1260 Other(String),
1261}
1262
1263#[cfg(feature = "unstable_session_cursors")]
1269#[serde_as]
1270#[skip_serializing_none]
1271#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1272#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1273#[serde(rename_all = "camelCase")]
1274#[non_exhaustive]
1275pub struct CursorMessageAnchor {
1276 pub message_id: MessageId,
1278 pub position: CursorAnchorPosition,
1280 #[serde_as(deserialize_as = "DefaultOnError")]
1286 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1287 #[serde(default)]
1288 #[serde(rename = "_meta")]
1289 pub meta: Option<Meta>,
1290}
1291
1292#[cfg(feature = "unstable_session_cursors")]
1293impl CursorMessageAnchor {
1294 #[must_use]
1296 pub fn new(message_id: impl Into<MessageId>, position: CursorAnchorPosition) -> Self {
1297 Self {
1298 message_id: message_id.into(),
1299 position,
1300 meta: None,
1301 }
1302 }
1303
1304 #[must_use]
1310 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1311 self.meta = meta.into_option();
1312 self
1313 }
1314}
1315
1316#[cfg(feature = "unstable_session_cursors")]
1322#[serde_as]
1323#[skip_serializing_none]
1324#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1325#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1326#[serde(rename_all = "camelCase")]
1327#[non_exhaustive]
1328pub struct CursorToolCallAnchor {
1329 pub tool_call_id: ToolCallId,
1331 pub position: CursorAnchorPosition,
1333 #[serde_as(deserialize_as = "DefaultOnError")]
1339 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1340 #[serde(default)]
1341 #[serde(rename = "_meta")]
1342 pub meta: Option<Meta>,
1343}
1344
1345#[cfg(feature = "unstable_session_cursors")]
1346impl CursorToolCallAnchor {
1347 #[must_use]
1349 pub fn new(tool_call_id: impl Into<ToolCallId>, position: CursorAnchorPosition) -> Self {
1350 Self {
1351 tool_call_id: tool_call_id.into(),
1352 position,
1353 meta: None,
1354 }
1355 }
1356
1357 #[must_use]
1363 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1364 self.meta = meta.into_option();
1365 self
1366 }
1367}
1368
1369#[cfg(feature = "unstable_session_cursors")]
1375#[serde_as]
1376#[skip_serializing_none]
1377#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1378#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1379#[serde(rename_all = "camelCase")]
1380#[non_exhaustive]
1381pub struct CursorCompactionAnchor {
1382 pub compaction_id: CompactionId,
1384 pub position: CursorAnchorPosition,
1386 #[serde_as(deserialize_as = "DefaultOnError")]
1392 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1393 #[serde(default)]
1394 #[serde(rename = "_meta")]
1395 pub meta: Option<Meta>,
1396}
1397
1398#[cfg(feature = "unstable_session_cursors")]
1399impl CursorCompactionAnchor {
1400 #[must_use]
1402 pub fn new(compaction_id: impl Into<CompactionId>, position: CursorAnchorPosition) -> Self {
1403 Self {
1404 compaction_id: compaction_id.into(),
1405 position,
1406 meta: None,
1407 }
1408 }
1409
1410 #[must_use]
1416 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1417 self.meta = meta.into_option();
1418 self
1419 }
1420}
1421
1422#[cfg(feature = "unstable_session_cursors")]
1431#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1432#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
1433#[cfg_attr(feature = "schemars", schemars(inline))]
1434#[cfg_attr(feature = "schemars", schemars(transform = other_cursor_anchor_schema))]
1435#[serde(rename_all = "camelCase")]
1436#[non_exhaustive]
1437pub struct OtherCursorAnchor {
1438 #[serde(rename = "type")]
1444 pub type_: String,
1445 #[serde(flatten)]
1448 pub fields: BTreeMap<String, serde_json::Value>,
1449}
1450
1451#[cfg(feature = "unstable_session_cursors")]
1452impl OtherCursorAnchor {
1453 #[must_use]
1455 pub fn new(type_: impl Into<String>, mut fields: BTreeMap<String, serde_json::Value>) -> Self {
1456 fields.remove("type");
1457 Self {
1458 type_: type_.into(),
1459 fields,
1460 }
1461 }
1462}
1463
1464#[cfg(feature = "unstable_session_cursors")]
1465impl<'de> Deserialize<'de> for OtherCursorAnchor {
1466 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1467 where
1468 D: serde::Deserializer<'de>,
1469 {
1470 let mut fields = BTreeMap::<String, serde_json::Value>::deserialize(deserializer)?;
1471 let type_ = fields
1472 .remove("type")
1473 .ok_or_else(|| serde::de::Error::missing_field("type"))?;
1474 let serde_json::Value::String(type_) = type_ else {
1475 return Err(serde::de::Error::custom("`type` must be a string"));
1476 };
1477
1478 if KNOWN_CURSOR_ANCHOR_TYPES.contains(&type_.as_str()) {
1479 return Err(serde::de::Error::custom(format!(
1480 "known cursor anchor `{type_}` did not match its schema"
1481 )));
1482 }
1483
1484 Ok(Self { type_, fields })
1485 }
1486}
1487
1488#[cfg(feature = "unstable_session_cursors")]
1489const KNOWN_CURSOR_ANCHOR_TYPES: &[&str] = &[
1490 "user_message",
1491 "agent_message",
1492 "agent_thought",
1493 #[cfg(feature = "unstable_subagents")]
1494 "session_message",
1495 "tool_call",
1496 "compaction",
1497];
1498
1499#[cfg(all(feature = "unstable_session_cursors", feature = "schemars"))]
1500fn other_cursor_anchor_schema(schema: &mut Schema) {
1501 let known = KNOWN_CURSOR_ANCHOR_TYPES
1502 .iter()
1503 .map(|type_| {
1504 serde_json::json!({
1505 "properties": { "type": { "const": type_, "type": "string" } },
1506 "required": ["type"],
1507 "type": "object"
1508 })
1509 })
1510 .collect::<Vec<_>>();
1511 schema.insert("not".into(), serde_json::json!({ "anyOf": known }));
1512}
1513
1514#[cfg(feature = "unstable_subagents")]
1540#[serde_as]
1541#[skip_serializing_none]
1542#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1543#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1544#[serde(rename_all = "camelCase")]
1545#[non_exhaustive]
1546pub struct SubagentUpdate {
1547 pub session_id: SessionId,
1549 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
1554 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1555 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
1556 pub title: MaybeUndefined<String>,
1557 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
1563 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1564 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
1565 pub description: MaybeUndefined<String>,
1566 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
1573 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1574 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
1575 pub capabilities: MaybeUndefined<SubagentSessionCapabilities>,
1576 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
1583 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1584 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
1585 pub state: MaybeUndefined<StateUpdate>,
1586 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
1593 pub cwd: MaybeUndefined<PathBuf>,
1594 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
1602 pub additional_directories: MaybeUndefined<Vec<PathBuf>>,
1603 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
1610 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1611 #[serde(
1612 default,
1613 rename = "_meta",
1614 skip_serializing_if = "MaybeUndefined::is_undefined"
1615 )]
1616 pub meta: MaybeUndefined<Meta>,
1617}
1618
1619#[cfg(feature = "unstable_subagents")]
1620impl SubagentUpdate {
1621 #[must_use]
1623 pub fn new(session_id: impl Into<SessionId>) -> Self {
1624 Self {
1625 session_id: session_id.into(),
1626 title: MaybeUndefined::Undefined,
1627 description: MaybeUndefined::Undefined,
1628 capabilities: MaybeUndefined::Undefined,
1629 state: MaybeUndefined::Undefined,
1630 cwd: MaybeUndefined::Undefined,
1631 additional_directories: MaybeUndefined::Undefined,
1632 meta: MaybeUndefined::Undefined,
1633 }
1634 }
1635
1636 #[must_use]
1638 pub fn title(mut self, title: impl IntoMaybeUndefined<String>) -> Self {
1639 self.title = title.into_maybe_undefined();
1640 self
1641 }
1642
1643 #[must_use]
1645 pub fn description(mut self, description: impl IntoMaybeUndefined<String>) -> Self {
1646 self.description = description.into_maybe_undefined();
1647 self
1648 }
1649
1650 #[must_use]
1652 pub fn capabilities(
1653 mut self,
1654 capabilities: impl IntoMaybeUndefined<SubagentSessionCapabilities>,
1655 ) -> Self {
1656 self.capabilities = capabilities.into_maybe_undefined();
1657 self
1658 }
1659
1660 #[must_use]
1662 pub fn state(mut self, state: impl IntoMaybeUndefined<StateUpdate>) -> Self {
1663 self.state = state.into_maybe_undefined();
1664 self
1665 }
1666
1667 #[must_use]
1671 pub fn cwd(mut self, cwd: impl IntoMaybeUndefined<PathBuf>) -> Self {
1672 self.cwd = cwd.into_maybe_undefined();
1673 self
1674 }
1675
1676 #[must_use]
1680 pub fn additional_directories(
1681 mut self,
1682 additional_directories: impl IntoMaybeUndefined<Vec<PathBuf>>,
1683 ) -> Self {
1684 self.additional_directories = additional_directories.into_maybe_undefined();
1685 self
1686 }
1687
1688 #[must_use]
1692 pub fn meta(mut self, meta: impl IntoMaybeUndefined<Meta>) -> Self {
1693 self.meta = meta.into_maybe_undefined();
1694 self
1695 }
1696}
1697
1698#[cfg(feature = "unstable_subagents")]
1707#[serde_as]
1708#[skip_serializing_none]
1709#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1710#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1711#[serde(rename_all = "camelCase")]
1712#[non_exhaustive]
1713pub struct SubagentSessionCapabilities {
1714 #[serde_as(deserialize_as = "DefaultOnError")]
1718 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1719 #[serde(default)]
1720 pub cancel: Option<SessionCancelCapabilities>,
1721 #[serde_as(deserialize_as = "DefaultOnError")]
1725 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1726 #[serde(default)]
1727 #[serde(rename = "_meta")]
1728 pub meta: Option<Meta>,
1729}
1730
1731#[cfg(feature = "unstable_subagents")]
1732impl SubagentSessionCapabilities {
1733 #[must_use]
1735 pub fn new() -> Self {
1736 Self::default()
1737 }
1738
1739 #[must_use]
1741 pub fn cancel(mut self, cancel: impl IntoOption<SessionCancelCapabilities>) -> Self {
1742 self.cancel = cancel.into_option();
1743 self
1744 }
1745
1746 #[must_use]
1750 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1751 self.meta = meta.into_option();
1752 self
1753 }
1754}
1755
1756#[cfg(feature = "unstable_subagents")]
1764#[serde_as]
1765#[skip_serializing_none]
1766#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1767#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1768#[non_exhaustive]
1769pub struct SessionCancelCapabilities {
1770 #[serde_as(deserialize_as = "DefaultOnError")]
1776 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1777 #[serde(default)]
1778 #[serde(rename = "_meta")]
1779 pub meta: Option<Meta>,
1780}
1781
1782#[cfg(feature = "unstable_subagents")]
1783impl SessionCancelCapabilities {
1784 #[must_use]
1786 pub fn new() -> Self {
1787 Self::default()
1788 }
1789
1790 #[must_use]
1796 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1797 self.meta = meta.into_option();
1798 self
1799 }
1800}
1801
1802#[cfg(feature = "unstable_subagents")]
1812#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1813#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1814#[serde(tag = "state", rename_all = "snake_case")]
1815#[non_exhaustive]
1816pub enum StateUpdate {
1817 Running(RunningStateUpdate),
1819 Idle(IdleStateUpdate),
1821 RequiresAction(RequiresActionStateUpdate),
1823 Unknown(UnknownStateUpdate),
1827 #[serde(untagged)]
1832 Other(OtherStateUpdate),
1833}
1834
1835#[cfg(feature = "unstable_subagents")]
1837#[serde_as]
1838#[skip_serializing_none]
1839#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1840#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1841#[serde(rename_all = "camelCase")]
1842#[non_exhaustive]
1843pub struct RunningStateUpdate {
1844 #[serde_as(deserialize_as = "DefaultOnError")]
1848 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1849 #[serde(default, rename = "_meta")]
1850 pub meta: Option<Meta>,
1851}
1852
1853#[cfg(feature = "unstable_subagents")]
1854impl RunningStateUpdate {
1855 #[must_use]
1857 pub fn new() -> Self {
1858 Self::default()
1859 }
1860
1861 #[must_use]
1863 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1864 self.meta = meta.into_option();
1865 self
1866 }
1867}
1868
1869#[cfg(feature = "unstable_subagents")]
1873#[serde_as]
1874#[skip_serializing_none]
1875#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1876#[cfg_attr(feature = "schemars", schemars(transform = idle_state_update_schema))]
1877#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1878#[serde(rename_all = "camelCase")]
1879#[non_exhaustive]
1880pub struct IdleStateUpdate {
1881 #[serde(flatten)]
1883 pub stop_reason: Option<IdleStopReason>,
1884 #[cfg(feature = "unstable_end_turn_token_usage")]
1888 #[serde_as(deserialize_as = "DefaultOnError")]
1889 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1890 #[serde(default)]
1891 pub usage: Option<Box<Usage>>,
1892 #[serde_as(deserialize_as = "DefaultOnError")]
1896 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1897 #[serde(default, rename = "_meta")]
1898 pub meta: Option<Meta>,
1899}
1900
1901#[cfg(feature = "unstable_subagents")]
1902impl IdleStateUpdate {
1903 #[must_use]
1905 pub fn new() -> Self {
1906 Self::default()
1907 }
1908
1909 #[must_use]
1911 pub fn stop_reason(mut self, stop_reason: impl IntoOption<IdleStopReason>) -> Self {
1912 self.stop_reason = stop_reason.into_option();
1913 self
1914 }
1915
1916 #[cfg(feature = "unstable_end_turn_token_usage")]
1918 #[must_use]
1919 pub fn usage(mut self, usage: impl IntoOption<Usage>) -> Self {
1920 self.usage = usage.into_option().map(Box::new);
1921 self
1922 }
1923
1924 #[must_use]
1926 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1927 self.meta = meta.into_option();
1928 self
1929 }
1930}
1931
1932#[cfg(all(feature = "unstable_subagents", feature = "schemars"))]
1941fn idle_state_update_schema(schema: &mut Schema) {
1942 if let Some(properties) = schema
1943 .get_mut("properties")
1944 .and_then(serde_json::Value::as_object_mut)
1945 {
1946 properties.insert(
1947 "stopReason".into(),
1948 serde_json::json!({
1949 "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; a malformed value is treated the same way.\n\nSee protocol docs: [Work state](https://agentclientprotocol.com/protocol/v1/subagents#work-state)",
1950 "type": ["string", "null"],
1951 "x-deserialize-default-on-error": true
1952 }),
1953 );
1954 }
1955 let Some(variants) = schema
1956 .get_mut("anyOf")
1957 .and_then(serde_json::Value::as_array_mut)
1958 else {
1959 return;
1960 };
1961 for variant in variants {
1962 if variant.as_object().is_some_and(serde_json::Map::is_empty) {
1963 *variant = serde_json::json!({
1964 "title": "none",
1965 "description": "No stop reason: `stopReason` is omitted or `null`.",
1966 "type": "object",
1967 "properties": {
1968 "stopReason": { "type": "null" }
1969 }
1970 });
1971 }
1972 }
1973}
1974
1975#[cfg(feature = "unstable_subagents")]
1988#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1989#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1990#[serde(tag = "stopReason", rename_all = "snake_case")]
1991#[non_exhaustive]
1992pub enum IdleStopReason {
1993 EndTurn,
1995 MaxTokens,
1997 MaxTurnRequests,
2000 Refusal,
2002 Cancelled,
2004 Error(ErrorStopReason),
2006 #[serde(untagged)]
2011 Other(OtherStopReason),
2012}
2013
2014#[cfg(feature = "unstable_subagents")]
2015impl From<ErrorStopReason> for IdleStopReason {
2016 fn from(value: ErrorStopReason) -> Self {
2017 Self::Error(value)
2018 }
2019}
2020
2021#[cfg(feature = "unstable_subagents")]
2027#[serde_as]
2028#[skip_serializing_none]
2029#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2030#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2031#[serde(rename_all = "camelCase")]
2032#[non_exhaustive]
2033pub struct ErrorStopReason {
2034 #[serde_as(deserialize_as = "DefaultOnError")]
2039 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2040 #[serde(default)]
2041 pub error: Option<Box<Error>>,
2042}
2043
2044#[cfg(feature = "unstable_subagents")]
2045impl ErrorStopReason {
2046 #[must_use]
2048 pub fn new() -> Self {
2049 Self::default()
2050 }
2051
2052 #[must_use]
2054 pub fn error(mut self, error: impl IntoOption<Error>) -> Self {
2055 self.error = error.into_option().map(Box::new);
2056 self
2057 }
2058}
2059
2060#[cfg(feature = "unstable_subagents")]
2066#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2067#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
2068#[cfg_attr(feature = "schemars", schemars(inline))]
2069#[cfg_attr(feature = "schemars", schemars(transform = other_stop_reason_schema))]
2070#[serde(rename_all = "camelCase")]
2071#[non_exhaustive]
2072pub struct OtherStopReason {
2073 pub stop_reason: String,
2075 #[serde(flatten)]
2077 pub fields: BTreeMap<String, serde_json::Value>,
2078}
2079
2080#[cfg(feature = "unstable_subagents")]
2081impl OtherStopReason {
2082 #[must_use]
2084 pub fn new(
2085 stop_reason: impl Into<String>,
2086 mut fields: BTreeMap<String, serde_json::Value>,
2087 ) -> Self {
2088 remove_idle_state_update_fields(&mut fields);
2089 Self {
2090 stop_reason: stop_reason.into(),
2091 fields,
2092 }
2093 }
2094}
2095
2096#[cfg(feature = "unstable_subagents")]
2097impl<'de> Deserialize<'de> for OtherStopReason {
2098 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2099 where
2100 D: serde::Deserializer<'de>,
2101 {
2102 let mut fields = BTreeMap::<String, serde_json::Value>::deserialize(deserializer)?;
2103 let stop_reason = fields
2104 .remove("stopReason")
2105 .ok_or_else(|| serde::de::Error::missing_field("stopReason"))?;
2106 let serde_json::Value::String(stop_reason) = stop_reason else {
2107 return Err(serde::de::Error::custom("`stopReason` must be a string"));
2108 };
2109 if KNOWN_STOP_REASONS.contains(&stop_reason.as_str()) {
2110 return Err(serde::de::Error::custom(format!(
2111 "known stop reason `{stop_reason}` did not match its schema"
2112 )));
2113 }
2114 remove_idle_state_update_fields(&mut fields);
2115 Ok(Self {
2116 stop_reason,
2117 fields,
2118 })
2119 }
2120}
2121
2122#[cfg(feature = "unstable_subagents")]
2123const KNOWN_STOP_REASONS: &[&str] = &[
2124 "end_turn",
2125 "max_tokens",
2126 "max_turn_requests",
2127 "refusal",
2128 "cancelled",
2129 "error",
2130];
2131
2132#[cfg(feature = "unstable_subagents")]
2134fn remove_idle_state_update_fields(fields: &mut BTreeMap<String, serde_json::Value>) {
2135 fields.remove("stopReason");
2136 fields.remove("usage");
2137 fields.remove("_meta");
2138}
2139
2140#[cfg(all(feature = "unstable_subagents", feature = "schemars"))]
2141fn other_stop_reason_schema(schema: &mut Schema) {
2142 let known = KNOWN_STOP_REASONS
2143 .iter()
2144 .map(|stop_reason| {
2145 serde_json::json!({
2146 "properties": { "stopReason": { "const": stop_reason, "type": "string" } },
2147 "required": ["stopReason"],
2148 "type": "object"
2149 })
2150 })
2151 .collect::<Vec<_>>();
2152 schema.insert("not".into(), serde_json::json!({ "anyOf": known }));
2153}
2154
2155#[cfg(feature = "unstable_subagents")]
2157#[serde_as]
2158#[skip_serializing_none]
2159#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2160#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2161#[serde(rename_all = "camelCase")]
2162#[non_exhaustive]
2163pub struct RequiresActionStateUpdate {
2164 #[serde_as(deserialize_as = "DefaultOnError")]
2168 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2169 #[serde(default, rename = "_meta")]
2170 pub meta: Option<Meta>,
2171}
2172
2173#[cfg(feature = "unstable_subagents")]
2174impl RequiresActionStateUpdate {
2175 #[must_use]
2177 pub fn new() -> Self {
2178 Self::default()
2179 }
2180
2181 #[must_use]
2183 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2184 self.meta = meta.into_option();
2185 self
2186 }
2187}
2188
2189#[cfg(feature = "unstable_subagents")]
2206#[serde_as]
2207#[skip_serializing_none]
2208#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2209#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2210#[serde(rename_all = "camelCase")]
2211#[non_exhaustive]
2212pub struct UnknownStateUpdate {
2213 #[serde_as(deserialize_as = "DefaultOnError")]
2217 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2218 #[serde(default, rename = "_meta")]
2219 pub meta: Option<Meta>,
2220}
2221
2222#[cfg(feature = "unstable_subagents")]
2223impl UnknownStateUpdate {
2224 #[must_use]
2226 pub fn new() -> Self {
2227 Self::default()
2228 }
2229
2230 #[must_use]
2232 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2233 self.meta = meta.into_option();
2234 self
2235 }
2236}
2237
2238#[cfg(feature = "unstable_subagents")]
2240#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2241#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
2242#[cfg_attr(feature = "schemars", schemars(inline))]
2243#[cfg_attr(feature = "schemars", schemars(transform = other_state_update_schema))]
2244#[serde(rename_all = "camelCase")]
2245#[non_exhaustive]
2246pub struct OtherStateUpdate {
2247 pub state: String,
2249 #[serde(flatten)]
2251 pub fields: BTreeMap<String, serde_json::Value>,
2252}
2253
2254#[cfg(feature = "unstable_subagents")]
2255impl OtherStateUpdate {
2256 #[must_use]
2258 pub fn new(state: impl Into<String>, mut fields: BTreeMap<String, serde_json::Value>) -> Self {
2259 fields.remove("state");
2260 Self {
2261 state: state.into(),
2262 fields,
2263 }
2264 }
2265}
2266
2267#[cfg(feature = "unstable_subagents")]
2268impl<'de> Deserialize<'de> for OtherStateUpdate {
2269 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2270 where
2271 D: serde::Deserializer<'de>,
2272 {
2273 let mut fields = BTreeMap::<String, serde_json::Value>::deserialize(deserializer)?;
2274 let state = fields
2275 .remove("state")
2276 .ok_or_else(|| serde::de::Error::missing_field("state"))?;
2277 let serde_json::Value::String(state) = state else {
2278 return Err(serde::de::Error::custom("`state` must be a string"));
2279 };
2280 if is_known_state_update(&state) {
2281 return Err(serde::de::Error::custom(format!(
2282 "known state update `{state}` did not match its schema"
2283 )));
2284 }
2285 Ok(Self { state, fields })
2286 }
2287}
2288
2289#[cfg(feature = "unstable_subagents")]
2290const KNOWN_STATE_UPDATE_STATES: &[&str] = &["running", "idle", "requires_action", "unknown"];
2291
2292#[cfg(feature = "unstable_subagents")]
2293fn is_known_state_update(state: &str) -> bool {
2294 KNOWN_STATE_UPDATE_STATES.contains(&state)
2295}
2296
2297#[cfg(all(feature = "unstable_subagents", feature = "schemars"))]
2298fn other_state_update_schema(schema: &mut Schema) {
2299 let known = KNOWN_STATE_UPDATE_STATES
2300 .iter()
2301 .map(|state| {
2302 serde_json::json!({
2303 "properties": { "state": { "const": state, "type": "string" } },
2304 "required": ["state"],
2305 "type": "object"
2306 })
2307 })
2308 .collect::<Vec<_>>();
2309 schema.insert("not".into(), serde_json::json!({ "anyOf": known }));
2310}
2311
2312#[serde_as]
2316#[skip_serializing_none]
2317#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2318#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2319#[serde(rename_all = "camelCase")]
2320#[non_exhaustive]
2321pub struct CurrentModeUpdate {
2322 pub current_mode_id: SessionModeId,
2324 #[serde_as(deserialize_as = "DefaultOnError")]
2330 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2331 #[serde(default)]
2332 #[serde(rename = "_meta")]
2333 pub meta: Option<Meta>,
2334}
2335
2336impl CurrentModeUpdate {
2337 #[must_use]
2339 pub fn new(current_mode_id: impl Into<SessionModeId>) -> Self {
2340 Self {
2341 current_mode_id: current_mode_id.into(),
2342 meta: None,
2343 }
2344 }
2345
2346 #[must_use]
2352 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2353 self.meta = meta.into_option();
2354 self
2355 }
2356}
2357
2358#[serde_as]
2360#[skip_serializing_none]
2361#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2362#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2363#[serde(rename_all = "camelCase")]
2364#[non_exhaustive]
2365pub struct ConfigOptionUpdate {
2366 #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
2368 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
2369 pub config_options: Vec<SessionConfigOption>,
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 ConfigOptionUpdate {
2383 #[must_use]
2385 pub fn new(config_options: Vec<SessionConfigOption>) -> Self {
2386 Self {
2387 config_options,
2388 meta: None,
2389 }
2390 }
2391
2392 #[must_use]
2398 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2399 self.meta = meta.into_option();
2400 self
2401 }
2402}
2403
2404#[serde_as]
2409#[skip_serializing_none]
2410#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2411#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2412#[serde(rename_all = "camelCase")]
2413#[non_exhaustive]
2414pub struct SessionInfoUpdate {
2415 #[serde_as(deserialize_as = "DefaultOnError")]
2417 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2418 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
2419 pub title: MaybeUndefined<String>,
2420 #[serde_as(deserialize_as = "DefaultOnError")]
2422 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2423 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
2424 pub updated_at: MaybeUndefined<String>,
2425 #[serde_as(deserialize_as = "DefaultOnError")]
2431 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2432 #[serde(default)]
2433 #[serde(rename = "_meta")]
2434 pub meta: Option<Meta>,
2435}
2436
2437impl SessionInfoUpdate {
2438 #[must_use]
2440 pub fn new() -> Self {
2441 Self::default()
2442 }
2443
2444 #[must_use]
2446 pub fn title(mut self, title: impl IntoMaybeUndefined<String>) -> Self {
2447 self.title = title.into_maybe_undefined();
2448 self
2449 }
2450
2451 #[must_use]
2453 pub fn updated_at(mut self, updated_at: impl IntoMaybeUndefined<String>) -> Self {
2454 self.updated_at = updated_at.into_maybe_undefined();
2455 self
2456 }
2457
2458 #[must_use]
2464 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2465 self.meta = meta.into_option();
2466 self
2467 }
2468}
2469
2470#[serde_as]
2472#[skip_serializing_none]
2473#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2474#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
2475#[serde(rename_all = "camelCase")]
2476#[non_exhaustive]
2477pub struct UsageUpdate {
2478 pub used: u64,
2480 pub size: u64,
2482 #[serde_as(deserialize_as = "DefaultOnError")]
2484 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2485 #[serde(default)]
2486 pub cost: Option<Cost>,
2487 #[serde_as(deserialize_as = "DefaultOnError")]
2493 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2494 #[serde(default)]
2495 #[serde(rename = "_meta")]
2496 pub meta: Option<Meta>,
2497}
2498
2499impl UsageUpdate {
2500 #[must_use]
2502 pub fn new(used: u64, size: u64) -> Self {
2503 Self {
2504 used,
2505 size,
2506 cost: None,
2507 meta: None,
2508 }
2509 }
2510
2511 #[must_use]
2513 pub fn cost(mut self, cost: impl IntoOption<Cost>) -> Self {
2514 self.cost = cost.into_option();
2515 self
2516 }
2517
2518 #[must_use]
2524 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2525 self.meta = meta.into_option();
2526 self
2527 }
2528}
2529
2530#[serde_as]
2532#[skip_serializing_none]
2533#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2534#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
2535#[serde(rename_all = "camelCase")]
2536#[non_exhaustive]
2537pub struct Cost {
2538 pub amount: f64,
2540 pub currency: String,
2543 #[serde_as(deserialize_as = "DefaultOnError")]
2549 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2550 #[serde(default)]
2551 #[serde(rename = "_meta")]
2552 pub meta: Option<Meta>,
2553}
2554
2555impl Cost {
2556 #[must_use]
2558 pub fn new(amount: f64, currency: impl Into<String>) -> Self {
2559 Self {
2560 amount,
2561 currency: currency.into(),
2562 meta: None,
2563 }
2564 }
2565
2566 #[must_use]
2572 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2573 self.meta = meta.into_option();
2574 self
2575 }
2576}
2577
2578#[serde_as]
2580#[skip_serializing_none]
2581#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2582#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2583#[serde(rename_all = "camelCase")]
2584#[non_exhaustive]
2585pub struct ContentChunk {
2586 pub content: ContentBlock,
2588 #[serde_as(deserialize_as = "DefaultOnError")]
2593 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2594 #[serde(default)]
2595 pub message_id: Option<MessageId>,
2596 #[serde_as(deserialize_as = "DefaultOnError")]
2602 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2603 #[serde(default)]
2604 #[serde(rename = "_meta")]
2605 pub meta: Option<Meta>,
2606}
2607
2608impl ContentChunk {
2609 #[must_use]
2611 pub fn new(content: ContentBlock) -> Self {
2612 Self {
2613 content,
2614 message_id: None,
2615 meta: None,
2616 }
2617 }
2618
2619 #[must_use]
2624 pub fn message_id(mut self, message_id: impl IntoOption<MessageId>) -> Self {
2625 self.message_id = message_id.into_option();
2626 self
2627 }
2628
2629 #[must_use]
2635 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2636 self.meta = meta.into_option();
2637 self
2638 }
2639}
2640
2641#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2643#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
2644#[serde(transparent)]
2645#[from(Arc<str>, String, &'static str)]
2646#[non_exhaustive]
2647pub struct MessageId(pub Arc<str>);
2648
2649impl MessageId {
2650 #[must_use]
2652 pub fn new(id: impl Into<Arc<str>>) -> Self {
2653 Self(id.into())
2654 }
2655}
2656
2657impl IntoOption<MessageId> for &str {
2658 fn into_option(self) -> Option<MessageId> {
2659 Some(MessageId::new(self))
2660 }
2661}
2662
2663#[cfg(feature = "unstable_prompt_suggestions")]
2680#[serde_as]
2681#[skip_serializing_none]
2682#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2683#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2684#[serde(rename_all = "camelCase")]
2685#[non_exhaustive]
2686pub struct PromptSuggestionsUpdate {
2687 #[serde_as(deserialize_as = "VecSkipError<_>")]
2693 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-skip-invalid-items" = true)))]
2694 pub suggestions: Vec<PromptSuggestion>,
2695 #[serde_as(deserialize_as = "DefaultOnError")]
2701 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2702 #[serde(default)]
2703 #[serde(rename = "_meta")]
2704 pub meta: Option<Meta>,
2705}
2706
2707#[cfg(feature = "unstable_prompt_suggestions")]
2708impl PromptSuggestionsUpdate {
2709 #[must_use]
2713 pub fn new(suggestions: Vec<PromptSuggestion>) -> Self {
2714 Self {
2715 suggestions,
2716 meta: None,
2717 }
2718 }
2719
2720 #[must_use]
2726 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2727 self.meta = meta.into_option();
2728 self
2729 }
2730}
2731
2732#[cfg(feature = "unstable_prompt_suggestions")]
2738#[serde_as]
2739#[skip_serializing_none]
2740#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2741#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2742#[serde(rename_all = "camelCase")]
2743#[non_exhaustive]
2744pub struct PromptSuggestion {
2745 #[cfg_attr(feature = "schemars", schemars(length(min = 1)))]
2757 pub prompt: Vec<ContentBlock>,
2758 #[serde_as(deserialize_as = "DefaultOnError")]
2764 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2765 #[serde(default)]
2766 #[serde(rename = "_meta")]
2767 pub meta: Option<Meta>,
2768}
2769
2770#[cfg(feature = "unstable_prompt_suggestions")]
2771impl PromptSuggestion {
2772 #[must_use]
2774 pub fn new(prompt: Vec<ContentBlock>) -> Self {
2775 Self { prompt, meta: None }
2776 }
2777
2778 #[must_use]
2784 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2785 self.meta = meta.into_option();
2786 self
2787 }
2788}
2789
2790#[serde_as]
2792#[skip_serializing_none]
2793#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2794#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2795#[serde(rename_all = "camelCase")]
2796#[non_exhaustive]
2797pub struct AvailableCommandsUpdate {
2798 #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
2800 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
2801 pub available_commands: Vec<AvailableCommand>,
2802 #[serde_as(deserialize_as = "DefaultOnError")]
2808 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2809 #[serde(default)]
2810 #[serde(rename = "_meta")]
2811 pub meta: Option<Meta>,
2812}
2813
2814impl AvailableCommandsUpdate {
2815 #[must_use]
2817 pub fn new(available_commands: Vec<AvailableCommand>) -> Self {
2818 Self {
2819 available_commands,
2820 meta: None,
2821 }
2822 }
2823
2824 #[must_use]
2830 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2831 self.meta = meta.into_option();
2832 self
2833 }
2834}
2835
2836#[serde_as]
2838#[skip_serializing_none]
2839#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2840#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2841#[serde(rename_all = "camelCase")]
2842#[non_exhaustive]
2843pub struct AvailableCommand {
2844 pub name: String,
2846 pub description: String,
2848 #[serde_as(deserialize_as = "DefaultOnError")]
2850 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2851 #[serde(default)]
2852 pub input: Option<AvailableCommandInput>,
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 AvailableCommand {
2866 #[must_use]
2868 pub fn new(name: impl Into<String>, description: impl Into<String>) -> Self {
2869 Self {
2870 name: name.into(),
2871 description: description.into(),
2872 input: None,
2873 meta: None,
2874 }
2875 }
2876
2877 #[must_use]
2879 pub fn input(mut self, input: impl IntoOption<AvailableCommandInput>) -> Self {
2880 self.input = input.into_option();
2881 self
2882 }
2883
2884 #[must_use]
2890 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2891 self.meta = meta.into_option();
2892 self
2893 }
2894}
2895
2896#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2898#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2899#[serde(untagged, rename_all = "camelCase")]
2900#[non_exhaustive]
2901pub enum AvailableCommandInput {
2902 Unstructured(UnstructuredCommandInput),
2904}
2905
2906#[serde_as]
2908#[skip_serializing_none]
2909#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2910#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2911#[serde(rename_all = "camelCase")]
2912#[non_exhaustive]
2913pub struct UnstructuredCommandInput {
2914 pub hint: String,
2916 #[serde_as(deserialize_as = "DefaultOnError")]
2922 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2923 #[serde(default)]
2924 #[serde(rename = "_meta")]
2925 pub meta: Option<Meta>,
2926}
2927
2928impl UnstructuredCommandInput {
2929 #[must_use]
2931 pub fn new(hint: impl Into<String>) -> Self {
2932 Self {
2933 hint: hint.into(),
2934 meta: None,
2935 }
2936 }
2937
2938 #[must_use]
2944 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2945 self.meta = meta.into_option();
2946 self
2947 }
2948}
2949
2950#[serde_as]
2958#[skip_serializing_none]
2959#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2960#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2961#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = SESSION_REQUEST_PERMISSION_METHOD_NAME)))]
2962#[serde(rename_all = "camelCase")]
2963#[non_exhaustive]
2964pub struct RequestPermissionRequest {
2965 pub session_id: SessionId,
2967 pub tool_call: ToolCallUpdate,
2969 pub options: Vec<PermissionOption>,
2971 #[serde_as(deserialize_as = "DefaultOnError")]
2977 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2978 #[serde(default)]
2979 #[serde(rename = "_meta")]
2980 pub meta: Option<Meta>,
2981}
2982
2983impl RequestPermissionRequest {
2984 #[must_use]
2986 pub fn new(
2987 session_id: impl Into<SessionId>,
2988 tool_call: ToolCallUpdate,
2989 options: Vec<PermissionOption>,
2990 ) -> Self {
2991 Self {
2992 session_id: session_id.into(),
2993 tool_call,
2994 options,
2995 meta: None,
2996 }
2997 }
2998
2999 #[must_use]
3005 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3006 self.meta = meta.into_option();
3007 self
3008 }
3009}
3010
3011#[serde_as]
3013#[skip_serializing_none]
3014#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3015#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3016#[serde(rename_all = "camelCase")]
3017#[non_exhaustive]
3018pub struct PermissionOption {
3019 pub option_id: PermissionOptionId,
3021 pub name: String,
3023 pub kind: PermissionOptionKind,
3025 #[serde_as(deserialize_as = "DefaultOnError")]
3031 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3032 #[serde(default)]
3033 #[serde(rename = "_meta")]
3034 pub meta: Option<Meta>,
3035}
3036
3037impl PermissionOption {
3038 #[must_use]
3040 pub fn new(
3041 option_id: impl Into<PermissionOptionId>,
3042 name: impl Into<String>,
3043 kind: PermissionOptionKind,
3044 ) -> Self {
3045 Self {
3046 option_id: option_id.into(),
3047 name: name.into(),
3048 kind,
3049 meta: None,
3050 }
3051 }
3052
3053 #[must_use]
3059 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3060 self.meta = meta.into_option();
3061 self
3062 }
3063}
3064
3065#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3067#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
3068#[serde(transparent)]
3069#[from(Arc<str>, String, &'static str)]
3070#[non_exhaustive]
3071pub struct PermissionOptionId(pub Arc<str>);
3072
3073impl PermissionOptionId {
3074 #[must_use]
3076 pub fn new(id: impl Into<Arc<str>>) -> Self {
3077 Self(id.into())
3078 }
3079}
3080
3081#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3085#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
3086#[serde(rename_all = "snake_case")]
3087#[non_exhaustive]
3088pub enum PermissionOptionKind {
3089 AllowOnce,
3091 AllowAlways,
3093 RejectOnce,
3095 RejectAlways,
3097}
3098
3099#[serde_as]
3101#[skip_serializing_none]
3102#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3103#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3104#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = SESSION_REQUEST_PERMISSION_METHOD_NAME)))]
3105#[serde(rename_all = "camelCase")]
3106#[non_exhaustive]
3107pub struct RequestPermissionResponse {
3108 pub outcome: RequestPermissionOutcome,
3111 #[serde_as(deserialize_as = "DefaultOnError")]
3117 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3118 #[serde(default)]
3119 #[serde(rename = "_meta")]
3120 pub meta: Option<Meta>,
3121}
3122
3123impl RequestPermissionResponse {
3124 #[must_use]
3126 pub fn new(outcome: RequestPermissionOutcome) -> Self {
3127 Self {
3128 outcome,
3129 meta: None,
3130 }
3131 }
3132
3133 #[must_use]
3139 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3140 self.meta = meta.into_option();
3141 self
3142 }
3143}
3144
3145#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3147#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3148#[serde(tag = "outcome", rename_all = "snake_case")]
3149#[cfg_attr(feature = "schemars", schemars(extend("discriminator" = {"propertyName": "outcome"})))]
3150#[non_exhaustive]
3151pub enum RequestPermissionOutcome {
3152 Cancelled,
3160 #[serde(rename_all = "camelCase")]
3162 Selected(SelectedPermissionOutcome),
3163}
3164
3165#[serde_as]
3167#[skip_serializing_none]
3168#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3169#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3170#[serde(rename_all = "camelCase")]
3171#[non_exhaustive]
3172pub struct SelectedPermissionOutcome {
3173 pub option_id: PermissionOptionId,
3175 #[serde_as(deserialize_as = "DefaultOnError")]
3181 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3182 #[serde(default)]
3183 #[serde(rename = "_meta")]
3184 pub meta: Option<Meta>,
3185}
3186
3187impl SelectedPermissionOutcome {
3188 #[must_use]
3190 pub fn new(option_id: impl Into<PermissionOptionId>) -> Self {
3191 Self {
3192 option_id: option_id.into(),
3193 meta: None,
3194 }
3195 }
3196
3197 #[must_use]
3203 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3204 self.meta = meta.into_option();
3205 self
3206 }
3207}
3208
3209#[serde_as]
3215#[skip_serializing_none]
3216#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3217#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3218#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = FS_WRITE_TEXT_FILE_METHOD_NAME)))]
3219#[serde(rename_all = "camelCase")]
3220#[non_exhaustive]
3221pub struct WriteTextFileRequest {
3222 pub session_id: SessionId,
3224 pub path: PathBuf,
3226 pub content: String,
3228 #[serde_as(deserialize_as = "DefaultOnError")]
3234 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3235 #[serde(default)]
3236 #[serde(rename = "_meta")]
3237 pub meta: Option<Meta>,
3238}
3239
3240impl WriteTextFileRequest {
3241 #[must_use]
3243 pub fn new(
3244 session_id: impl Into<SessionId>,
3245 path: impl Into<PathBuf>,
3246 content: impl Into<String>,
3247 ) -> Self {
3248 Self {
3249 session_id: session_id.into(),
3250 path: path.into(),
3251 content: content.into(),
3252 meta: None,
3253 }
3254 }
3255
3256 #[must_use]
3262 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3263 self.meta = meta.into_option();
3264 self
3265 }
3266}
3267
3268crate::serde_util::default_on_null! {
3269 #[serde_as]
3271 #[skip_serializing_none]
3272 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3273 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
3274 #[serde(rename_all = "camelCase")]
3275 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = FS_WRITE_TEXT_FILE_METHOD_NAME)))]
3276 #[non_exhaustive]
3277 pub struct WriteTextFileResponse {
3278 #[serde_as(deserialize_as = "DefaultOnError")]
3284 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3285 #[serde(default)]
3286 #[serde(rename = "_meta")]
3287 pub meta: Option<Meta>,
3288 }
3289}
3290
3291impl WriteTextFileResponse {
3292 #[must_use]
3294 pub fn new() -> Self {
3295 Self::default()
3296 }
3297
3298 #[must_use]
3304 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3305 self.meta = meta.into_option();
3306 self
3307 }
3308}
3309
3310#[serde_as]
3316#[skip_serializing_none]
3317#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3318#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3319#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = FS_READ_TEXT_FILE_METHOD_NAME)))]
3320#[serde(rename_all = "camelCase")]
3321#[non_exhaustive]
3322pub struct ReadTextFileRequest {
3323 pub session_id: SessionId,
3325 pub path: PathBuf,
3327 #[serde(default)]
3329 pub line: Option<u32>,
3330 #[serde(default)]
3332 pub limit: Option<u32>,
3333 #[serde_as(deserialize_as = "DefaultOnError")]
3339 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3340 #[serde(default)]
3341 #[serde(rename = "_meta")]
3342 pub meta: Option<Meta>,
3343}
3344
3345impl ReadTextFileRequest {
3346 #[must_use]
3348 pub fn new(session_id: impl Into<SessionId>, path: impl Into<PathBuf>) -> Self {
3349 Self {
3350 session_id: session_id.into(),
3351 path: path.into(),
3352 line: None,
3353 limit: None,
3354 meta: None,
3355 }
3356 }
3357
3358 #[must_use]
3360 pub fn line(mut self, line: impl IntoOption<u32>) -> Self {
3361 self.line = line.into_option();
3362 self
3363 }
3364
3365 #[must_use]
3367 pub fn limit(mut self, limit: impl IntoOption<u32>) -> Self {
3368 self.limit = limit.into_option();
3369 self
3370 }
3371
3372 #[must_use]
3378 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3379 self.meta = meta.into_option();
3380 self
3381 }
3382}
3383
3384#[serde_as]
3386#[skip_serializing_none]
3387#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3388#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3389#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = FS_READ_TEXT_FILE_METHOD_NAME)))]
3390#[serde(rename_all = "camelCase")]
3391#[non_exhaustive]
3392pub struct ReadTextFileResponse {
3393 pub content: String,
3395 #[serde_as(deserialize_as = "DefaultOnError")]
3401 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3402 #[serde(default)]
3403 #[serde(rename = "_meta")]
3404 pub meta: Option<Meta>,
3405}
3406
3407impl ReadTextFileResponse {
3408 #[must_use]
3410 pub fn new(content: impl Into<String>) -> Self {
3411 Self {
3412 content: content.into(),
3413 meta: None,
3414 }
3415 }
3416
3417 #[must_use]
3423 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3424 self.meta = meta.into_option();
3425 self
3426 }
3427}
3428
3429#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3433#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
3434#[serde(transparent)]
3435#[from(Arc<str>, String, &'static str)]
3436#[non_exhaustive]
3437pub struct TerminalId(pub Arc<str>);
3438
3439impl TerminalId {
3440 #[must_use]
3442 pub fn new(id: impl Into<Arc<str>>) -> Self {
3443 Self(id.into())
3444 }
3445}
3446
3447#[serde_as]
3449#[skip_serializing_none]
3450#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3451#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3452#[serde(rename_all = "camelCase")]
3453#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = TERMINAL_CREATE_METHOD_NAME)))]
3454#[non_exhaustive]
3455pub struct CreateTerminalRequest {
3456 pub session_id: SessionId,
3458 pub command: String,
3460 #[serde_as(deserialize_as = "DefaultOnNull")]
3462 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
3463 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3464 pub args: Vec<String>,
3465 #[serde_as(deserialize_as = "DefaultOnNull")]
3467 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
3468 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3469 pub env: Vec<EnvVariable>,
3470 #[serde(default)]
3472 pub cwd: Option<PathBuf>,
3473 #[serde(default)]
3482 pub output_byte_limit: Option<u64>,
3483 #[serde_as(deserialize_as = "DefaultOnError")]
3489 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3490 #[serde(default)]
3491 #[serde(rename = "_meta")]
3492 pub meta: Option<Meta>,
3493}
3494
3495impl CreateTerminalRequest {
3496 #[must_use]
3498 pub fn new(session_id: impl Into<SessionId>, command: impl Into<String>) -> Self {
3499 Self {
3500 session_id: session_id.into(),
3501 command: command.into(),
3502 args: Vec::new(),
3503 env: Vec::new(),
3504 cwd: None,
3505 output_byte_limit: None,
3506 meta: None,
3507 }
3508 }
3509
3510 #[must_use]
3512 pub fn args(mut self, args: Vec<String>) -> Self {
3513 self.args = args;
3514 self
3515 }
3516
3517 #[must_use]
3519 pub fn env(mut self, env: Vec<EnvVariable>) -> Self {
3520 self.env = env;
3521 self
3522 }
3523
3524 #[must_use]
3526 pub fn cwd(mut self, cwd: impl IntoOption<PathBuf>) -> Self {
3527 self.cwd = cwd.into_option();
3528 self
3529 }
3530
3531 #[must_use]
3540 pub fn output_byte_limit(mut self, output_byte_limit: impl IntoOption<u64>) -> Self {
3541 self.output_byte_limit = output_byte_limit.into_option();
3542 self
3543 }
3544
3545 #[must_use]
3551 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3552 self.meta = meta.into_option();
3553 self
3554 }
3555}
3556
3557#[serde_as]
3559#[skip_serializing_none]
3560#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3561#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3562#[serde(rename_all = "camelCase")]
3563#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = TERMINAL_CREATE_METHOD_NAME)))]
3564#[non_exhaustive]
3565pub struct CreateTerminalResponse {
3566 pub terminal_id: TerminalId,
3568 #[serde_as(deserialize_as = "DefaultOnError")]
3574 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3575 #[serde(default)]
3576 #[serde(rename = "_meta")]
3577 pub meta: Option<Meta>,
3578}
3579
3580impl CreateTerminalResponse {
3581 #[must_use]
3583 pub fn new(terminal_id: impl Into<TerminalId>) -> Self {
3584 Self {
3585 terminal_id: terminal_id.into(),
3586 meta: None,
3587 }
3588 }
3589
3590 #[must_use]
3596 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3597 self.meta = meta.into_option();
3598 self
3599 }
3600}
3601
3602#[serde_as]
3604#[skip_serializing_none]
3605#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3606#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3607#[serde(rename_all = "camelCase")]
3608#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = TERMINAL_OUTPUT_METHOD_NAME)))]
3609#[non_exhaustive]
3610pub struct TerminalOutputRequest {
3611 pub session_id: SessionId,
3613 pub terminal_id: TerminalId,
3615 #[serde_as(deserialize_as = "DefaultOnError")]
3621 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3622 #[serde(default)]
3623 #[serde(rename = "_meta")]
3624 pub meta: Option<Meta>,
3625}
3626
3627impl TerminalOutputRequest {
3628 #[must_use]
3630 pub fn new(session_id: impl Into<SessionId>, terminal_id: impl Into<TerminalId>) -> Self {
3631 Self {
3632 session_id: session_id.into(),
3633 terminal_id: terminal_id.into(),
3634 meta: None,
3635 }
3636 }
3637
3638 #[must_use]
3644 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3645 self.meta = meta.into_option();
3646 self
3647 }
3648}
3649
3650#[serde_as]
3652#[skip_serializing_none]
3653#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3654#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3655#[serde(rename_all = "camelCase")]
3656#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = TERMINAL_OUTPUT_METHOD_NAME)))]
3657#[non_exhaustive]
3658pub struct TerminalOutputResponse {
3659 pub output: String,
3661 pub truncated: bool,
3663 #[serde_as(deserialize_as = "DefaultOnError")]
3665 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3666 #[serde(default)]
3667 pub exit_status: Option<TerminalExitStatus>,
3668 #[serde_as(deserialize_as = "DefaultOnError")]
3674 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3675 #[serde(default)]
3676 #[serde(rename = "_meta")]
3677 pub meta: Option<Meta>,
3678}
3679
3680impl TerminalOutputResponse {
3681 #[must_use]
3683 pub fn new(output: impl Into<String>, truncated: bool) -> Self {
3684 Self {
3685 output: output.into(),
3686 truncated,
3687 exit_status: None,
3688 meta: None,
3689 }
3690 }
3691
3692 #[must_use]
3694 pub fn exit_status(mut self, exit_status: impl IntoOption<TerminalExitStatus>) -> Self {
3695 self.exit_status = exit_status.into_option();
3696 self
3697 }
3698
3699 #[must_use]
3705 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3706 self.meta = meta.into_option();
3707 self
3708 }
3709}
3710
3711#[serde_as]
3713#[skip_serializing_none]
3714#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3715#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3716#[serde(rename_all = "camelCase")]
3717#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = TERMINAL_RELEASE_METHOD_NAME)))]
3718#[non_exhaustive]
3719pub struct ReleaseTerminalRequest {
3720 pub session_id: SessionId,
3722 pub terminal_id: TerminalId,
3724 #[serde_as(deserialize_as = "DefaultOnError")]
3730 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3731 #[serde(default)]
3732 #[serde(rename = "_meta")]
3733 pub meta: Option<Meta>,
3734}
3735
3736impl ReleaseTerminalRequest {
3737 #[must_use]
3739 pub fn new(session_id: impl Into<SessionId>, terminal_id: impl Into<TerminalId>) -> Self {
3740 Self {
3741 session_id: session_id.into(),
3742 terminal_id: terminal_id.into(),
3743 meta: None,
3744 }
3745 }
3746
3747 #[must_use]
3753 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3754 self.meta = meta.into_option();
3755 self
3756 }
3757}
3758
3759crate::serde_util::default_on_null! {
3760 #[serde_as]
3762 #[skip_serializing_none]
3763 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3764 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
3765 #[serde(rename_all = "camelCase")]
3766 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = TERMINAL_RELEASE_METHOD_NAME)))]
3767 #[non_exhaustive]
3768 pub struct ReleaseTerminalResponse {
3769 #[serde_as(deserialize_as = "DefaultOnError")]
3775 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3776 #[serde(default)]
3777 #[serde(rename = "_meta")]
3778 pub meta: Option<Meta>,
3779 }
3780}
3781
3782impl ReleaseTerminalResponse {
3783 #[must_use]
3785 pub fn new() -> Self {
3786 Self::default()
3787 }
3788
3789 #[must_use]
3795 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3796 self.meta = meta.into_option();
3797 self
3798 }
3799}
3800
3801#[serde_as]
3803#[skip_serializing_none]
3804#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3805#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3806#[serde(rename_all = "camelCase")]
3807#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = TERMINAL_KILL_METHOD_NAME)))]
3808#[non_exhaustive]
3809pub struct KillTerminalRequest {
3810 pub session_id: SessionId,
3812 pub terminal_id: TerminalId,
3814 #[serde_as(deserialize_as = "DefaultOnError")]
3820 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3821 #[serde(default)]
3822 #[serde(rename = "_meta")]
3823 pub meta: Option<Meta>,
3824}
3825
3826impl KillTerminalRequest {
3827 #[must_use]
3829 pub fn new(session_id: impl Into<SessionId>, terminal_id: impl Into<TerminalId>) -> Self {
3830 Self {
3831 session_id: session_id.into(),
3832 terminal_id: terminal_id.into(),
3833 meta: None,
3834 }
3835 }
3836
3837 #[must_use]
3843 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3844 self.meta = meta.into_option();
3845 self
3846 }
3847}
3848
3849crate::serde_util::default_on_null! {
3850 #[serde_as]
3852 #[skip_serializing_none]
3853 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3854 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
3855 #[serde(rename_all = "camelCase")]
3856 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = TERMINAL_KILL_METHOD_NAME)))]
3857 #[non_exhaustive]
3858 pub struct KillTerminalResponse {
3859 #[serde_as(deserialize_as = "DefaultOnError")]
3865 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3866 #[serde(default)]
3867 #[serde(rename = "_meta")]
3868 pub meta: Option<Meta>,
3869 }
3870}
3871
3872impl KillTerminalResponse {
3873 #[must_use]
3875 pub fn new() -> Self {
3876 Self::default()
3877 }
3878
3879 #[must_use]
3885 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3886 self.meta = meta.into_option();
3887 self
3888 }
3889}
3890
3891#[serde_as]
3893#[skip_serializing_none]
3894#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3895#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3896#[serde(rename_all = "camelCase")]
3897#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = TERMINAL_WAIT_FOR_EXIT_METHOD_NAME)))]
3898#[non_exhaustive]
3899pub struct WaitForTerminalExitRequest {
3900 pub session_id: SessionId,
3902 pub terminal_id: TerminalId,
3904 #[serde_as(deserialize_as = "DefaultOnError")]
3910 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3911 #[serde(default)]
3912 #[serde(rename = "_meta")]
3913 pub meta: Option<Meta>,
3914}
3915
3916impl WaitForTerminalExitRequest {
3917 #[must_use]
3919 pub fn new(session_id: impl Into<SessionId>, terminal_id: impl Into<TerminalId>) -> Self {
3920 Self {
3921 session_id: session_id.into(),
3922 terminal_id: terminal_id.into(),
3923 meta: None,
3924 }
3925 }
3926
3927 #[must_use]
3933 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3934 self.meta = meta.into_option();
3935 self
3936 }
3937}
3938
3939crate::serde_util::default_on_null! {
3940 #[serde_as]
3942 #[skip_serializing_none]
3943 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3944 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
3945 #[serde(rename_all = "camelCase")]
3946 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = TERMINAL_WAIT_FOR_EXIT_METHOD_NAME)))]
3947 #[non_exhaustive]
3948 pub struct WaitForTerminalExitResponse {
3949 #[serde(flatten)]
3951 pub exit_status: TerminalExitStatus,
3952 #[serde_as(deserialize_as = "DefaultOnError")]
3958 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3959 #[serde(default)]
3960 #[serde(rename = "_meta")]
3961 pub meta: Option<Meta>,
3962 }
3963}
3964
3965impl WaitForTerminalExitResponse {
3966 #[must_use]
3968 pub fn new(exit_status: TerminalExitStatus) -> Self {
3969 Self {
3970 exit_status,
3971 meta: None,
3972 }
3973 }
3974
3975 #[must_use]
3981 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3982 self.meta = meta.into_option();
3983 self
3984 }
3985}
3986
3987#[serde_as]
3989#[skip_serializing_none]
3990#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3991#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3992#[serde(rename_all = "camelCase")]
3993#[non_exhaustive]
3994pub struct TerminalExitStatus {
3995 #[serde_as(deserialize_as = "DefaultOnError")]
3997 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3998 #[serde(default)]
3999 pub exit_code: Option<u32>,
4000 #[serde_as(deserialize_as = "DefaultOnError")]
4002 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4003 #[serde(default)]
4004 pub signal: Option<String>,
4005 #[serde_as(deserialize_as = "DefaultOnError")]
4011 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4012 #[serde(default)]
4013 #[serde(rename = "_meta")]
4014 pub meta: Option<Meta>,
4015}
4016
4017impl TerminalExitStatus {
4018 #[must_use]
4020 pub fn new() -> Self {
4021 Self::default()
4022 }
4023
4024 #[must_use]
4026 pub fn exit_code(mut self, exit_code: impl IntoOption<u32>) -> Self {
4027 self.exit_code = exit_code.into_option();
4028 self
4029 }
4030
4031 #[must_use]
4033 pub fn signal(mut self, signal: impl IntoOption<String>) -> Self {
4034 self.signal = signal.into_option();
4035 self
4036 }
4037
4038 #[must_use]
4044 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4045 self.meta = meta.into_option();
4046 self
4047 }
4048}
4049
4050#[serde_as]
4059#[skip_serializing_none]
4060#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4061#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4062#[serde(rename_all = "camelCase")]
4063#[non_exhaustive]
4064pub struct ClientCapabilities {
4065 #[serde_as(deserialize_as = "DefaultOnError")]
4068 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4069 #[serde(default)]
4070 pub fs: FileSystemCapabilities,
4071 #[serde_as(deserialize_as = "DefaultOnError")]
4073 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4074 #[serde(default)]
4075 pub terminal: bool,
4076 #[serde_as(deserialize_as = "DefaultOnError")]
4081 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4082 #[serde(default)]
4083 pub session: Option<ClientSessionCapabilities>,
4084 #[cfg(feature = "unstable_subagents")]
4095 #[serde_as(deserialize_as = "DefaultOnError")]
4096 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4097 #[serde(default)]
4098 pub subagents: Option<SubagentCapabilities>,
4099 #[cfg(feature = "unstable_plan_operations")]
4108 #[serde_as(deserialize_as = "DefaultOnError")]
4109 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4110 #[serde(default)]
4111 pub plan: Option<PlanCapabilities>,
4112 #[serde_as(deserialize_as = "DefaultOnError")]
4116 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4117 #[serde(default)]
4118 pub auth: AuthCapabilities,
4119 #[serde_as(deserialize_as = "DefaultOnError")]
4125 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4126 #[serde(default)]
4127 pub elicitation: Option<ElicitationCapabilities>,
4128 #[serde_as(deserialize_as = "DefaultOnError")]
4134 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4135 #[serde(default)]
4136 #[serde(rename = "_meta")]
4137 pub meta: Option<Meta>,
4138}
4139
4140impl ClientCapabilities {
4141 #[must_use]
4143 pub fn new() -> Self {
4144 Self::default()
4145 }
4146
4147 #[must_use]
4150 pub fn fs(mut self, fs: FileSystemCapabilities) -> Self {
4151 self.fs = fs;
4152 self
4153 }
4154
4155 #[must_use]
4157 pub fn terminal(mut self, terminal: bool) -> Self {
4158 self.terminal = terminal;
4159 self
4160 }
4161
4162 #[must_use]
4164 pub fn session(mut self, session: impl IntoOption<ClientSessionCapabilities>) -> Self {
4165 self.session = session.into_option();
4166 self
4167 }
4168
4169 #[cfg(feature = "unstable_subagents")]
4175 #[must_use]
4176 pub fn subagents(mut self, subagents: impl IntoOption<SubagentCapabilities>) -> Self {
4177 self.subagents = subagents.into_option();
4178 self
4179 }
4180
4181 #[cfg(feature = "unstable_plan_operations")]
4190 #[must_use]
4191 pub fn plan(mut self, plan: impl IntoOption<PlanCapabilities>) -> Self {
4192 self.plan = plan.into_option();
4193 self
4194 }
4195
4196 #[must_use]
4200 pub fn auth(mut self, auth: AuthCapabilities) -> Self {
4201 self.auth = auth;
4202 self
4203 }
4204
4205 #[must_use]
4208 pub fn elicitation(mut self, elicitation: impl IntoOption<ElicitationCapabilities>) -> Self {
4209 self.elicitation = elicitation.into_option();
4210 self
4211 }
4212
4213 #[must_use]
4219 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4220 self.meta = meta.into_option();
4221 self
4222 }
4223}
4224
4225#[cfg(feature = "unstable_subagents")]
4236#[serde_as]
4237#[skip_serializing_none]
4238#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4239#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4240#[non_exhaustive]
4241pub struct SubagentCapabilities {
4242 #[serde_as(deserialize_as = "DefaultOnError")]
4246 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4247 #[serde(default)]
4248 #[serde(rename = "_meta")]
4249 pub meta: Option<Meta>,
4250}
4251
4252#[cfg(feature = "unstable_subagents")]
4253impl SubagentCapabilities {
4254 #[must_use]
4256 pub fn new() -> Self {
4257 Self::default()
4258 }
4259
4260 #[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#[serde_as]
4272#[skip_serializing_none]
4273#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4274#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4275#[serde(rename_all = "camelCase")]
4276#[non_exhaustive]
4277pub struct ClientSessionCapabilities {
4278 #[serde_as(deserialize_as = "DefaultOnError")]
4281 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4282 #[serde(default)]
4283 pub compaction: Option<CompactionCapabilities>,
4284 #[serde_as(deserialize_as = "DefaultOnError")]
4289 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4290 #[serde(default)]
4291 pub config_options: Option<SessionConfigOptionsCapabilities>,
4292 #[serde_as(deserialize_as = "DefaultOnError")]
4297 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4298 #[serde(default)]
4299 pub notices: Option<NoticeCapabilities>,
4300 #[cfg(feature = "unstable_prompt_suggestions")]
4310 #[serde_as(deserialize_as = "DefaultOnError")]
4311 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4312 #[serde(default)]
4313 pub prompt_suggestions: Option<PromptSuggestionsCapabilities>,
4314 #[cfg(feature = "unstable_session_cursors")]
4323 #[serde_as(deserialize_as = "DefaultOnError")]
4324 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4325 #[serde(default)]
4326 pub cursors: Option<SessionCursorsCapabilities>,
4327 #[serde_as(deserialize_as = "DefaultOnError")]
4333 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4334 #[serde(default)]
4335 #[serde(rename = "_meta")]
4336 pub meta: Option<Meta>,
4337}
4338
4339impl ClientSessionCapabilities {
4340 #[must_use]
4342 pub fn new() -> Self {
4343 Self::default()
4344 }
4345
4346 #[must_use]
4348 pub fn compaction(mut self, compaction: impl IntoOption<CompactionCapabilities>) -> Self {
4349 self.compaction = compaction.into_option();
4350 self
4351 }
4352
4353 #[must_use]
4358 pub fn config_options(
4359 mut self,
4360 config_options: impl IntoOption<SessionConfigOptionsCapabilities>,
4361 ) -> Self {
4362 self.config_options = config_options.into_option();
4363 self
4364 }
4365
4366 #[must_use]
4368 pub fn notices(mut self, notices: impl IntoOption<NoticeCapabilities>) -> Self {
4369 self.notices = notices.into_option();
4370 self
4371 }
4372
4373 #[cfg(feature = "unstable_prompt_suggestions")]
4379 #[must_use]
4380 pub fn prompt_suggestions(
4381 mut self,
4382 prompt_suggestions: impl IntoOption<PromptSuggestionsCapabilities>,
4383 ) -> Self {
4384 self.prompt_suggestions = prompt_suggestions.into_option();
4385 self
4386 }
4387
4388 #[cfg(feature = "unstable_session_cursors")]
4394 #[must_use]
4395 pub fn cursors(mut self, cursors: impl IntoOption<SessionCursorsCapabilities>) -> Self {
4396 self.cursors = cursors.into_option();
4397 self
4398 }
4399
4400 #[must_use]
4406 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4407 self.meta = meta.into_option();
4408 self
4409 }
4410}
4411
4412#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4414#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4415#[serde(rename_all = "camelCase")]
4416#[non_exhaustive]
4417pub struct CompactionCapabilities {}
4418
4419impl CompactionCapabilities {
4420 #[must_use]
4422 pub fn new() -> Self {
4423 Self {}
4424 }
4425}
4426
4427#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4429#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4430#[serde(rename_all = "camelCase")]
4431#[non_exhaustive]
4432pub struct NoticeCapabilities {}
4433
4434impl NoticeCapabilities {
4435 #[must_use]
4437 pub fn new() -> Self {
4438 Self {}
4439 }
4440}
4441
4442#[cfg(feature = "unstable_session_cursors")]
4450#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4451#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4452#[serde(rename_all = "camelCase")]
4453#[non_exhaustive]
4454pub struct SessionCursorsCapabilities {}
4455
4456#[cfg(feature = "unstable_session_cursors")]
4457impl SessionCursorsCapabilities {
4458 #[must_use]
4460 pub fn new() -> Self {
4461 Self {}
4462 }
4463}
4464
4465#[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#[serde(rename_all = "camelCase")]
4481#[non_exhaustive]
4482pub struct PromptSuggestionsCapabilities {
4483 #[serde_as(deserialize_as = "DefaultOnError")]
4488 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4489 #[serde(default)]
4490 pub image: Option<PromptSuggestionsImageCapabilities>,
4491 #[serde_as(deserialize_as = "DefaultOnError")]
4496 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4497 #[serde(default)]
4498 pub audio: Option<PromptSuggestionsAudioCapabilities>,
4499 #[serde_as(deserialize_as = "DefaultOnError")]
4505 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4506 #[serde(default)]
4507 pub embedded_context: Option<PromptSuggestionsEmbeddedContextCapabilities>,
4508 #[serde_as(deserialize_as = "DefaultOnError")]
4514 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4515 #[serde(default)]
4516 #[serde(rename = "_meta")]
4517 pub meta: Option<Meta>,
4518}
4519
4520#[cfg(feature = "unstable_prompt_suggestions")]
4521impl PromptSuggestionsCapabilities {
4522 #[must_use]
4524 pub fn new() -> Self {
4525 Self::default()
4526 }
4527
4528 #[must_use]
4530 pub fn image(mut self, image: impl IntoOption<PromptSuggestionsImageCapabilities>) -> Self {
4531 self.image = image.into_option();
4532 self
4533 }
4534
4535 #[must_use]
4537 pub fn audio(mut self, audio: impl IntoOption<PromptSuggestionsAudioCapabilities>) -> Self {
4538 self.audio = audio.into_option();
4539 self
4540 }
4541
4542 #[must_use]
4544 pub fn embedded_context(
4545 mut self,
4546 embedded_context: impl IntoOption<PromptSuggestionsEmbeddedContextCapabilities>,
4547 ) -> Self {
4548 self.embedded_context = embedded_context.into_option();
4549 self
4550 }
4551
4552 #[must_use]
4558 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4559 self.meta = meta.into_option();
4560 self
4561 }
4562}
4563
4564#[cfg(feature = "unstable_prompt_suggestions")]
4572#[serde_as]
4573#[skip_serializing_none]
4574#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4575#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4576#[non_exhaustive]
4577pub struct PromptSuggestionsImageCapabilities {
4578 #[serde_as(deserialize_as = "DefaultOnError")]
4584 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4585 #[serde(default)]
4586 #[serde(rename = "_meta")]
4587 pub meta: Option<Meta>,
4588}
4589
4590#[cfg(feature = "unstable_prompt_suggestions")]
4591impl PromptSuggestionsImageCapabilities {
4592 #[must_use]
4594 pub fn new() -> Self {
4595 Self::default()
4596 }
4597
4598 #[must_use]
4604 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4605 self.meta = meta.into_option();
4606 self
4607 }
4608}
4609
4610#[cfg(feature = "unstable_prompt_suggestions")]
4618#[serde_as]
4619#[skip_serializing_none]
4620#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4621#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4622#[non_exhaustive]
4623pub struct PromptSuggestionsAudioCapabilities {
4624 #[serde_as(deserialize_as = "DefaultOnError")]
4630 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4631 #[serde(default)]
4632 #[serde(rename = "_meta")]
4633 pub meta: Option<Meta>,
4634}
4635
4636#[cfg(feature = "unstable_prompt_suggestions")]
4637impl PromptSuggestionsAudioCapabilities {
4638 #[must_use]
4640 pub fn new() -> Self {
4641 Self::default()
4642 }
4643
4644 #[must_use]
4650 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4651 self.meta = meta.into_option();
4652 self
4653 }
4654}
4655
4656#[cfg(feature = "unstable_prompt_suggestions")]
4665#[serde_as]
4666#[skip_serializing_none]
4667#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4668#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4669#[non_exhaustive]
4670pub struct PromptSuggestionsEmbeddedContextCapabilities {
4671 #[serde_as(deserialize_as = "DefaultOnError")]
4677 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4678 #[serde(default)]
4679 #[serde(rename = "_meta")]
4680 pub meta: Option<Meta>,
4681}
4682
4683#[cfg(feature = "unstable_prompt_suggestions")]
4684impl PromptSuggestionsEmbeddedContextCapabilities {
4685 #[must_use]
4687 pub fn new() -> Self {
4688 Self::default()
4689 }
4690
4691 #[must_use]
4697 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4698 self.meta = meta.into_option();
4699 self
4700 }
4701}
4702
4703#[serde_as]
4705#[skip_serializing_none]
4706#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4707#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4708#[serde(rename_all = "camelCase")]
4709#[non_exhaustive]
4710pub struct SessionConfigOptionsCapabilities {
4711 #[serde_as(deserialize_as = "DefaultOnError")]
4718 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4719 #[serde(default)]
4720 pub boolean: Option<BooleanConfigOptionCapabilities>,
4721 #[serde_as(deserialize_as = "DefaultOnError")]
4727 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4728 #[serde(default)]
4729 #[serde(rename = "_meta")]
4730 pub meta: Option<Meta>,
4731}
4732
4733impl SessionConfigOptionsCapabilities {
4734 #[must_use]
4736 pub fn new() -> Self {
4737 Self::default()
4738 }
4739
4740 #[must_use]
4747 pub fn boolean(mut self, boolean: impl IntoOption<BooleanConfigOptionCapabilities>) -> Self {
4748 self.boolean = boolean.into_option();
4749 self
4750 }
4751
4752 #[must_use]
4758 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4759 self.meta = meta.into_option();
4760 self
4761 }
4762}
4763
4764#[serde_as]
4768#[skip_serializing_none]
4769#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4770#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4771#[non_exhaustive]
4772pub struct BooleanConfigOptionCapabilities {
4773 #[serde_as(deserialize_as = "DefaultOnError")]
4779 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4780 #[serde(default)]
4781 #[serde(rename = "_meta")]
4782 pub meta: Option<Meta>,
4783}
4784
4785impl BooleanConfigOptionCapabilities {
4786 #[must_use]
4788 pub fn new() -> Self {
4789 Self::default()
4790 }
4791
4792 #[must_use]
4798 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4799 self.meta = meta.into_option();
4800 self
4801 }
4802}
4803
4804#[serde_as]
4810#[skip_serializing_none]
4811#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4812#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4813#[serde(rename_all = "camelCase")]
4814#[non_exhaustive]
4815pub struct AuthCapabilities {
4816 #[serde_as(deserialize_as = "DefaultOnError")]
4822 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4823 #[serde(default)]
4824 pub terminal: bool,
4825 #[serde_as(deserialize_as = "DefaultOnError")]
4831 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4832 #[serde(default)]
4833 #[serde(rename = "_meta")]
4834 pub meta: Option<Meta>,
4835}
4836
4837impl AuthCapabilities {
4838 #[must_use]
4840 pub fn new() -> Self {
4841 Self::default()
4842 }
4843
4844 #[must_use]
4851 pub fn terminal(mut self, terminal: bool) -> Self {
4852 self.terminal = terminal;
4853 self
4854 }
4855
4856 #[must_use]
4862 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4863 self.meta = meta.into_option();
4864 self
4865 }
4866}
4867
4868#[serde_as]
4872#[skip_serializing_none]
4873#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4874#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4875#[serde(rename_all = "camelCase")]
4876#[non_exhaustive]
4877pub struct FileSystemCapabilities {
4878 #[serde_as(deserialize_as = "DefaultOnError")]
4880 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4881 #[serde(default)]
4882 pub read_text_file: bool,
4883 #[serde_as(deserialize_as = "DefaultOnError")]
4885 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4886 #[serde(default)]
4887 pub write_text_file: bool,
4888 #[serde_as(deserialize_as = "DefaultOnError")]
4894 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4895 #[serde(default)]
4896 #[serde(rename = "_meta")]
4897 pub meta: Option<Meta>,
4898}
4899
4900impl FileSystemCapabilities {
4901 #[must_use]
4903 pub fn new() -> Self {
4904 Self::default()
4905 }
4906
4907 #[must_use]
4909 pub fn read_text_file(mut self, read_text_file: bool) -> Self {
4910 self.read_text_file = read_text_file;
4911 self
4912 }
4913
4914 #[must_use]
4916 pub fn write_text_file(mut self, write_text_file: bool) -> Self {
4917 self.write_text_file = write_text_file;
4918 self
4919 }
4920
4921 #[must_use]
4927 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4928 self.meta = meta.into_option();
4929 self
4930 }
4931}
4932
4933#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4939#[non_exhaustive]
4940pub struct ClientMethodNames {
4941 pub session_request_permission: &'static str,
4943 pub session_update: &'static str,
4945 pub fs_write_text_file: &'static str,
4947 pub fs_read_text_file: &'static str,
4949 pub terminal_create: &'static str,
4951 pub terminal_output: &'static str,
4953 pub terminal_release: &'static str,
4955 pub terminal_wait_for_exit: &'static str,
4957 pub terminal_kill: &'static str,
4959 #[cfg(feature = "unstable_mcp_over_acp")]
4961 pub mcp_message: &'static str,
4962 pub elicitation_create: &'static str,
4964 pub elicitation_complete: &'static str,
4966 #[cfg(feature = "unstable_auth_status")]
4968 pub auth_status_update: &'static str,
4969}
4970
4971pub const CLIENT_METHOD_NAMES: ClientMethodNames = ClientMethodNames {
4973 session_update: SESSION_UPDATE_NOTIFICATION,
4974 session_request_permission: SESSION_REQUEST_PERMISSION_METHOD_NAME,
4975 fs_write_text_file: FS_WRITE_TEXT_FILE_METHOD_NAME,
4976 fs_read_text_file: FS_READ_TEXT_FILE_METHOD_NAME,
4977 terminal_create: TERMINAL_CREATE_METHOD_NAME,
4978 terminal_output: TERMINAL_OUTPUT_METHOD_NAME,
4979 terminal_release: TERMINAL_RELEASE_METHOD_NAME,
4980 terminal_wait_for_exit: TERMINAL_WAIT_FOR_EXIT_METHOD_NAME,
4981 terminal_kill: TERMINAL_KILL_METHOD_NAME,
4982 #[cfg(feature = "unstable_mcp_over_acp")]
4983 mcp_message: MCP_MESSAGE_METHOD_NAME,
4984 elicitation_create: ELICITATION_CREATE_METHOD_NAME,
4985 elicitation_complete: ELICITATION_COMPLETE_NOTIFICATION,
4986 #[cfg(feature = "unstable_auth_status")]
4987 auth_status_update: AUTH_STATUS_UPDATE_NOTIFICATION,
4988};
4989
4990pub(crate) const SESSION_UPDATE_NOTIFICATION: &str = "session/update";
4992pub(crate) const SESSION_REQUEST_PERMISSION_METHOD_NAME: &str = "session/request_permission";
4994pub(crate) const FS_WRITE_TEXT_FILE_METHOD_NAME: &str = "fs/write_text_file";
4996pub(crate) const FS_READ_TEXT_FILE_METHOD_NAME: &str = "fs/read_text_file";
4998pub(crate) const TERMINAL_CREATE_METHOD_NAME: &str = "terminal/create";
5000pub(crate) const TERMINAL_OUTPUT_METHOD_NAME: &str = "terminal/output";
5002pub(crate) const TERMINAL_RELEASE_METHOD_NAME: &str = "terminal/release";
5004pub(crate) const TERMINAL_WAIT_FOR_EXIT_METHOD_NAME: &str = "terminal/wait_for_exit";
5006pub(crate) const TERMINAL_KILL_METHOD_NAME: &str = "terminal/kill";
5008pub(crate) const ELICITATION_CREATE_METHOD_NAME: &str = "elicitation/create";
5010pub(crate) const ELICITATION_COMPLETE_NOTIFICATION: &str = "elicitation/complete";
5012#[cfg(feature = "unstable_auth_status")]
5014pub(crate) const AUTH_STATUS_UPDATE_NOTIFICATION: &str = "auth/status_update";
5015
5016#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5023#[derive(Clone, Debug, Serialize, Deserialize)]
5024#[serde(untagged)]
5025#[cfg_attr(feature = "schemars", schemars(inline))]
5026#[non_exhaustive]
5027#[allow(clippy::large_enum_variant)]
5028pub enum AgentRequest {
5029 WriteTextFileRequest(WriteTextFileRequest),
5036 ReadTextFileRequest(ReadTextFileRequest),
5043 RequestPermissionRequest(RequestPermissionRequest),
5054 CreateTerminalRequest(CreateTerminalRequest),
5069 TerminalOutputRequest(TerminalOutputRequest),
5076 ReleaseTerminalRequest(ReleaseTerminalRequest),
5089 WaitForTerminalExitRequest(WaitForTerminalExitRequest),
5093 KillTerminalRequest(KillTerminalRequest),
5106 CreateElicitationRequest(CreateElicitationRequest),
5110 #[cfg(feature = "unstable_mcp_over_acp")]
5116 MessageMcpRequest(MessageMcpRequest),
5117 ExtMethodRequest(ExtRequest),
5125}
5126
5127impl_request_dispatch! {
5128 AgentRequest => ClientResponse {
5129 WriteTextFileRequest => WriteTextFileResponse: CLIENT_METHOD_NAMES.fs_write_text_file,
5130 ReadTextFileRequest => ReadTextFileResponse: CLIENT_METHOD_NAMES.fs_read_text_file,
5131 RequestPermissionRequest => RequestPermissionResponse: CLIENT_METHOD_NAMES.session_request_permission,
5132 CreateTerminalRequest => CreateTerminalResponse: CLIENT_METHOD_NAMES.terminal_create,
5133 TerminalOutputRequest => TerminalOutputResponse: CLIENT_METHOD_NAMES.terminal_output,
5134 ReleaseTerminalRequest => ReleaseTerminalResponse: CLIENT_METHOD_NAMES.terminal_release,
5135 WaitForTerminalExitRequest => WaitForTerminalExitResponse: CLIENT_METHOD_NAMES.terminal_wait_for_exit,
5136 KillTerminalRequest => KillTerminalResponse: CLIENT_METHOD_NAMES.terminal_kill,
5137 CreateElicitationRequest => CreateElicitationResponse: CLIENT_METHOD_NAMES.elicitation_create,
5138 #[cfg(feature = "unstable_mcp_over_acp")]
5139 MessageMcpRequest => MessageMcpResponse: CLIENT_METHOD_NAMES.mcp_message,
5140 }
5141 extension ExtMethodRequest(ExtRequest) => ExtMethodResponse;
5142}
5143
5144#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5151#[derive(Clone, Debug, Serialize, Deserialize)]
5152#[serde(untagged)]
5153#[cfg_attr(feature = "schemars", schemars(inline))]
5154#[non_exhaustive]
5155pub enum ClientResponse {
5156 WriteTextFileResponse(#[serde(default)] WriteTextFileResponse),
5158 ReadTextFileResponse(ReadTextFileResponse),
5160 RequestPermissionResponse(RequestPermissionResponse),
5162 CreateTerminalResponse(CreateTerminalResponse),
5164 TerminalOutputResponse(TerminalOutputResponse),
5166 ReleaseTerminalResponse(#[serde(default)] ReleaseTerminalResponse),
5168 WaitForTerminalExitResponse(WaitForTerminalExitResponse),
5170 KillTerminalResponse(#[serde(default)] KillTerminalResponse),
5172 CreateElicitationResponse(CreateElicitationResponse),
5174 #[cfg(feature = "unstable_mcp_over_acp")]
5176 MessageMcpResponse(MessageMcpResponse),
5177 ExtMethodResponse(ExtResponse),
5179}
5180
5181#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5188#[derive(Clone, Debug, Serialize, Deserialize)]
5189#[serde(untagged)]
5190#[expect(clippy::large_enum_variant)]
5191#[cfg_attr(feature = "schemars", schemars(inline))]
5192#[non_exhaustive]
5193pub enum AgentNotification {
5194 SessionNotification(SessionNotification),
5206 CompleteElicitationNotification(CompleteElicitationNotification),
5210 #[cfg(feature = "unstable_auth_status")]
5218 AuthStatusUpdateNotification(AuthStatusUpdateNotification),
5219 ExtNotification(ExtNotification),
5227}
5228
5229impl_message_dispatch! {
5230 AgentNotification {
5231 SessionNotification => CLIENT_METHOD_NAMES.session_update,
5232 CompleteElicitationNotification => CLIENT_METHOD_NAMES.elicitation_complete,
5233 #[cfg(feature = "unstable_auth_status")]
5234 AuthStatusUpdateNotification => CLIENT_METHOD_NAMES.auth_status_update,
5235 }
5236 extension ExtNotification(ExtNotification);
5237}
5238
5239#[cfg(test)]
5240mod tests {
5241 use super::*;
5242
5243 #[test]
5244 fn notice_preserves_wire_shape_nullable_fields_and_open_severity() {
5245 use serde_json::json;
5246
5247 let mut meta = Meta::new();
5248 meta.insert("source".into(), json!("fallback"));
5249 assert_eq!(
5250 serde_json::to_value(SessionUpdate::Notice(
5251 Notice::new(NoticeSeverity::Warning, "MCP server unavailable")
5252 .description("Continuing without it.")
5253 .meta(meta),
5254 ))
5255 .unwrap(),
5256 json!({
5257 "sessionUpdate": "notice",
5258 "severity": "warning",
5259 "title": "MCP server unavailable",
5260 "description": "Continuing without it.",
5261 "_meta": { "source": "fallback" }
5262 })
5263 );
5264
5265 assert_eq!(
5266 serde_json::to_value(SessionUpdate::Notice(Notice::new(
5267 NoticeSeverity::Info,
5268 "Indexing workspace",
5269 )))
5270 .unwrap(),
5271 json!({
5272 "sessionUpdate": "notice",
5273 "severity": "info",
5274 "title": "Indexing workspace"
5275 })
5276 );
5277
5278 let SessionUpdate::Notice(notice) = serde_json::from_value(json!({
5279 "sessionUpdate": "notice",
5280 "severity": "critical",
5281 "title": "Provider degraded",
5282 "description": null,
5283 "_meta": null
5284 }))
5285 .unwrap() else {
5286 panic!("expected notice");
5287 };
5288
5289 assert_eq!(
5290 notice.severity,
5291 NoticeSeverity::Other("critical".to_string())
5292 );
5293 assert_eq!(notice.description, None);
5294 assert_eq!(notice.meta, None);
5295 assert_eq!(
5296 serde_json::to_value(SessionUpdate::Notice(notice)).unwrap(),
5297 json!({
5298 "sessionUpdate": "notice",
5299 "severity": "critical",
5300 "title": "Provider degraded"
5301 })
5302 );
5303 }
5304
5305 #[test]
5306 fn notice_requires_string_severity_and_title() {
5307 use serde_json::json;
5308
5309 for malformed in [
5310 json!({
5311 "sessionUpdate": "notice",
5312 "severity": "warning",
5313 "title": 42
5314 }),
5315 json!({
5316 "sessionUpdate": "notice",
5317 "severity": 42,
5318 "title": "MCP server unavailable"
5319 }),
5320 json!({
5321 "sessionUpdate": "notice",
5322 "severity": "warning"
5323 }),
5324 json!({
5325 "sessionUpdate": "notice",
5326 "severity": "warning",
5327 "title": null
5328 }),
5329 json!({
5330 "sessionUpdate": "notice",
5331 "title": "MCP server unavailable"
5332 }),
5333 json!({
5334 "sessionUpdate": "notice",
5335 "severity": null,
5336 "title": "MCP server unavailable"
5337 }),
5338 ] {
5339 assert!(serde_json::from_str::<SessionUpdate>(&malformed.to_string()).is_err());
5340 assert!(serde_json::from_value::<SessionUpdate>(malformed).is_err());
5341 }
5342 }
5343
5344 #[test]
5345 fn notice_tolerates_invalid_optional_display_fields_and_custom_severity() {
5346 use serde_json::json;
5347
5348 let wire = json!({
5349 "sessionUpdate": "notice",
5350 "severity": "_custom",
5351 "title": "Provider degraded",
5352 "description": 42,
5353 "_meta": false
5354 });
5355 let SessionUpdate::Notice(notice) = serde_json::from_value(wire.clone()).unwrap() else {
5356 panic!("expected notice");
5357 };
5358 assert_eq!(
5360 serde_json::from_str::<SessionUpdate>(&wire.to_string()).unwrap(),
5361 SessionUpdate::Notice(notice.clone())
5362 );
5363 assert_eq!(notice.severity, NoticeSeverity::Other("_custom".into()));
5364 assert_eq!(notice.description, None);
5365 assert_eq!(notice.meta, None);
5366 assert_eq!(
5367 serde_json::to_value(notice).unwrap(),
5368 json!({"severity": "_custom", "title": "Provider degraded"})
5369 );
5370 }
5371
5372 #[cfg(feature = "schemars")]
5373 #[test]
5374 fn notice_schema_preserves_required_and_nullable_fields() {
5375 use serde_json::json;
5376
5377 let schema = serde_json::to_value(schemars::schema_for!(Notice)).unwrap();
5378 assert_eq!(schema["required"], json!(["severity", "title"]));
5379 assert_eq!(schema["properties"]["title"]["minLength"], 1);
5380 for field in ["description", "_meta"] {
5381 assert!(
5382 schema["properties"][field]["type"]
5383 .as_array()
5384 .unwrap()
5385 .contains(&json!("null"))
5386 );
5387 }
5388 let capabilities =
5389 serde_json::to_value(schemars::schema_for!(ClientSessionCapabilities)).unwrap();
5390 assert!(
5391 capabilities["properties"]["notices"]["anyOf"]
5392 .as_array()
5393 .unwrap()
5394 .contains(&json!({"type": "null"}))
5395 );
5396 assert!(
5397 !capabilities["required"]
5398 .as_array()
5399 .is_some_and(|required| required.contains(&json!("notices")))
5400 );
5401 }
5402
5403 #[test]
5404 fn notice_capability_advertises_support_only_when_present() {
5405 use serde_json::json;
5406
5407 let capabilities = ClientCapabilities::new()
5408 .session(ClientSessionCapabilities::new().notices(NoticeCapabilities::new()));
5409 let value = serde_json::to_value(&capabilities).unwrap();
5410 assert_eq!(value["session"], json!({ "notices": {} }));
5411 assert_eq!(
5412 serde_json::from_value::<ClientCapabilities>(value).unwrap(),
5413 capabilities
5414 );
5415
5416 for unsupported in [
5417 json!({}),
5418 json!({ "session": null }),
5419 json!({ "session": {} }),
5420 json!({ "session": { "notices": null } }),
5421 json!({ "session": { "notices": false } }),
5422 json!({ "session": { "notices": true } }),
5423 json!({ "session": { "notices": "supported" } }),
5424 ] {
5425 let capabilities: ClientCapabilities = serde_json::from_value(unsupported).unwrap();
5426 assert!(
5427 capabilities
5428 .session
5429 .and_then(|session| session.notices)
5430 .is_none()
5431 );
5432 }
5433
5434 assert_eq!(
5435 serde_json::to_value(
5436 ClientSessionCapabilities::new()
5437 .notices(NoticeCapabilities::new())
5438 .notices(None)
5439 )
5440 .unwrap(),
5441 json!({})
5442 );
5443 }
5444
5445 #[cfg(feature = "unstable_prompt_suggestions")]
5446 #[test]
5447 fn prompt_suggestions_update_round_trips_prompt_content_and_meta() {
5448 use crate::v1::{ResourceLink, TextContent};
5449 use serde_json::json;
5450
5451 let mut meta = Meta::new();
5452 meta.insert("rank".into(), json!(1));
5453 let update = SessionUpdate::PromptSuggestionsUpdate(PromptSuggestionsUpdate::new(vec![
5454 PromptSuggestion::new(vec![ContentBlock::Text(TextContent::new(
5455 "Run the test suite and fix what breaks",
5456 ))])
5457 .meta(meta),
5458 PromptSuggestion::new(vec![
5459 ContentBlock::Text(TextContent::new("Add tests for ")),
5460 ContentBlock::ResourceLink(ResourceLink::new(
5461 "parser.rs",
5462 "file:///home/user/project/src/parser.rs",
5463 )),
5464 ]),
5465 ]));
5466 let wire = json!({
5467 "sessionUpdate": "prompt_suggestions_update",
5468 "suggestions": [
5469 {
5470 "prompt": [
5471 { "type": "text", "text": "Run the test suite and fix what breaks" }
5472 ],
5473 "_meta": { "rank": 1 }
5474 },
5475 {
5476 "prompt": [
5477 { "type": "text", "text": "Add tests for " },
5478 {
5479 "type": "resource_link",
5480 "name": "parser.rs",
5481 "uri": "file:///home/user/project/src/parser.rs"
5482 }
5483 ]
5484 }
5485 ]
5486 });
5487 assert_eq!(serde_json::to_value(&update).unwrap(), wire);
5488 assert_eq!(
5489 serde_json::from_value::<SessionUpdate>(wire).unwrap(),
5490 update
5491 );
5492 }
5493
5494 #[cfg(feature = "unstable_prompt_suggestions")]
5495 #[test]
5496 fn prompt_suggestions_update_with_an_empty_list_withdraws_suggestions() {
5497 use serde_json::json;
5498
5499 let update = SessionUpdate::PromptSuggestionsUpdate(PromptSuggestionsUpdate::new(vec![]));
5500 let wire = json!({
5501 "sessionUpdate": "prompt_suggestions_update",
5502 "suggestions": []
5503 });
5504 assert_eq!(serde_json::to_value(&update).unwrap(), wire);
5505 assert_eq!(
5506 serde_json::from_value::<SessionUpdate>(wire).unwrap(),
5507 update
5508 );
5509
5510 for malformed in [json!(null), json!("none"), json!({ "prompt": [] })] {
5512 assert!(
5513 serde_json::from_value::<SessionUpdate>(json!({
5514 "sessionUpdate": "prompt_suggestions_update",
5515 "suggestions": malformed
5516 }))
5517 .is_err()
5518 );
5519 }
5520 assert!(
5521 serde_json::from_value::<SessionUpdate>(json!({
5522 "sessionUpdate": "prompt_suggestions_update"
5523 }))
5524 .is_err()
5525 );
5526 }
5527
5528 #[cfg(feature = "unstable_prompt_suggestions")]
5529 #[test]
5530 fn prompt_suggestions_update_skips_whole_suggestions_it_cannot_parse() {
5531 use crate::v1::TextContent;
5532 use serde_json::json;
5533
5534 let text =
5535 |text: &str| PromptSuggestion::new(vec![ContentBlock::Text(TextContent::new(text))]);
5536
5537 let update: SessionUpdate = serde_json::from_value(json!({
5540 "sessionUpdate": "prompt_suggestions_update",
5541 "suggestions": [
5542 { "prompt": [{ "type": "text", "text": "Keep the first" }] },
5543 { "text": "A suggestion without a prompt" },
5544 { "prompt": "Not a list" },
5545 { "prompt": [{ "type": "text", "text": "Open " }, { "type": "text" }] },
5546 { "prompt": [{ "type": "hologram", "data": "AAAA" }] },
5547 "not an object",
5548 { "prompt": [{ "type": "text", "text": "Keep the last" }], "_meta": false }
5549 ]
5550 }))
5551 .unwrap();
5552
5553 assert_eq!(
5554 update,
5555 SessionUpdate::PromptSuggestionsUpdate(PromptSuggestionsUpdate::new(vec![
5556 text("Keep the first"),
5557 text("Keep the last"),
5558 ]))
5559 );
5560 }
5561
5562 #[cfg(feature = "unstable_prompt_suggestions")]
5563 #[test]
5564 fn prompt_suggestions_capability_advertises_support_and_content_types() {
5565 use serde_json::json;
5566
5567 let capabilities = ClientCapabilities::new().session(
5568 ClientSessionCapabilities::new()
5569 .prompt_suggestions(PromptSuggestionsCapabilities::new()),
5570 );
5571 let value = serde_json::to_value(&capabilities).unwrap();
5572 assert_eq!(value["session"], json!({ "promptSuggestions": {} }));
5573 assert_eq!(
5574 serde_json::from_value::<ClientCapabilities>(value).unwrap(),
5575 capabilities
5576 );
5577
5578 let content_types = PromptSuggestionsCapabilities::new()
5579 .image(PromptSuggestionsImageCapabilities::new())
5580 .audio(PromptSuggestionsAudioCapabilities::new())
5581 .embedded_context(PromptSuggestionsEmbeddedContextCapabilities::new());
5582 let wire = json!({ "image": {}, "audio": {}, "embeddedContext": {} });
5583 assert_eq!(serde_json::to_value(&content_types).unwrap(), wire);
5584 assert_eq!(
5585 serde_json::from_value::<PromptSuggestionsCapabilities>(wire).unwrap(),
5586 content_types
5587 );
5588
5589 for unsupported in [
5590 json!({}),
5591 json!({ "session": null }),
5592 json!({ "session": {} }),
5593 json!({ "session": { "promptSuggestions": null } }),
5594 json!({ "session": { "promptSuggestions": false } }),
5595 json!({ "session": { "promptSuggestions": true } }),
5596 json!({ "session": { "promptSuggestions": "supported" } }),
5597 ] {
5598 let capabilities: ClientCapabilities = serde_json::from_value(unsupported).unwrap();
5599 assert!(
5600 capabilities
5601 .session
5602 .and_then(|session| session.prompt_suggestions)
5603 .is_none()
5604 );
5605 }
5606
5607 assert_eq!(
5610 serde_json::from_value::<PromptSuggestionsCapabilities>(json!({
5611 "image": true,
5612 "audio": null,
5613 "embeddedContext": {}
5614 }))
5615 .unwrap(),
5616 PromptSuggestionsCapabilities::new()
5617 .embedded_context(PromptSuggestionsEmbeddedContextCapabilities::new())
5618 );
5619 }
5620
5621 #[cfg(all(feature = "schemars", feature = "unstable_prompt_suggestions"))]
5622 #[test]
5623 fn prompt_suggestions_schema_requires_the_list_and_a_non_empty_prompt() {
5624 use serde_json::json;
5625
5626 let update = serde_json::to_value(schemars::schema_for!(PromptSuggestionsUpdate)).unwrap();
5627 assert_eq!(update["required"], json!(["suggestions"]));
5628 assert_eq!(update["properties"]["suggestions"]["type"], "array");
5629
5630 let suggestion = serde_json::to_value(schemars::schema_for!(PromptSuggestion)).unwrap();
5631 assert_eq!(suggestion["required"], json!(["prompt"]));
5632 assert_eq!(suggestion["properties"]["prompt"]["type"], "array");
5633 assert_eq!(suggestion["properties"]["prompt"]["minItems"], 1);
5634
5635 let capabilities =
5636 serde_json::to_value(schemars::schema_for!(ClientSessionCapabilities)).unwrap();
5637 assert!(
5638 capabilities["properties"]["promptSuggestions"]["anyOf"]
5639 .as_array()
5640 .unwrap()
5641 .contains(&json!({"type": "null"}))
5642 );
5643 assert!(
5644 !capabilities["required"]
5645 .as_array()
5646 .is_some_and(|required| required.contains(&json!("promptSuggestions")))
5647 );
5648
5649 let content_types =
5650 serde_json::to_value(schemars::schema_for!(PromptSuggestionsCapabilities)).unwrap();
5651 assert!(content_types.get("required").is_none());
5652 for field in ["image", "audio", "embeddedContext"] {
5653 assert!(
5654 content_types["properties"][field]["anyOf"]
5655 .as_array()
5656 .unwrap()
5657 .contains(&json!({"type": "null"}))
5658 );
5659 }
5660 }
5661
5662 #[test]
5663 fn compaction_updates_preserve_patch_and_open_status_semantics() {
5664 use serde_json::json;
5665
5666 assert_eq!(
5667 serde_json::to_value(SessionUpdate::CompactionUpdate(CompactionUpdate::new(
5668 "cmp_001",
5669 CompactionStatus::InProgress,
5670 )))
5671 .unwrap(),
5672 json!({
5673 "sessionUpdate": "compaction_update",
5674 "compactionId": "cmp_001",
5675 "status": "in_progress"
5676 })
5677 );
5678
5679 let SessionUpdate::CompactionUpdate(update) = serde_json::from_value(json!({
5680 "sessionUpdate": "compaction_update",
5681 "compactionId": "cmp_001",
5682 "status": "paused",
5683 "summary": null,
5684 "error": null
5685 }))
5686 .unwrap() else {
5687 panic!("expected compaction update");
5688 };
5689 assert_eq!(update.status, CompactionStatus::Other("paused".into()));
5690 assert!(update.summary.is_null());
5691 assert!(update.error.is_null());
5692 assert!(update.meta.is_undefined());
5693 }
5694
5695 #[test]
5696 fn compaction_chunk_and_v1_capability_serialize() {
5697 use serde_json::json;
5698
5699 assert_eq!(
5700 serde_json::to_value(SessionUpdate::CompactionSummaryChunk(
5701 CompactionSummaryChunk::new(
5702 "cmp_001",
5703 ContentBlock::Text(crate::v1::TextContent::new("retained")),
5704 ),
5705 ))
5706 .unwrap(),
5707 json!({
5708 "sessionUpdate": "compaction_summary_chunk",
5709 "compactionId": "cmp_001",
5710 "content": { "type": "text", "text": "retained" }
5711 })
5712 );
5713 assert_eq!(
5714 serde_json::to_value(
5715 ClientSessionCapabilities::new().compaction(CompactionCapabilities::new())
5716 )
5717 .unwrap(),
5718 json!({ "compaction": {} })
5719 );
5720 let absent: ClientSessionCapabilities = serde_json::from_value(json!({})).unwrap();
5721 let null: ClientSessionCapabilities =
5722 serde_json::from_value(json!({ "compaction": null })).unwrap();
5723 assert!(absent.compaction.is_none());
5724 assert!(null.compaction.is_none());
5725 }
5726
5727 #[cfg(feature = "unstable_subagents")]
5728 #[test]
5729 fn test_subagent_updates_serialization() {
5730 use serde_json::json;
5731
5732 let announced = SessionUpdate::SubagentUpdate(SubagentUpdate::new("sess_child_1"));
5733 assert_eq!(
5734 serde_json::to_value(&announced).unwrap(),
5735 json!({
5736 "sessionUpdate": "subagent_update",
5737 "sessionId": "sess_child_1"
5738 })
5739 );
5740 assert_eq!(
5741 serde_json::from_value::<SessionUpdate>(serde_json::to_value(&announced).unwrap())
5742 .unwrap(),
5743 announced
5744 );
5745 let capable = SubagentUpdate::new("sess_child_1").capabilities(
5746 SubagentSessionCapabilities::new().cancel(SessionCancelCapabilities::new()),
5747 );
5748 assert_eq!(
5749 serde_json::to_value(capable).unwrap(),
5750 json!({
5751 "sessionId": "sess_child_1",
5752 "capabilities": {"cancel": {}}
5753 })
5754 );
5755 let minimal: SubagentUpdate =
5756 serde_json::from_value(json!({ "sessionId": "sess_child_3" })).unwrap();
5757 assert!(minimal.capabilities.is_undefined());
5758 assert!(minimal.state.is_undefined());
5759
5760 let nulls: SubagentUpdate = serde_json::from_value(json!({
5761 "sessionId": "sess_child_3",
5762 "capabilities": null,
5763 "state": null
5764 }))
5765 .unwrap();
5766 assert!(nulls.capabilities.is_null());
5767 assert!(nulls.state.is_null());
5768 assert_eq!(
5769 serde_json::to_value(nulls).unwrap(),
5770 json!({"sessionId": "sess_child_3", "capabilities": null, "state": null})
5771 );
5772 }
5773
5774 #[cfg(feature = "unstable_subagents")]
5775 #[test]
5776 fn test_subagent_display_metadata() {
5777 use serde_json::json;
5778
5779 let update = SubagentUpdate::new("child")
5780 .title("Test investigator".to_string())
5781 .description("Investigates platform-specific test failures.".to_string());
5782 let wire = json!({
5783 "sessionId": "child",
5784 "title": "Test investigator",
5785 "description": "Investigates platform-specific test failures."
5786 });
5787 assert_eq!(serde_json::to_value(&update).unwrap(), wire);
5788 assert_eq!(
5789 serde_json::from_value::<SubagentUpdate>(wire).unwrap(),
5790 update
5791 );
5792
5793 let minimal = SubagentUpdate::new("child");
5794 assert_eq!(
5795 serde_json::to_value(&minimal).unwrap(),
5796 json!({"sessionId": "child"})
5797 );
5798 let cleared: SubagentUpdate = serde_json::from_value(json!({
5799 "sessionId": "child", "title": null, "description": null
5800 }))
5801 .unwrap();
5802 assert!(cleared.title.is_null());
5803 assert!(cleared.description.is_null());
5804 assert_eq!(
5805 serde_json::to_value(cleared).unwrap(),
5806 json!({"sessionId": "child", "title": null, "description": null})
5807 );
5808 let invalid: SubagentUpdate = serde_json::from_value(json!({
5809 "sessionId": "child", "title": false, "description": false
5810 }))
5811 .unwrap();
5812 assert_eq!(invalid, minimal);
5813
5814 let title_only: SubagentUpdate = serde_json::from_value(json!({
5815 "sessionId": "child", "title": "Updated title"
5816 }))
5817 .unwrap();
5818 assert_eq!(
5819 title_only.title.value().map(String::as_str),
5820 Some("Updated title")
5821 );
5822 assert!(title_only.description.is_undefined());
5823 }
5824
5825 #[cfg(feature = "unstable_subagents")]
5826 #[test]
5827 fn subagent_directories_use_strict_patch_semantics() {
5828 use serde_json::json;
5829
5830 let update = SubagentUpdate::new("child")
5831 .cwd("/home/user/project/.worktrees/investigator")
5832 .additional_directories(vec![]);
5833 let wire = json!({
5834 "sessionId": "child",
5835 "cwd": "/home/user/project/.worktrees/investigator",
5836 "additionalDirectories": []
5837 });
5838 assert_eq!(serde_json::to_value(&update).unwrap(), wire);
5839 assert_eq!(
5840 serde_json::from_value::<SubagentUpdate>(wire).unwrap(),
5841 update
5842 );
5843
5844 let inherited: SubagentUpdate =
5845 serde_json::from_value(json!({"sessionId": "child"})).unwrap();
5846 assert!(inherited.cwd.is_undefined());
5847 assert!(inherited.additional_directories.is_undefined());
5848
5849 let cleared_wire = json!({
5850 "sessionId": "child", "cwd": null, "additionalDirectories": null
5851 });
5852 let cleared: SubagentUpdate = serde_json::from_value(cleared_wire.clone()).unwrap();
5853 assert!(cleared.cwd.is_null());
5854 assert!(cleared.additional_directories.is_null());
5855 assert_eq!(serde_json::to_value(cleared).unwrap(), cleared_wire);
5856
5857 for malformed in [
5858 json!({"sessionId": "child", "cwd": false}),
5859 json!({"sessionId": "child", "additionalDirectories": "/tmp/wt"}),
5860 json!({"sessionId": "child", "additionalDirectories": ["/tmp/wt", false]}),
5861 ] {
5862 assert!(
5863 serde_json::from_value::<SubagentUpdate>(malformed.clone()).is_err(),
5864 "{malformed}"
5865 );
5866 }
5867 }
5868
5869 #[cfg(feature = "unstable_subagents")]
5870 #[test]
5871 fn subagent_patch_fields_preserve_omitted_null_and_concrete() {
5872 use serde_json::json;
5873
5874 let omitted = SubagentUpdate::new("child");
5875 for field in ["title", "description", "capabilities", "state", "_meta"] {
5876 let wire = json!({"sessionId": "child", field: null});
5877 let decoded: SubagentUpdate = serde_json::from_value(wire.clone()).unwrap();
5878 assert_eq!(serde_json::to_value(decoded).unwrap(), wire, "{field}");
5879 let malformed = json!({"sessionId": "child", field: false});
5880 let decoded: SubagentUpdate = serde_json::from_value(malformed).unwrap();
5881 assert_eq!(decoded, omitted, "{field}");
5882 }
5883 let concrete = json!({
5884 "sessionId": "child", "title": "Investigator",
5885 "description": "Tests", "capabilities": {"cancel": {}},
5886 "state": {"state": "running"}, "_meta": {"source": "parent"}
5887 });
5888 let decoded: SubagentUpdate = serde_json::from_value(concrete.clone()).unwrap();
5889 assert!(decoded.title.value().is_some());
5890 assert!(decoded.description.value().is_some());
5891 assert!(decoded.capabilities.value().is_some());
5892 assert!(decoded.state.value().is_some());
5893 assert!(decoded.meta.value().is_some());
5894 assert_eq!(serde_json::to_value(decoded).unwrap(), concrete);
5895 let cleared = SubagentUpdate::new("child")
5896 .title(None)
5897 .description(None)
5898 .capabilities(None)
5899 .state(None)
5900 .meta(None);
5901 assert_eq!(
5902 serde_json::to_value(cleared).unwrap(),
5903 json!({
5904 "sessionId": "child", "title": null, "description": null,
5905 "capabilities": null, "state": null, "_meta": null
5906 })
5907 );
5908 }
5909
5910 #[cfg(feature = "unstable_subagents")]
5911 #[test]
5912 fn test_subagent_notification_keeps_parent_and_child_ids_nested() {
5913 use serde_json::json;
5914
5915 let notification = SessionNotification::new(
5916 "parent",
5917 SessionUpdate::SubagentUpdate(SubagentUpdate::new("child")),
5918 );
5919 let wire = json!({
5920 "sessionId": "parent",
5921 "update": {
5922 "sessionUpdate": "subagent_update",
5923 "sessionId": "child"
5924 }
5925 });
5926 assert_eq!(serde_json::to_value(¬ification).unwrap(), wire);
5927 assert_eq!(
5928 serde_json::from_value::<SessionNotification>(wire).unwrap(),
5929 notification
5930 );
5931 for malformed in [
5933 json!({"sessionId": "parent", "update": {"sessionUpdate": "subagent_update"}}),
5934 json!({"update": {"sessionUpdate": "subagent_update", "sessionId": "child"}}),
5935 ] {
5936 assert!(serde_json::from_value::<SessionNotification>(malformed).is_err());
5937 }
5938 }
5939
5940 #[cfg(feature = "unstable_subagents")]
5941 #[test]
5942 fn test_subagent_states_round_trip() {
5943 use serde_json::json;
5944
5945 for (wire_state, expected) in [
5946 (
5947 json!({"state": "running"}),
5948 StateUpdate::Running(RunningStateUpdate::new()),
5949 ),
5950 (
5951 json!({"state": "idle", "stopReason": "end_turn"}),
5952 StateUpdate::Idle(IdleStateUpdate::new().stop_reason(IdleStopReason::EndTurn)),
5953 ),
5954 (
5955 json!({"state": "requires_action"}),
5956 StateUpdate::RequiresAction(RequiresActionStateUpdate::new()),
5957 ),
5958 (
5959 json!({"state": "unknown"}),
5960 StateUpdate::Unknown(UnknownStateUpdate::new()),
5961 ),
5962 (
5963 json!({"state": "_waiting", "detail": {"ticket": 7}}),
5964 StateUpdate::Other(OtherStateUpdate::new(
5965 "_waiting",
5966 [("detail".into(), json!({"ticket": 7}))].into(),
5967 )),
5968 ),
5969 (
5970 json!({"state": "paused", "retryAt": 42}),
5971 StateUpdate::Other(OtherStateUpdate::new(
5972 "paused",
5973 [("retryAt".into(), json!(42))].into(),
5974 )),
5975 ),
5976 ] {
5977 let wire = json!({
5978 "sessionUpdate": "subagent_update",
5979 "sessionId": "sess_child",
5980 "state": wire_state
5981 });
5982 let parsed: SessionUpdate = serde_json::from_value(wire.clone()).unwrap();
5983 let SessionUpdate::SubagentUpdate(update) = &parsed else {
5984 panic!("expected subagent update");
5985 };
5986 assert_eq!(update.state.value(), Some(&expected));
5987 assert_eq!(serde_json::to_value(parsed).unwrap(), wire);
5988 }
5989
5990 for reason in [
5991 "end_turn",
5992 "max_tokens",
5993 "max_turn_requests",
5994 "refusal",
5995 "cancelled",
5996 ] {
5997 let state: StateUpdate = serde_json::from_value(json!({
5998 "state": "idle", "stopReason": reason
5999 }))
6000 .unwrap();
6001 assert_eq!(serde_json::to_value(state).unwrap()["stopReason"], reason);
6002 }
6003
6004 for state in [
6007 StateUpdate::Running(RunningStateUpdate::new()),
6008 StateUpdate::RequiresAction(RequiresActionStateUpdate::new()),
6009 StateUpdate::Unknown(UnknownStateUpdate::new()),
6010 StateUpdate::Running(RunningStateUpdate::new()),
6011 StateUpdate::Idle(IdleStateUpdate::new().stop_reason(IdleStopReason::EndTurn)),
6012 StateUpdate::Unknown(UnknownStateUpdate::new()),
6013 StateUpdate::Running(RunningStateUpdate::new()),
6014 ] {
6015 let update = SubagentUpdate::new("sess_child").state(state.clone());
6016 let wire = serde_json::to_value(&update).unwrap();
6017 assert_eq!(wire["sessionId"], "sess_child");
6018 assert_eq!(
6019 serde_json::from_value::<SubagentUpdate>(wire)
6020 .unwrap()
6021 .state,
6022 MaybeUndefined::Value(state)
6023 );
6024 }
6025 assert_eq!(
6026 serde_json::to_value(
6027 SubagentUpdate::new("sess_child").state(StateUpdate::Idle(IdleStateUpdate::new()))
6028 )
6029 .unwrap()["state"],
6030 json!({"state": "idle"})
6031 );
6032 }
6033
6034 #[cfg(feature = "unstable_subagents")]
6035 #[test]
6036 fn subagent_idle_snapshot_reports_child_failure() {
6037 use serde_json::json;
6038
6039 let update = SubagentUpdate::new("sess_child").state(StateUpdate::Idle(
6040 IdleStateUpdate::new().stop_reason(IdleStopReason::from(
6041 ErrorStopReason::new().error(Error::auth_required()),
6042 )),
6043 ));
6044 let wire = json!({
6045 "sessionId": "sess_child",
6046 "state": {
6047 "state": "idle",
6048 "stopReason": "error",
6049 "error": { "code": -32000, "message": "Authentication required" }
6050 }
6051 });
6052 assert_eq!(serde_json::to_value(&update).unwrap(), wire);
6053 assert_eq!(
6054 serde_json::from_value::<SubagentUpdate>(wire).unwrap(),
6055 update
6056 );
6057
6058 let without_details = StateUpdate::Idle(
6060 IdleStateUpdate::new().stop_reason(IdleStopReason::from(ErrorStopReason::new())),
6061 );
6062 for error in [None, Some(json!(null)), Some(json!("failed"))] {
6063 let mut wire = json!({ "state": "idle", "stopReason": "error" });
6064 if let Some(error) = error {
6065 wire["error"] = error;
6066 }
6067 assert_eq!(
6068 serde_json::from_value::<StateUpdate>(wire).unwrap(),
6069 without_details
6070 );
6071 }
6072
6073 let parsed: StateUpdate = serde_json::from_value(json!({
6076 "state": "idle",
6077 "stopReason": "end_turn",
6078 "error": { "code": -32603, "message": "Internal error" }
6079 }))
6080 .unwrap();
6081 assert_eq!(
6082 parsed,
6083 StateUpdate::Idle(IdleStateUpdate::new().stop_reason(IdleStopReason::EndTurn))
6084 );
6085
6086 let meta: Meta = [("source".into(), json!("worker"))].into_iter().collect();
6089 for stop_reason in [None, Some(json!(null)), Some(json!(true))] {
6090 let mut wire = json!({ "state": "idle", "_meta": { "source": "worker" } });
6091 if let Some(stop_reason) = stop_reason {
6092 wire["stopReason"] = stop_reason;
6093 }
6094 assert_eq!(
6095 serde_json::from_value::<StateUpdate>(wire).unwrap(),
6096 StateUpdate::Idle(IdleStateUpdate::new().meta(meta.clone()))
6097 );
6098 }
6099
6100 for stop_reason in ["_paused", "not_a_reason"] {
6103 let wire = json!({
6104 "state": "idle",
6105 "stopReason": stop_reason,
6106 "resumeAfter": 30,
6107 "_meta": { "source": "worker" }
6108 });
6109 let parsed: StateUpdate = serde_json::from_value(wire.clone()).unwrap();
6110 assert_eq!(
6111 parsed,
6112 StateUpdate::Idle(
6113 IdleStateUpdate::new()
6114 .stop_reason(IdleStopReason::Other(OtherStopReason::new(
6115 stop_reason,
6116 [("resumeAfter".into(), json!(30))].into_iter().collect(),
6117 )))
6118 .meta(meta.clone())
6119 )
6120 );
6121 assert_eq!(serde_json::to_value(&parsed).unwrap(), wire);
6122 }
6123 }
6124
6125 #[cfg(feature = "unstable_subagents")]
6126 #[test]
6127 fn subagent_known_stop_reasons_are_never_read_as_other() {
6128 use serde_json::json;
6129
6130 let known = [
6131 IdleStopReason::EndTurn,
6132 IdleStopReason::MaxTokens,
6133 IdleStopReason::MaxTurnRequests,
6134 IdleStopReason::Refusal,
6135 IdleStopReason::Cancelled,
6136 IdleStopReason::Error(ErrorStopReason::new()),
6137 ];
6138 for stop_reason in &known {
6140 match stop_reason {
6141 IdleStopReason::EndTurn
6142 | IdleStopReason::MaxTokens
6143 | IdleStopReason::MaxTurnRequests
6144 | IdleStopReason::Refusal
6145 | IdleStopReason::Cancelled
6146 | IdleStopReason::Error(_)
6147 | IdleStopReason::Other(_) => {}
6148 }
6149 }
6150
6151 for stop_reason in known {
6152 let state = StateUpdate::Idle(IdleStateUpdate::new().stop_reason(stop_reason));
6153 let wire = serde_json::to_value(&state).unwrap();
6154 assert_eq!(
6155 serde_json::from_value::<StateUpdate>(wire.clone()).unwrap(),
6156 state
6157 );
6158 assert!(
6159 serde_json::from_value::<OtherStopReason>(
6160 json!({ "stopReason": wire["stopReason"] })
6161 )
6162 .is_err(),
6163 "{} must not be accepted as a custom stop reason",
6164 wire["stopReason"]
6165 );
6166 }
6167 }
6168
6169 #[cfg(feature = "unstable_subagents")]
6170 #[test]
6171 fn subagent_unknown_stop_reason_leaves_usage_on_the_snapshot() {
6172 use serde_json::json;
6173
6174 let usage = json!({ "totalTokens": 10, "inputTokens": 6, "outputTokens": 4 });
6175 let wire = json!({ "state": "idle", "stopReason": "_paused", "usage": usage });
6176 let StateUpdate::Idle(idle) = serde_json::from_value(wire).unwrap() else {
6177 panic!("expected idle state snapshot");
6178 };
6179 let Some(IdleStopReason::Other(other)) = &idle.stop_reason else {
6180 panic!("expected a custom stop reason");
6181 };
6182 assert!(other.fields.is_empty());
6183
6184 #[cfg(feature = "unstable_end_turn_token_usage")]
6185 {
6186 assert!(idle.usage.is_some());
6187 assert_eq!(serde_json::to_value(&idle).unwrap()["usage"], usage);
6188 }
6189 #[cfg(not(feature = "unstable_end_turn_token_usage"))]
6192 assert!(serde_json::to_value(&idle).unwrap().get("usage").is_none());
6193 }
6194
6195 #[cfg(feature = "unstable_subagents")]
6196 #[test]
6197 fn test_subagent_unknown_activity_metadata_and_capabilities() {
6198 use serde_json::json;
6199
6200 let update = SubagentUpdate::new("child").state(StateUpdate::Unknown(
6201 UnknownStateUpdate::new().meta(
6202 [("source".into(), json!("worker"))]
6203 .into_iter()
6204 .collect::<Meta>(),
6205 ),
6206 ));
6207 let wire = json!({
6208 "sessionId": "child",
6209 "state": {
6210 "state": "unknown",
6211 "_meta": { "source": "worker" }
6212 }
6213 });
6214 assert_eq!(serde_json::to_value(&update).unwrap(), wire);
6215 assert_eq!(
6216 serde_json::from_value::<SubagentUpdate>(wire).unwrap(),
6217 update
6218 );
6219 assert!(update.capabilities.is_undefined());
6221
6222 for meta in [json!(null), json!(false)] {
6223 let state: StateUpdate = serde_json::from_value(json!({
6224 "state": "unknown",
6225 "_meta": meta
6226 }))
6227 .unwrap();
6228 assert_eq!(state, StateUpdate::Unknown(UnknownStateUpdate::new()));
6229 assert_eq!(
6230 serde_json::to_value(state).unwrap(),
6231 json!({"state": "unknown"})
6232 );
6233 }
6234 assert!(serde_json::from_value::<OtherStateUpdate>(json!({"state": "unknown"})).is_err());
6236 }
6237
6238 #[cfg(feature = "unstable_subagents")]
6239 #[test]
6240 fn test_subagent_malformed_optional_state() {
6241 use serde_json::json;
6242
6243 for malformed in [json!("running"), json!({}), json!({"state": 4})] {
6244 assert!(serde_json::from_value::<StateUpdate>(malformed.clone()).is_err());
6245 let update: SubagentUpdate = serde_json::from_value(json!({
6246 "sessionId": "child", "state": malformed
6247 }))
6248 .unwrap();
6249 assert!(update.state.is_undefined());
6250 }
6251 let bad_reason: StateUpdate =
6252 serde_json::from_value(json!({"state": "idle", "stopReason": false})).unwrap();
6253 assert_eq!(bad_reason, StateUpdate::Idle(IdleStateUpdate::new()));
6254 let null_reason: StateUpdate =
6255 serde_json::from_value(json!({"state": "idle", "stopReason": null})).unwrap();
6256 assert_eq!(null_reason, StateUpdate::Idle(IdleStateUpdate::new()));
6257 }
6258
6259 #[cfg(all(feature = "unstable_subagents", feature = "unstable_protocol_v2"))]
6260 #[test]
6261 fn test_subagent_state_v2_wire_parity() {
6262 use serde_json::json;
6263
6264 for wire in [
6265 json!({"state": "running"}),
6266 json!({"state": "idle", "stopReason": "cancelled"}),
6267 json!({"state": "requires_action"}),
6268 json!({"state": "unknown"}),
6269 json!({"state": "unknown", "_meta": {"source": "worker"}}),
6270 json!({"state": "_waiting", "detail": {"ticket": 7}}),
6271 ] {
6272 let v1: StateUpdate = serde_json::from_value(wire.clone()).unwrap();
6273 let v2: crate::v2::StateUpdate = serde_json::from_value(wire.clone()).unwrap();
6274 assert_eq!(serde_json::to_value(v1).unwrap(), wire);
6275 assert_eq!(serde_json::to_value(v2).unwrap(), wire);
6276 }
6277 }
6278
6279 #[cfg(feature = "unstable_subagents")]
6280 #[test]
6281 fn test_subagent_capability_semantics() {
6282 use serde_json::json;
6283
6284 let capabilities =
6285 serde_json::to_value(ClientCapabilities::new().subagents(SubagentCapabilities::new()))
6286 .unwrap();
6287 assert_eq!(capabilities["subagents"], json!({}));
6288
6289 let omitted: ClientCapabilities = serde_json::from_value(json!({})).unwrap();
6290 assert!(omitted.subagents.is_none());
6291
6292 let null: ClientCapabilities =
6293 serde_json::from_value(json!({ "subagents": null })).unwrap();
6294 assert!(null.subagents.is_none());
6295 assert_eq!(null, omitted);
6296 let serialized = serde_json::to_value(null).unwrap();
6297 assert_eq!(serialized, serde_json::to_value(omitted).unwrap());
6298 assert!(serialized.get("subagents").is_none());
6299
6300 for wire in [
6301 json!({}),
6302 json!({"cancel": null}),
6303 json!({"cancel": true}),
6304 json!({"cancel": false}),
6305 ] {
6306 let child: SubagentSessionCapabilities = serde_json::from_value(wire).unwrap();
6307 assert!(child.cancel.is_none());
6308 assert_eq!(serde_json::to_value(child).unwrap(), json!({}));
6309 }
6310 let enabled = SubagentSessionCapabilities::new().cancel(SessionCancelCapabilities::new());
6311 assert_eq!(
6312 serde_json::to_value(&enabled).unwrap(),
6313 json!({"cancel": {}})
6314 );
6315 assert_eq!(
6316 serde_json::from_value::<SubagentSessionCapabilities>(json!({"cancel": {}})).unwrap(),
6317 enabled
6318 );
6319 let meta: Meta = [("source".into(), json!("worker"))].into_iter().collect();
6320 let with_meta =
6321 SubagentSessionCapabilities::new().cancel(SessionCancelCapabilities::new().meta(meta));
6322 let wire = json!({"cancel": {"_meta": {"source": "worker"}}});
6323 assert_eq!(serde_json::to_value(&with_meta).unwrap(), wire);
6324 assert_eq!(
6325 serde_json::from_value::<SubagentSessionCapabilities>(wire).unwrap(),
6326 with_meta
6327 );
6328 let removed = SubagentSessionCapabilities::new();
6330 assert_eq!(serde_json::to_value(&removed).unwrap(), json!({}));
6331 assert!(removed.cancel.is_none());
6332 assert!(enabled.cancel.is_some());
6333 assert!(enabled.cancel(None).cancel.is_none());
6334 let replacement = SubagentUpdate::new("child").capabilities(removed);
6335 assert_eq!(
6336 serde_json::to_value(replacement).unwrap(),
6337 json!({"sessionId": "child", "capabilities": {}})
6338 );
6339 }
6340
6341 #[cfg(all(feature = "unstable_subagents", feature = "schemars"))]
6342 #[test]
6343 fn test_subagent_capability_schema_is_optional_and_nullable() {
6344 use serde_json::json;
6345
6346 let schema = serde_json::to_value(schemars::schema_for!(ClientCapabilities)).unwrap();
6347 let variants = schema["properties"]["subagents"]["anyOf"]
6348 .as_array()
6349 .expect("subagents must allow the capability object or null");
6350 assert!(variants.contains(&json!({"type": "null"})));
6351 assert!(
6352 !schema["required"]
6353 .as_array()
6354 .is_some_and(|required| required.contains(&json!("subagents")))
6355 );
6356 let child =
6357 serde_json::to_value(schemars::schema_for!(SubagentSessionCapabilities)).unwrap();
6358 let variants = child["properties"]["cancel"]["anyOf"]
6359 .as_array()
6360 .expect("cancel must allow the capability object or null");
6361 assert!(variants.contains(&json!({"type": "null"})));
6362 assert!(
6363 variants
6364 .iter()
6365 .any(|variant| variant["type"] == "object" || variant.get("$ref").is_some())
6366 );
6367 assert!(!variants.iter().any(|variant| variant["type"] == "boolean"));
6368 let cancel =
6369 serde_json::to_value(schemars::schema_for!(SessionCancelCapabilities)).unwrap();
6370 assert_eq!(cancel["type"], "object");
6371 assert!(
6372 !child["required"]
6373 .as_array()
6374 .is_some_and(|required| required.contains(&json!("cancel")))
6375 );
6376 }
6377
6378 #[test]
6379 fn test_elicitation_capability_semantics() {
6380 use serde_json::json;
6381
6382 let unsupported: ClientCapabilities = serde_json::from_value(json!({})).unwrap();
6383 assert!(unsupported.elicitation.is_none());
6384
6385 let null: ClientCapabilities =
6386 serde_json::from_value(json!({ "elicitation": null })).unwrap();
6387 assert!(null.elicitation.is_none());
6388
6389 let malformed: ClientCapabilities =
6390 serde_json::from_value(json!({ "elicitation": false })).unwrap();
6391 assert!(malformed.elicitation.is_none());
6392
6393 let empty: ClientCapabilities =
6394 serde_json::from_value(json!({ "elicitation": {} })).unwrap();
6395 let empty = empty.elicitation.expect("present capability");
6396 assert!(!empty.supports_form());
6397 assert!(!empty.supports_url());
6398
6399 let form_only: ClientCapabilities = serde_json::from_value(json!({
6400 "elicitation": { "form": {} }
6401 }))
6402 .unwrap();
6403 let form_only = form_only.elicitation.expect("advertised capability");
6404 assert!(form_only.supports_form());
6405 assert!(!form_only.supports_url());
6406
6407 let url_only: ClientCapabilities = serde_json::from_value(json!({
6408 "elicitation": { "url": {} }
6409 }))
6410 .unwrap();
6411 let url_only = url_only.elicitation.expect("advertised capability");
6412 assert!(!url_only.supports_form());
6413 assert!(url_only.supports_url());
6414
6415 let both: ClientCapabilities = serde_json::from_value(json!({
6416 "elicitation": { "form": {}, "url": {} }
6417 }))
6418 .unwrap();
6419 let both = both.elicitation.expect("advertised capability");
6420 assert!(both.supports_form());
6421 assert!(both.supports_url());
6422 }
6423
6424 #[test]
6425 fn test_elicitation_method_routing_and_envelopes() {
6426 use serde_json::json;
6427
6428 assert_eq!(CLIENT_METHOD_NAMES.elicitation_create, "elicitation/create");
6429 assert_eq!(
6430 CLIENT_METHOD_NAMES.elicitation_complete,
6431 "elicitation/complete"
6432 );
6433
6434 let request = AgentRequest::CreateElicitationRequest(CreateElicitationRequest::new(
6435 crate::v1::ElicitationFormMode::new(
6436 crate::v1::ElicitationSessionScope::new("sess_1"),
6437 crate::v1::ElicitationSchema::new(),
6438 ),
6439 "Choose a value",
6440 ));
6441 assert_eq!(request.method(), "elicitation/create");
6442 let method = Arc::from(request.method());
6443 let request = crate::v1::JsonRpcMessage::wrap(crate::v1::Request {
6444 id: crate::v1::RequestId::Number(7),
6445 method,
6446 params: Some(request),
6447 });
6448 assert_eq!(
6449 serde_json::to_value(request).unwrap(),
6450 json!({
6451 "jsonrpc": "2.0",
6452 "id": 7,
6453 "method": "elicitation/create",
6454 "params": {
6455 "mode": "form",
6456 "sessionId": "sess_1",
6457 "message": "Choose a value",
6458 "requestedSchema": { "type": "object", "properties": {} }
6459 }
6460 })
6461 );
6462
6463 let notification = AgentNotification::CompleteElicitationNotification(
6464 CompleteElicitationNotification::new("elic_1"),
6465 );
6466 assert_eq!(notification.method(), "elicitation/complete");
6467 let method = Arc::from(notification.method());
6468 let notification = crate::v1::JsonRpcMessage::wrap(crate::v1::Notification {
6469 method,
6470 params: Some(notification),
6471 });
6472 assert_eq!(
6473 serde_json::to_value(notification).unwrap(),
6474 json!({
6475 "jsonrpc": "2.0",
6476 "method": "elicitation/complete",
6477 "params": { "elicitationId": "elic_1" }
6478 })
6479 );
6480 }
6481
6482 #[test]
6483 fn test_client_capabilities_default_on_malformed_values() {
6484 use serde_json::json;
6485
6486 let capabilities: ClientCapabilities = serde_json::from_value(json!({
6487 "fs": {
6488 "readTextFile": "yes",
6489 "writeTextFile": true
6490 },
6491 "terminal": {}
6492 }))
6493 .unwrap();
6494
6495 assert!(!capabilities.fs.read_text_file);
6496 assert!(capabilities.fs.write_text_file);
6497 assert!(!capabilities.terminal);
6498
6499 let capabilities: ClientCapabilities = serde_json::from_value(json!({
6500 "fs": false
6501 }))
6502 .unwrap();
6503 assert_eq!(capabilities.fs, FileSystemCapabilities::default());
6504
6505 {
6506 let capabilities: ClientCapabilities = serde_json::from_value(json!({
6507 "auth": false
6508 }))
6509 .unwrap();
6510 assert_eq!(capabilities.auth, AuthCapabilities::default());
6511
6512 let capabilities: AuthCapabilities = serde_json::from_value(json!({
6513 "terminal": {}
6514 }))
6515 .unwrap();
6516 assert!(!capabilities.terminal);
6517 }
6518 }
6519
6520 #[test]
6521 fn test_serialization_behavior() {
6522 use serde_json::json;
6523
6524 assert_eq!(
6525 serde_json::from_value::<SessionInfoUpdate>(json!({})).unwrap(),
6526 SessionInfoUpdate {
6527 title: MaybeUndefined::Undefined,
6528 updated_at: MaybeUndefined::Undefined,
6529 meta: None
6530 }
6531 );
6532 assert_eq!(
6533 serde_json::from_value::<SessionInfoUpdate>(json!({"title": null, "updatedAt": null}))
6534 .unwrap(),
6535 SessionInfoUpdate {
6536 title: MaybeUndefined::Null,
6537 updated_at: MaybeUndefined::Null,
6538 meta: None
6539 }
6540 );
6541 assert_eq!(
6542 serde_json::from_value::<SessionInfoUpdate>(
6543 json!({"title": "title", "updatedAt": "timestamp"})
6544 )
6545 .unwrap(),
6546 SessionInfoUpdate {
6547 title: MaybeUndefined::Value("title".to_string()),
6548 updated_at: MaybeUndefined::Value("timestamp".to_string()),
6549 meta: None
6550 }
6551 );
6552
6553 assert_eq!(
6554 serde_json::to_value(SessionInfoUpdate::new()).unwrap(),
6555 json!({})
6556 );
6557 assert_eq!(
6558 serde_json::to_value(SessionInfoUpdate::new().title("title")).unwrap(),
6559 json!({"title": "title"})
6560 );
6561 assert_eq!(
6562 serde_json::to_value(SessionInfoUpdate::new().title(None)).unwrap(),
6563 json!({"title": null})
6564 );
6565 assert_eq!(
6566 serde_json::to_value(
6567 SessionInfoUpdate::new()
6568 .title("title")
6569 .title(MaybeUndefined::Undefined)
6570 )
6571 .unwrap(),
6572 json!({})
6573 );
6574 }
6575
6576 #[test]
6577 fn test_content_chunk_message_id_serialization() {
6578 use serde_json::json;
6579
6580 assert_eq!(
6581 serde_json::to_value(SessionUpdate::AgentMessageChunk(ContentChunk::new(
6582 ContentBlock::Text(crate::v1::TextContent::new("Hello"))
6583 )))
6584 .unwrap(),
6585 json!({
6586 "sessionUpdate": "agent_message_chunk",
6587 "content": {
6588 "type": "text",
6589 "text": "Hello"
6590 }
6591 })
6592 );
6593
6594 assert_eq!(
6595 serde_json::to_value(SessionUpdate::AgentMessageChunk(
6596 ContentChunk::new(ContentBlock::Text(crate::v1::TextContent::new("Hello")))
6597 .message_id("msg_agent_c42b9")
6598 ))
6599 .unwrap(),
6600 json!({
6601 "sessionUpdate": "agent_message_chunk",
6602 "messageId": "msg_agent_c42b9",
6603 "content": {
6604 "type": "text",
6605 "text": "Hello"
6606 }
6607 })
6608 );
6609
6610 let SessionUpdate::AgentMessageChunk(chunk) = serde_json::from_value(json!({
6611 "sessionUpdate": "agent_message_chunk",
6612 "messageId": null,
6613 "content": {
6614 "type": "text",
6615 "text": "Hello"
6616 }
6617 }))
6618 .unwrap() else {
6619 panic!("expected agent message chunk");
6620 };
6621
6622 assert_eq!(chunk.message_id, None);
6623 }
6624
6625 #[test]
6626 fn test_usage_update_serialization() {
6627 use serde_json::json;
6628
6629 assert_eq!(
6630 serde_json::to_value(SessionUpdate::UsageUpdate(UsageUpdate::new(
6631 53_000, 200_000
6632 )))
6633 .unwrap(),
6634 json!({
6635 "sessionUpdate": "usage_update",
6636 "used": 53000,
6637 "size": 200_000
6638 })
6639 );
6640
6641 assert_eq!(
6642 serde_json::to_value(SessionUpdate::UsageUpdate(
6643 UsageUpdate::new(53_000, 200_000).cost(Cost::new(0.045, "USD"))
6644 ))
6645 .unwrap(),
6646 json!({
6647 "sessionUpdate": "usage_update",
6648 "used": 53000,
6649 "size": 200_000,
6650 "cost": {
6651 "amount": 0.045,
6652 "currency": "USD"
6653 }
6654 })
6655 );
6656
6657 let SessionUpdate::UsageUpdate(update) = serde_json::from_value(json!({
6658 "sessionUpdate": "usage_update",
6659 "used": 53000,
6660 "size": 200_000,
6661 "cost": null
6662 }))
6663 .unwrap() else {
6664 panic!("expected usage update");
6665 };
6666
6667 assert_eq!(update.cost, None);
6668 }
6669
6670 #[test]
6671 fn test_client_capabilities_boolean_config_options_serialization() {
6672 use serde_json::json;
6673
6674 let capabilities = ClientCapabilities::new().session(
6675 ClientSessionCapabilities::new().config_options(
6676 SessionConfigOptionsCapabilities::new()
6677 .boolean(BooleanConfigOptionCapabilities::new()),
6678 ),
6679 );
6680 let json = serde_json::to_value(&capabilities).unwrap();
6681
6682 assert_eq!(json["session"]["configOptions"]["boolean"], json!({}));
6683
6684 let omitted: ClientCapabilities = serde_json::from_value(json!({})).unwrap();
6685 assert!(omitted.session.is_none());
6686
6687 let null_session: ClientCapabilities = serde_json::from_value(json!({
6688 "session": null
6689 }))
6690 .unwrap();
6691 assert!(null_session.session.is_none());
6692
6693 let null_config_options: ClientCapabilities = serde_json::from_value(json!({
6694 "session": {
6695 "configOptions": null
6696 }
6697 }))
6698 .unwrap();
6699 assert!(
6700 null_config_options
6701 .session
6702 .and_then(|session| session.config_options)
6703 .is_none()
6704 );
6705
6706 let null_boolean: ClientCapabilities = serde_json::from_value(json!({
6707 "session": {
6708 "configOptions": {
6709 "boolean": null
6710 }
6711 }
6712 }))
6713 .unwrap();
6714 assert!(
6715 null_boolean
6716 .session
6717 .and_then(|session| session.config_options)
6718 .and_then(|config_options| config_options.boolean)
6719 .is_none()
6720 );
6721 }
6722
6723 #[cfg(feature = "unstable_plan_operations")]
6724 #[test]
6725 fn test_plan_operations_serialization() {
6726 use serde_json::json;
6727
6728 use crate::v1::{PlanEntry, PlanEntryPriority, PlanEntryStatus, PlanUpdateContent};
6729
6730 let plan_update = SessionUpdate::PlanUpdate(PlanUpdate::new(PlanUpdateContent::items(
6731 "plan-1",
6732 vec![PlanEntry::new(
6733 "Step 1",
6734 PlanEntryPriority::High,
6735 PlanEntryStatus::Pending,
6736 )],
6737 )));
6738
6739 assert_eq!(
6740 serde_json::to_value(plan_update).unwrap(),
6741 json!({
6742 "sessionUpdate": "plan_update",
6743 "plan": {
6744 "type": "items",
6745 "planId": "plan-1",
6746 "entries": [
6747 {
6748 "content": "Step 1",
6749 "priority": "high",
6750 "status": "pending"
6751 }
6752 ]
6753 }
6754 })
6755 );
6756
6757 assert_eq!(
6758 serde_json::to_value(SessionUpdate::PlanRemoved(PlanRemoved::new("plan-1"))).unwrap(),
6759 json!({
6760 "sessionUpdate": "plan_removed",
6761 "planId": "plan-1"
6762 })
6763 );
6764
6765 let capabilities = ClientCapabilities::new().plan(PlanCapabilities::new());
6766 let json = serde_json::to_value(&capabilities).unwrap();
6767 assert_eq!(json["plan"], json!({}));
6768
6769 assert_eq!(
6770 serde_json::from_value::<ClientCapabilities>(json!({ "plan": null }))
6771 .unwrap()
6772 .plan,
6773 None
6774 );
6775 }
6776
6777 #[cfg(feature = "unstable_mcp_over_acp")]
6778 #[test]
6779 fn test_agent_mcp_request_method_names() {
6780 use serde_json::json;
6781
6782 let params: serde_json::Map<String, serde_json::Value> =
6783 [("cursor".to_string(), json!("abc"))].into_iter().collect();
6784
6785 assert_eq!(CLIENT_METHOD_NAMES.mcp_message, "mcp/message");
6786 assert_eq!(
6787 AgentRequest::MessageMcpRequest(MessageMcpRequest::new(
6788 "server-1",
6789 "req-1",
6790 "tools/list"
6791 ))
6792 .method(),
6793 "mcp/message"
6794 );
6795 assert_eq!(
6796 serde_json::to_value(
6797 MessageMcpRequest::new("server-1", "req-1", "tools/list").params(params)
6798 )
6799 .unwrap(),
6800 json!({
6801 "serverId": "server-1",
6802 "requestId": "req-1",
6803 "method": "tools/list",
6804 "params": { "cursor": "abc" }
6805 })
6806 );
6807
6808 let request_with_null_params: MessageMcpRequest = serde_json::from_value(json!({
6809 "serverId": "server-1",
6810 "requestId": "req-1",
6811 "method": "tools/list",
6812 "params": null,
6813 "_meta": null
6814 }))
6815 .unwrap();
6816 assert_eq!(request_with_null_params.params, None);
6817 assert_eq!(request_with_null_params.meta, None);
6818 for key in ["serverId", "requestId", "method"] {
6819 let mut value =
6820 json!({"serverId":"server-1", "requestId":"req-1", "method":"tools/list"});
6821 value.as_object_mut().unwrap().remove(key);
6822 assert!(serde_json::from_value::<MessageMcpRequest>(value).is_err());
6823 }
6824 for key in ["serverId", "requestId", "method"] {
6825 let mut value =
6826 json!({"serverId":"server-1", "requestId":"req-1", "method":"tools/list"});
6827 value[key] = serde_json::Value::Null;
6828 assert!(serde_json::from_value::<MessageMcpRequest>(value).is_err());
6829 }
6830 }
6831
6832 #[test]
6833 fn request_permission_request_rejects_malformed_options() {
6834 use serde_json::json;
6835
6836 assert!(
6837 serde_json::from_value::<RequestPermissionRequest>(json!({
6838 "sessionId": "sess-1",
6839 "toolCall": {"toolCallId": "tc-1"},
6840 "options": "not-an-array"
6841 }))
6842 .is_err()
6843 );
6844 assert!(
6845 serde_json::from_value::<RequestPermissionRequest>(json!({
6846 "sessionId": "sess-1",
6847 "toolCall": {"toolCallId": "tc-1"},
6848 "options": [{"optionId": "allow"}]
6849 }))
6850 .is_err()
6851 );
6852 }
6853
6854 #[test]
6855 fn create_terminal_request_rejects_malformed_fields() {
6856 use serde_json::json;
6857
6858 let request = |field: &str, value: serde_json::Value| {
6859 let mut request = json!({"sessionId": "sess-1", "command": "npx"});
6860 request[field] = value;
6861 serde_json::from_value::<CreateTerminalRequest>(request)
6862 };
6863
6864 for (field, value) in [
6866 ("args", json!(["serve", "--port", 3000])),
6867 ("args", json!("serve --port 3000")),
6868 ("env", json!([{"name": "PORT", "value": 3000}])),
6869 ("env", json!({"PORT": "3000"})),
6870 ("cwd", json!({"path": "/repo"})),
6871 ("outputByteLimit", json!("1048576")),
6872 ] {
6873 assert!(request(field, value.clone()).is_err(), "{field}: {value}");
6874 }
6875
6876 for field in ["args", "env", "cwd", "outputByteLimit"] {
6877 assert_eq!(
6878 request(field, serde_json::Value::Null).unwrap(),
6879 CreateTerminalRequest::new("sess-1", "npx"),
6880 "{field}"
6881 );
6882 }
6883 }
6884
6885 #[test]
6886 fn read_text_file_request_rejects_malformed_range() {
6887 use serde_json::json;
6888
6889 let request = |field: &str, value: serde_json::Value| {
6890 let mut request = json!({"sessionId": "sess-1", "path": "/repo/src/main.rs"});
6891 request[field] = value;
6892 serde_json::from_value::<ReadTextFileRequest>(request)
6893 };
6894
6895 for field in ["line", "limit"] {
6897 assert!(request(field, json!("120")).is_err(), "{field}");
6898 assert!(request(field, json!(-1)).is_err(), "{field}");
6899 assert_eq!(
6900 request(field, serde_json::Value::Null).unwrap(),
6901 ReadTextFileRequest::new("sess-1", "/repo/src/main.rs"),
6902 "{field}"
6903 );
6904 }
6905 }
6906
6907 #[cfg(feature = "unstable_session_cursors")]
6908 #[test]
6909 fn cursor_updates_round_trip_and_patch_capabilities() {
6910 use serde_json::json;
6911
6912 let update = SessionUpdate::CursorUpdate(
6913 CursorUpdate::new("cur_1")
6914 .capabilities(CursorCapabilities::new())
6915 .anchor(CursorAnchor::UserMessage(CursorMessageAnchor::new(
6916 "msg_user_2",
6917 CursorAnchorPosition::Before,
6918 ))),
6919 );
6920 let wire = json!({
6921 "sessionUpdate": "cursor_update",
6922 "cursorId": "cur_1",
6923 "capabilities": {},
6924 "anchor": { "type": "user_message", "messageId": "msg_user_2", "position": "before" }
6925 });
6926 assert_eq!(serde_json::to_value(&update).unwrap(), wire);
6927 assert_eq!(
6928 serde_json::from_value::<SessionUpdate>(wire).unwrap(),
6929 update
6930 );
6931
6932 let SessionUpdate::CursorUpdate(omitted) = serde_json::from_value(json!({
6934 "sessionUpdate": "cursor_update",
6935 "cursorId": "cur_1"
6936 }))
6937 .unwrap() else {
6938 panic!("expected cursor update");
6939 };
6940 assert!(omitted.capabilities.is_undefined());
6941 assert_eq!(omitted.anchor, None);
6942 assert!(omitted.meta.is_undefined());
6943 assert_eq!(
6944 serde_json::to_value(SessionUpdate::CursorUpdate(CursorUpdate::new("cur_1"))).unwrap(),
6945 json!({ "sessionUpdate": "cursor_update", "cursorId": "cur_1" })
6946 );
6947
6948 let SessionUpdate::CursorUpdate(cleared) = serde_json::from_value(json!({
6950 "sessionUpdate": "cursor_update",
6951 "cursorId": "cur_1",
6952 "capabilities": null,
6953 "anchor": null
6954 }))
6955 .unwrap() else {
6956 panic!("expected cursor update");
6957 };
6958 assert!(cleared.capabilities.is_null());
6959 assert_eq!(cleared.anchor, None);
6960 assert_eq!(
6961 serde_json::to_value(SessionUpdate::CursorUpdate(
6962 CursorUpdate::new("cur_1").capabilities(None)
6963 ))
6964 .unwrap(),
6965 json!({ "sessionUpdate": "cursor_update", "cursorId": "cur_1", "capabilities": null })
6966 );
6967 }
6968
6969 #[cfg(feature = "unstable_session_cursors")]
6970 #[test]
6971 fn cursor_anchors_cover_each_entity_type_and_preserve_unknown_ones() {
6972 use serde_json::json;
6973
6974 for (anchor, wire) in [
6975 (
6976 CursorAnchor::AgentMessage(CursorMessageAnchor::new(
6977 "msg_agent_1",
6978 CursorAnchorPosition::After,
6979 )),
6980 json!({ "type": "agent_message", "messageId": "msg_agent_1", "position": "after" }),
6981 ),
6982 (
6983 CursorAnchor::AgentThought(CursorMessageAnchor::new(
6984 "msg_agent_1",
6985 CursorAnchorPosition::After,
6986 )),
6987 json!({ "type": "agent_thought", "messageId": "msg_agent_1", "position": "after" }),
6988 ),
6989 #[cfg(feature = "unstable_subagents")]
6990 (
6991 CursorAnchor::SessionMessage(CursorMessageAnchor::new(
6992 "msg_session_1",
6993 CursorAnchorPosition::Before,
6994 )),
6995 json!({ "type": "session_message", "messageId": "msg_session_1", "position": "before" }),
6996 ),
6997 (
6998 CursorAnchor::ToolCall(CursorToolCallAnchor::new(
6999 "call_1",
7000 CursorAnchorPosition::After,
7001 )),
7002 json!({ "type": "tool_call", "toolCallId": "call_1", "position": "after" }),
7003 ),
7004 (
7005 CursorAnchor::Compaction(CursorCompactionAnchor::new(
7006 "cmp_1",
7007 CursorAnchorPosition::Before,
7008 )),
7009 json!({ "type": "compaction", "compactionId": "cmp_1", "position": "before" }),
7010 ),
7011 ] {
7012 assert_eq!(serde_json::to_value(&anchor).unwrap(), wire);
7013 assert_eq!(
7014 serde_json::from_value::<CursorAnchor>(wire).unwrap(),
7015 anchor
7016 );
7017 }
7018
7019 let wire = json!({ "type": "_acme_marker", "markerId": "mk_1", "position": "after" });
7021 let other = serde_json::from_value::<CursorAnchor>(wire.clone()).unwrap();
7022 assert!(matches!(other, CursorAnchor::Other(_)));
7023 assert_eq!(serde_json::to_value(&other).unwrap(), wire);
7024
7025 let wire =
7027 json!({ "type": "user_message", "messageId": "msg_user_2", "position": "inside" });
7028 let future = serde_json::from_value::<CursorAnchor>(wire.clone()).unwrap();
7029 assert_eq!(
7030 future,
7031 CursorAnchor::UserMessage(CursorMessageAnchor::new(
7032 "msg_user_2",
7033 CursorAnchorPosition::Other("inside".into()),
7034 ))
7035 );
7036 assert_eq!(serde_json::to_value(&future).unwrap(), wire);
7037 }
7038
7039 #[cfg(feature = "unstable_session_cursors")]
7040 #[test]
7041 fn malformed_cursor_anchor_fails_the_update() {
7042 use serde_json::json;
7043
7044 for anchor in [
7046 json!({ "type": "user_message", "position": "before" }),
7047 json!({ "type": "tool_call", "toolCallId": 7, "position": "after" }),
7048 json!({ "type": "compaction", "compactionId": "cmp_1" }),
7049 json!({ "messageId": "msg_user_2", "position": "before" }),
7050 json!("before"),
7051 ] {
7052 assert!(
7053 serde_json::from_value::<SessionUpdate>(json!({
7054 "sessionUpdate": "cursor_update",
7055 "cursorId": "cur_1",
7056 "anchor": anchor
7057 }))
7058 .is_err(),
7059 "{anchor}"
7060 );
7061 }
7062 assert!(
7063 serde_json::from_value::<SessionUpdate>(json!({ "sessionUpdate": "cursor_update" }))
7064 .is_err()
7065 );
7066 }
7067
7068 #[cfg(feature = "unstable_session_cursors")]
7069 #[test]
7070 fn malformed_cursor_capabilities_are_not_advertised() {
7071 use serde_json::json;
7072
7073 let SessionUpdate::CursorUpdate(update) = serde_json::from_value(json!({
7075 "sessionUpdate": "cursor_update",
7076 "cursorId": "cur_1",
7077 "capabilities": "fork"
7078 }))
7079 .unwrap() else {
7080 panic!("expected cursor update");
7081 };
7082 assert!(update.capabilities.is_undefined());
7083
7084 assert_eq!(
7086 serde_json::from_value::<CursorCapabilities>(json!({ "futureMethod": {} })).unwrap(),
7087 CursorCapabilities::new()
7088 );
7089
7090 #[cfg(feature = "unstable_session_fork")]
7091 {
7092 assert_eq!(
7093 serde_json::to_value(CursorCapabilities::new().fork(CursorForkCapabilities::new()))
7094 .unwrap(),
7095 json!({ "fork": {} })
7096 );
7097 assert_eq!(
7098 serde_json::from_value::<CursorCapabilities>(json!({ "fork": {} }))
7099 .unwrap()
7100 .fork,
7101 Some(CursorForkCapabilities::new())
7102 );
7103 for fork in [json!(null), json!(true), json!("yes")] {
7104 assert_eq!(
7105 serde_json::from_value::<CursorCapabilities>(json!({ "fork": fork }))
7106 .unwrap()
7107 .fork,
7108 None
7109 );
7110 }
7111 }
7112 }
7113
7114 #[cfg(feature = "unstable_session_cursors")]
7115 #[test]
7116 fn client_session_cursors_capability_is_optional_and_lenient() {
7117 use serde_json::json;
7118
7119 assert_eq!(
7120 serde_json::to_value(
7121 ClientSessionCapabilities::new().cursors(SessionCursorsCapabilities::new())
7122 )
7123 .unwrap(),
7124 json!({ "cursors": {} })
7125 );
7126 assert_eq!(
7127 serde_json::from_value::<ClientSessionCapabilities>(json!({ "cursors": {} }))
7128 .unwrap()
7129 .cursors,
7130 Some(SessionCursorsCapabilities::new())
7131 );
7132 for wire in [
7133 json!({}),
7134 json!({ "cursors": null }),
7135 json!({ "cursors": "yes" }),
7136 ] {
7137 assert_eq!(
7138 serde_json::from_value::<ClientSessionCapabilities>(wire)
7139 .unwrap()
7140 .cursors,
7141 None
7142 );
7143 }
7144 }
7145}