1use std::{path::PathBuf, sync::Arc};
7
8use derive_more::{Display, From};
9#[cfg(all(feature = "schemars", feature = "unstable_subagents"))]
10use schemars::Schema;
11use serde::{Deserialize, Serialize};
12use serde_with::{DefaultOnError, DefaultOnNull, VecSkipError, serde_as, skip_serializing_none};
13#[cfg(feature = "unstable_subagents")]
14use std::collections::BTreeMap;
15
16#[cfg(feature = "unstable_auth_status")]
17use super::AuthStatusUpdateNotification;
18#[cfg(feature = "unstable_subagents")]
19use super::Error;
20#[cfg(all(
21 feature = "unstable_subagents",
22 feature = "unstable_end_turn_token_usage"
23))]
24use super::Usage;
25use super::{
26 CompleteElicitationNotification, CreateElicitationRequest, CreateElicitationResponse,
27 ElicitationCapabilities,
28};
29use crate::{IntoMaybeUndefined, IntoOption, MaybeUndefined};
30
31use super::{
32 ContentBlock, EnvVariable, ExtNotification, ExtRequest, ExtResponse, Meta, Plan,
33 SessionConfigOption, SessionId, SessionModeId, ToolCall, ToolCallUpdate,
34};
35#[cfg(feature = "unstable_plan_operations")]
36use super::{PlanCapabilities, PlanRemoved, PlanUpdate};
37
38#[cfg(feature = "unstable_mcp_over_acp")]
39use super::mcp::{MCP_MESSAGE_METHOD_NAME, MessageMcpRequest, MessageMcpResponse};
40
41#[serde_as]
49#[skip_serializing_none]
50#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
51#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
52#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = SESSION_UPDATE_NOTIFICATION)))]
53#[serde(rename_all = "camelCase")]
54#[non_exhaustive]
55pub struct SessionNotification {
56 pub session_id: SessionId,
58 pub update: SessionUpdate,
60 #[serde_as(deserialize_as = "DefaultOnError")]
66 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
67 #[serde(default)]
68 #[serde(rename = "_meta")]
69 pub meta: Option<Meta>,
70}
71
72impl SessionNotification {
73 #[must_use]
75 pub fn new(session_id: impl Into<SessionId>, update: SessionUpdate) -> Self {
76 Self {
77 session_id: session_id.into(),
78 update,
79 meta: None,
80 }
81 }
82
83 #[must_use]
89 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
90 self.meta = meta.into_option();
91 self
92 }
93}
94
95#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
101#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
102#[serde(tag = "sessionUpdate", rename_all = "snake_case")]
103#[cfg_attr(feature = "schemars", schemars(extend("discriminator" = {"propertyName": "sessionUpdate"})))]
104#[non_exhaustive]
105pub enum SessionUpdate {
106 UserMessageChunk(ContentChunk),
108 AgentMessageChunk(ContentChunk),
110 AgentThoughtChunk(ContentChunk),
112 ToolCall(ToolCall),
114 ToolCallUpdate(ToolCallUpdate),
116 Plan(Plan),
119 #[cfg(feature = "unstable_plan_operations")]
125 PlanUpdate(PlanUpdate),
126 #[cfg(feature = "unstable_plan_operations")]
132 PlanRemoved(PlanRemoved),
133 AvailableCommandsUpdate(AvailableCommandsUpdate),
135 CurrentModeUpdate(CurrentModeUpdate),
139 ConfigOptionUpdate(ConfigOptionUpdate),
141 SessionInfoUpdate(SessionInfoUpdate),
143 UsageUpdate(UsageUpdate),
145 Notice(Notice),
150 CompactionUpdate(CompactionUpdate),
155 CompactionSummaryChunk(CompactionSummaryChunk),
160 #[cfg(feature = "unstable_prompt_suggestions")]
169 PromptSuggestionsUpdate(PromptSuggestionsUpdate),
170 #[cfg(feature = "unstable_subagents")]
177 SubagentUpdate(SubagentUpdate),
178 #[cfg(feature = "unstable_subagents")]
185 SessionMessage(SessionMessage),
186 #[cfg(feature = "unstable_subagents")]
192 SessionMessageChunk(SessionMessageChunk),
193}
194
195#[cfg(feature = "unstable_subagents")]
204#[serde_as]
205#[skip_serializing_none]
206#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
207#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
208#[serde(rename_all = "camelCase")]
209#[non_exhaustive]
210pub struct SessionMessageChunk {
211 pub message_id: MessageId,
213 pub content: ContentBlock,
215 #[serde_as(deserialize_as = "DefaultOnError")]
219 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
220 #[serde(default, rename = "_meta")]
221 pub meta: Option<Meta>,
222}
223
224#[cfg(feature = "unstable_subagents")]
225impl SessionMessageChunk {
226 #[must_use]
228 pub fn new(message_id: impl Into<MessageId>, content: ContentBlock) -> Self {
229 Self {
230 message_id: message_id.into(),
231 content,
232 meta: None,
233 }
234 }
235
236 #[must_use]
238 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
239 self.meta = meta.into_option();
240 self
241 }
242}
243
244#[cfg(feature = "unstable_subagents")]
250#[serde_as]
251#[skip_serializing_none]
252#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
253#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
254#[serde(rename_all = "camelCase")]
255#[non_exhaustive]
256pub struct SessionMessage {
257 pub message_id: MessageId,
259 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
263 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
264 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
265 pub sender_session_id: MaybeUndefined<SessionId>,
266 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
270 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
271 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
272 pub recipient_session_id: MaybeUndefined<SessionId>,
273 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
279 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
280 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
281 pub sender_message_id: MaybeUndefined<MessageId>,
282 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
288 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
289 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
290 pub recipient_message_id: MaybeUndefined<MessageId>,
291 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<VecSkipError<_>>>")]
294 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
295 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
296 pub content: MaybeUndefined<Vec<ContentBlock>>,
297 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
301 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
302 #[serde(
303 default,
304 rename = "_meta",
305 skip_serializing_if = "MaybeUndefined::is_undefined"
306 )]
307 pub meta: MaybeUndefined<Meta>,
308}
309
310#[cfg(feature = "unstable_subagents")]
311impl SessionMessage {
312 #[must_use]
314 pub fn new(message_id: impl Into<MessageId>) -> Self {
315 Self {
316 message_id: message_id.into(),
317 sender_session_id: MaybeUndefined::Undefined,
318 recipient_session_id: MaybeUndefined::Undefined,
319 sender_message_id: MaybeUndefined::Undefined,
320 recipient_message_id: MaybeUndefined::Undefined,
321 content: MaybeUndefined::Undefined,
322 meta: MaybeUndefined::Undefined,
323 }
324 }
325
326 #[must_use]
328 pub fn sender_session_id(
329 mut self,
330 sender_session_id: impl IntoMaybeUndefined<SessionId>,
331 ) -> Self {
332 self.sender_session_id = sender_session_id.into_maybe_undefined();
333 self
334 }
335
336 #[must_use]
338 pub fn recipient_session_id(
339 mut self,
340 recipient_session_id: impl IntoMaybeUndefined<SessionId>,
341 ) -> Self {
342 self.recipient_session_id = recipient_session_id.into_maybe_undefined();
343 self
344 }
345
346 #[must_use]
348 pub fn sender_message_id(
349 mut self,
350 sender_message_id: impl IntoMaybeUndefined<MessageId>,
351 ) -> Self {
352 self.sender_message_id = sender_message_id.into_maybe_undefined();
353 self
354 }
355
356 #[must_use]
358 pub fn recipient_message_id(
359 mut self,
360 recipient_message_id: impl IntoMaybeUndefined<MessageId>,
361 ) -> Self {
362 self.recipient_message_id = recipient_message_id.into_maybe_undefined();
363 self
364 }
365
366 #[must_use]
368 pub fn content(mut self, content: impl IntoMaybeUndefined<Vec<ContentBlock>>) -> Self {
369 self.content = content.into_maybe_undefined();
370 self
371 }
372
373 #[must_use]
375 pub fn meta(mut self, meta: impl IntoMaybeUndefined<Meta>) -> Self {
376 self.meta = meta.into_maybe_undefined();
377 self
378 }
379}
380
381#[cfg(all(test, feature = "unstable_subagents"))]
382mod session_message_tests {
383 use super::*;
384 use serde_json::{Value, json};
385
386 #[test]
387 fn envelopes_preserve_participants_and_multimodal_content() {
388 let content = json!([
389 {"type": "text", "text": "Please inspect this"},
390 {"type": "image", "data": "aGVsbG8=", "mimeType": "image/png"}
391 ]);
392 for (transcript, sender, recipient, id) in [
393 ("parent", "parent", "child", "sent-1"),
394 ("child", "parent", "child", "received-9"),
395 ("child", "child", "parent", "sent-2"),
396 ] {
397 let wire = json!({"sessionId": transcript, "update": {
398 "sessionUpdate": "session_message", "messageId": id,
399 "senderSessionId": sender, "recipientSessionId": recipient, "content": content
400 }});
401 let decoded: SessionNotification = serde_json::from_value(wire.clone()).unwrap();
402 assert_eq!(serde_json::to_value(&decoded).unwrap(), wire);
403 assert!(matches!(decoded.update, SessionUpdate::SessionMessage(_)));
404 let message = SessionMessage::new(id)
405 .sender_session_id(SessionId::new(sender))
406 .recipient_session_id(SessionId::new(recipient))
407 .content(vec![]);
408 assert_eq!(serde_json::to_value(message).unwrap()["content"], json!([]));
409 }
410 }
411
412 #[test]
413 fn message_upserts_validate_ids_and_patch_fields() {
414 let base = json!({"sessionUpdate": "session_message", "messageId": "m1",
415 "senderSessionId": "parent", "recipientSessionId": "child", "content": []});
416 {
417 let key = "messageId";
418 let mut missing = base.clone();
419 missing.as_object_mut().unwrap().remove(key);
420 assert!(
421 serde_json::from_value::<SessionUpdate>(missing).is_err(),
422 "{key}"
423 );
424 let mut null = base.clone();
425 null[key] = Value::Null;
426 assert!(
427 serde_json::from_value::<SessionUpdate>(null).is_err(),
428 "{key}"
429 );
430 let mut non_string = base.clone();
431 non_string[key] = json!(42);
432 assert!(
433 serde_json::from_value::<SessionUpdate>(non_string).is_err(),
434 "{key}"
435 );
436 }
437 for content in [None, Some(json!({}))] {
438 let mut wire = base.clone();
439 wire.as_object_mut().unwrap().remove("content");
440 if let Some(content) = content {
441 wire["content"] = content;
442 }
443 let decoded: SessionUpdate = serde_json::from_value(wire).unwrap();
444 let encoded = serde_json::to_value(decoded).unwrap();
445 let mut unchanged = base.clone();
446 unchanged.as_object_mut().unwrap().remove("content");
447 assert_eq!(encoded, unchanged);
448 }
449 let clear = SessionMessage::new("m1")
450 .sender_session_id(SessionId::new("parent"))
451 .recipient_session_id(SessionId::new("child"))
452 .content(None)
453 .meta(None);
454 let mut clear_wire = base.clone();
455 clear_wire["content"] = Value::Null;
456 clear_wire["_meta"] = Value::Null;
457 assert_eq!(
458 serde_json::to_value(&clear).unwrap()["content"],
459 Value::Null
460 );
461 let clear_update: SessionUpdate = serde_json::from_value(clear_wire.clone()).unwrap();
462 assert_eq!(serde_json::to_value(clear_update).unwrap(), clear_wire);
463 assert!(clear.content.is_null());
464 assert!(clear.meta.is_null());
465 for meta in [None, Some(Value::Null), Some(json!({"tag": "value"}))] {
466 let mut wire = base.clone();
467 if let Some(meta) = meta {
468 wire["_meta"] = meta;
469 }
470 let decoded: SessionUpdate = serde_json::from_value(wire.clone()).unwrap();
471 let encoded = serde_json::to_value(decoded).unwrap();
472 assert_eq!(encoded, wire);
473 }
474 let metadata_only = json!({"sessionUpdate": "session_message",
475 "messageId": "m1", "senderSessionId": "parent",
476 "recipientSessionId": "child", "_meta": {"tag": "value"}});
477 let decoded: SessionUpdate = serde_json::from_value(metadata_only.clone()).unwrap();
478 assert_eq!(serde_json::to_value(decoded).unwrap(), metadata_only);
479 let unset = SessionMessage::new("m1");
480 assert_eq!(
481 serde_json::to_value(&unset).unwrap(),
482 json!({"messageId": "m1"})
483 );
484 assert!(unset.content.is_undefined());
485 assert!(unset.meta.is_undefined());
486 let reset = SessionMessage::new("m1").content(vec![]);
487 assert_eq!(serde_json::to_value(reset).unwrap()["content"], json!([]));
488 let malformed: SessionMessage = serde_json::from_value(json!({
489 "messageId": "m1", "senderSessionId": "parent", "recipientSessionId": "child",
490 "content": false, "_meta": false
491 }))
492 .unwrap();
493 assert!(malformed.content.is_undefined());
494 assert!(malformed.meta.is_undefined());
495 }
496
497 #[test]
498 fn first_chunk_and_upsert_share_transcript_local_identity() {
499 for (transcript, id) in [("parent", "sent-1"), ("child", "received-9")] {
500 let wire = json!({"sessionId": transcript, "update": {
501 "sessionUpdate": "session_message_chunk", "messageId": id,
502 "content": {"type": "text", "text": "first"}
503 }});
504 let decoded: SessionNotification = serde_json::from_value(wire.clone()).unwrap();
505 assert_eq!(serde_json::to_value(decoded).unwrap(), wire);
506 let upsert = SessionMessage::new(id)
507 .sender_session_id(SessionId::new("parent"))
508 .recipient_session_id(SessionId::new("child"));
509 let chunk = SessionMessageChunk::new(
510 id,
511 ContentBlock::Text(crate::v1::TextContent::new("first")),
512 );
513 assert_eq!(chunk.message_id, upsert.message_id);
514 assert_eq!(
515 serde_json::to_value(SessionUpdate::SessionMessageChunk(chunk)).unwrap(),
516 wire["update"]
517 );
518 }
519 let wire = json!({"sessionId": "child", "update": {
520 "sessionUpdate": "session_message_chunk", "messageId": "received-9",
521 "content": {"type": "text", "text": "first"}
522 }});
523 let base = wire["update"].clone();
524 for key in ["messageId", "content"] {
525 let mut missing = base.clone();
526 missing.as_object_mut().unwrap().remove(key);
527 assert!(
528 serde_json::from_value::<SessionUpdate>(missing).is_err(),
529 "{key}"
530 );
531 let mut null = base.clone();
532 null[key] = Value::Null;
533 assert!(
534 serde_json::from_value::<SessionUpdate>(null).is_err(),
535 "{key}"
536 );
537 let mut non_string = base.clone();
538 non_string[key] = json!(42);
539 assert!(
540 serde_json::from_value::<SessionUpdate>(non_string).is_err(),
541 "{key}"
542 );
543 }
544 for meta in [None, Some(Value::Null), Some(json!({"chunk": true}))] {
545 let mut value = base.clone();
546 if let Some(meta) = meta {
547 value["_meta"] = meta;
548 }
549 let decoded: SessionUpdate = serde_json::from_value(value.clone()).unwrap();
550 let encoded = serde_json::to_value(decoded).unwrap();
551 if value["_meta"].is_null() {
552 assert_eq!(encoded, base);
553 } else {
554 assert_eq!(encoded, value);
555 }
556 }
557 let with_identity = json!({"sessionUpdate": "session_message_chunk", "messageId": "m1",
559 "senderSessionId": "parent", "recipientSessionId": "child",
560 "senderMessageId": "sent-1", "recipientMessageId": "received-1",
561 "content": {"type": "text", "text": "hello"}});
562 let decoded: SessionUpdate = serde_json::from_value(with_identity).unwrap();
563 assert_eq!(
564 serde_json::to_value(decoded).unwrap(),
565 json!({"sessionUpdate": "session_message_chunk", "messageId": "m1",
566 "content": {"type": "text", "text": "hello"}})
567 );
568 }
569
570 #[cfg(feature = "schemars")]
571 #[test]
572 fn schema_requires_ids_and_chunk_content() {
573 let schema = serde_json::to_value(schemars::schema_for!(SessionMessage)).unwrap();
574 let required = schema["required"].as_array().unwrap();
575 assert_eq!(required, &vec![json!("messageId")]);
576 let chunk = serde_json::to_value(schemars::schema_for!(SessionMessageChunk)).unwrap();
577 let required = chunk["required"].as_array().unwrap();
578 assert_eq!(required.len(), 2);
579 assert!(required.contains(&json!("messageId")));
580 assert!(required.contains(&json!("content")));
581 }
582
583 #[test]
584 fn endpoints_can_arrive_late_or_be_omitted_from_later_events() {
585 let block = ContentBlock::Text(crate::v1::TextContent::new("hello"));
586 let minimal = SessionMessage::new("m1");
587 let first = SessionMessageChunk::new("m1", block.clone());
588 assert_eq!(
589 serde_json::to_value(&minimal).unwrap(),
590 json!({"messageId": "m1"})
591 );
592 assert_eq!(
593 serde_json::to_value(&first).unwrap(),
594 json!({"messageId": "m1", "content": {"type": "text", "text": "hello"}})
595 );
596 let enriched = SessionMessage::new("m1")
597 .sender_session_id(SessionId::new("parent"))
598 .recipient_session_id(SessionId::new("child"));
599 assert_eq!(
600 enriched.sender_session_id,
601 MaybeUndefined::Value(SessionId::new("parent"))
602 );
603 assert_eq!(
604 enriched.recipient_session_id,
605 MaybeUndefined::Value(SessionId::new("child"))
606 );
607 let later = SessionMessage::new("m1").sender_session_id(SessionId::new("parent"));
608 assert_eq!(
609 later.sender_session_id,
610 MaybeUndefined::Value(SessionId::new("parent"))
611 );
612 assert_eq!(later.recipient_session_id, MaybeUndefined::Undefined);
613 let more = SessionMessageChunk::new("m1", block);
614 for update in [
615 SessionUpdate::SessionMessage(minimal),
616 SessionUpdate::SessionMessageChunk(first),
617 SessionUpdate::SessionMessage(enriched),
618 SessionUpdate::SessionMessage(later),
619 SessionUpdate::SessionMessageChunk(more),
620 ] {
621 let wire = serde_json::to_value(&update).unwrap();
622 let decoded: SessionUpdate = serde_json::from_value(wire.clone()).unwrap();
623 assert_eq!(serde_json::to_value(decoded).unwrap(), wire);
624 }
625 }
626
627 #[test]
628 fn null_endpoints_clear_invalid_are_absent_but_message_id_is_required() {
629 let mut base = json!({"sessionUpdate": "session_message", "messageId": "m1",
630 "senderSessionId": null, "recipientSessionId": 42});
631 let decoded: SessionUpdate = serde_json::from_value(base.clone()).unwrap();
632 let encoded = serde_json::to_value(decoded).unwrap();
633 base.as_object_mut().unwrap().remove("recipientSessionId");
634 assert_eq!(encoded, base);
635 for bad in [Value::Null, json!(42)] {
636 let mut invalid = base.clone();
637 invalid["messageId"] = bad;
638 assert!(serde_json::from_value::<SessionUpdate>(invalid).is_err());
639 }
640 }
641
642 #[test]
643 fn message_references_link_views_and_can_arrive_late() {
644 let block = ContentBlock::Text(crate::v1::TextContent::new("hello"));
645 let incoming = SessionMessage::new("received-1")
646 .sender_session_id(SessionId::new("parent"))
647 .recipient_session_id(SessionId::new("child"))
648 .sender_message_id(MessageId::new("sent-1"))
649 .content(vec![block]);
650 let outgoing =
652 SessionMessage::new("sent-1").recipient_message_id(MessageId::new("received-1"));
653 for (update, wire) in [
654 (
655 SessionUpdate::SessionMessage(incoming),
656 json!({"sessionUpdate": "session_message", "messageId": "received-1",
657 "senderSessionId": "parent", "recipientSessionId": "child",
658 "senderMessageId": "sent-1", "content": [{"type": "text", "text": "hello"}]}),
659 ),
660 (
661 SessionUpdate::SessionMessage(outgoing),
662 json!({"sessionUpdate": "session_message", "messageId": "sent-1",
663 "recipientMessageId": "received-1"}),
664 ),
665 ] {
666 assert_eq!(serde_json::to_value(&update).unwrap(), wire);
667 let decoded: SessionUpdate = serde_json::from_value(wire.clone()).unwrap();
668 assert_eq!(decoded, update);
669 }
670
671 let mut wire = json!({"sessionUpdate": "session_message", "messageId": "m1",
672 "senderMessageId": null, "recipientMessageId": 42});
673 let decoded: SessionUpdate = serde_json::from_value(wire.clone()).unwrap();
674 wire.as_object_mut().unwrap().remove("recipientMessageId");
675 assert_eq!(
676 serde_json::to_value(decoded).unwrap(),
677 wire,
678 "null clears a reference and a malformed one is not supplied"
679 );
680 }
681}
682
683#[cfg(all(test, not(feature = "unstable_subagents")))]
684mod disabled_session_message_tests {
685 use super::*;
686 use serde_json::json;
687
688 #[test]
689 fn message_updates_require_subagents_gate() {
690 for (kind, content) in [
691 ("session_message", json!([])),
692 (
693 "session_message_chunk",
694 json!({"type": "text", "text": "hello"}),
695 ),
696 ] {
697 let wire = json!({"sessionUpdate": kind, "messageId": "m1", "content": content});
698 assert!(serde_json::from_value::<SessionUpdate>(wire).is_err());
699 }
700 }
701}
702
703#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
705#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
706#[serde(rename_all = "snake_case")]
707#[non_exhaustive]
708pub enum NoticeSeverity {
709 Info,
711 Warning,
713 Error,
715 #[serde(untagged)]
720 Other(String),
721}
722
723#[serde_as]
733#[skip_serializing_none]
734#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
735#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
736#[serde(rename_all = "camelCase")]
737#[non_exhaustive]
738pub struct Notice {
739 pub severity: NoticeSeverity,
741 #[cfg_attr(feature = "schemars", schemars(length(min = 1)))]
743 pub title: String,
744 #[serde_as(deserialize_as = "DefaultOnError")]
748 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
749 #[serde(default)]
750 pub description: Option<String>,
751 #[serde_as(deserialize_as = "DefaultOnError")]
755 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
756 #[serde(default, rename = "_meta")]
757 pub meta: Option<Meta>,
758}
759
760impl Notice {
761 #[must_use]
763 pub fn new(severity: NoticeSeverity, title: impl Into<String>) -> Self {
764 Self {
765 severity,
766 title: title.into(),
767 description: None,
768 meta: None,
769 }
770 }
771
772 #[must_use]
774 pub fn description(mut self, description: impl IntoOption<String>) -> Self {
775 self.description = description.into_option();
776 self
777 }
778
779 #[must_use]
781 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
782 self.meta = meta.into_option();
783 self
784 }
785}
786
787#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
789#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
790#[serde(transparent)]
791#[from(Arc<str>, String, &'static str)]
792#[non_exhaustive]
793pub struct CompactionId(pub Arc<str>);
794
795impl CompactionId {
796 #[must_use]
798 pub fn new(id: impl Into<Arc<str>>) -> Self {
799 Self(id.into())
800 }
801}
802
803#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
805#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
806#[serde(rename_all = "snake_case")]
807#[non_exhaustive]
808pub enum CompactionStatus {
809 #[default]
811 InProgress,
812 Completed,
814 Failed,
816 Cancelled,
818 #[serde(untagged)]
823 Other(String),
824}
825
826#[serde_as]
835#[skip_serializing_none]
836#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
837#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
838#[serde(rename_all = "camelCase")]
839#[non_exhaustive]
840pub struct CompactionUpdate {
841 pub compaction_id: CompactionId,
843 pub status: CompactionStatus,
845 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<VecSkipError<_>>>")]
847 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
848 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
849 pub summary: MaybeUndefined<Vec<ContentBlock>>,
850 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
852 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
853 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
854 pub error: MaybeUndefined<String>,
855 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
857 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
858 #[serde(
859 rename = "_meta",
860 default,
861 skip_serializing_if = "MaybeUndefined::is_undefined"
862 )]
863 pub meta: MaybeUndefined<Meta>,
864}
865
866impl CompactionUpdate {
867 #[must_use]
869 pub fn new(compaction_id: impl Into<CompactionId>, status: CompactionStatus) -> Self {
870 Self {
871 compaction_id: compaction_id.into(),
872 status,
873 summary: MaybeUndefined::Undefined,
874 error: MaybeUndefined::Undefined,
875 meta: MaybeUndefined::Undefined,
876 }
877 }
878
879 #[must_use]
881 pub fn summary(mut self, summary: impl IntoMaybeUndefined<Vec<ContentBlock>>) -> Self {
882 self.summary = summary.into_maybe_undefined();
883 self
884 }
885
886 #[must_use]
888 pub fn error(mut self, error: impl IntoMaybeUndefined<String>) -> Self {
889 self.error = error.into_maybe_undefined();
890 self
891 }
892
893 #[must_use]
895 pub fn meta(mut self, meta: impl IntoMaybeUndefined<Meta>) -> Self {
896 self.meta = meta.into_maybe_undefined();
897 self
898 }
899}
900
901#[serde_as]
906#[skip_serializing_none]
907#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
908#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
909#[serde(rename_all = "camelCase")]
910#[non_exhaustive]
911pub struct CompactionSummaryChunk {
912 pub compaction_id: CompactionId,
914 pub content: ContentBlock,
916 #[serde_as(deserialize_as = "DefaultOnError")]
918 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
919 #[serde(default, rename = "_meta")]
920 pub meta: Option<Meta>,
921}
922
923impl CompactionSummaryChunk {
924 #[must_use]
926 pub fn new(compaction_id: impl Into<CompactionId>, content: ContentBlock) -> Self {
927 Self {
928 compaction_id: compaction_id.into(),
929 content,
930 meta: None,
931 }
932 }
933
934 #[must_use]
936 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
937 self.meta = meta.into_option();
938 self
939 }
940}
941
942#[cfg(feature = "unstable_subagents")]
968#[serde_as]
969#[skip_serializing_none]
970#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
971#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
972#[serde(rename_all = "camelCase")]
973#[non_exhaustive]
974pub struct SubagentUpdate {
975 pub session_id: SessionId,
977 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
982 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
983 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
984 pub title: MaybeUndefined<String>,
985 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
991 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
992 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
993 pub description: MaybeUndefined<String>,
994 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
1001 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1002 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
1003 pub capabilities: MaybeUndefined<SubagentSessionCapabilities>,
1004 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
1011 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1012 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
1013 pub state: MaybeUndefined<StateUpdate>,
1014 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
1021 pub cwd: MaybeUndefined<PathBuf>,
1022 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
1030 pub additional_directories: MaybeUndefined<Vec<PathBuf>>,
1031 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
1038 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1039 #[serde(
1040 default,
1041 rename = "_meta",
1042 skip_serializing_if = "MaybeUndefined::is_undefined"
1043 )]
1044 pub meta: MaybeUndefined<Meta>,
1045}
1046
1047#[cfg(feature = "unstable_subagents")]
1048impl SubagentUpdate {
1049 #[must_use]
1051 pub fn new(session_id: impl Into<SessionId>) -> Self {
1052 Self {
1053 session_id: session_id.into(),
1054 title: MaybeUndefined::Undefined,
1055 description: MaybeUndefined::Undefined,
1056 capabilities: MaybeUndefined::Undefined,
1057 state: MaybeUndefined::Undefined,
1058 cwd: MaybeUndefined::Undefined,
1059 additional_directories: MaybeUndefined::Undefined,
1060 meta: MaybeUndefined::Undefined,
1061 }
1062 }
1063
1064 #[must_use]
1066 pub fn title(mut self, title: impl IntoMaybeUndefined<String>) -> Self {
1067 self.title = title.into_maybe_undefined();
1068 self
1069 }
1070
1071 #[must_use]
1073 pub fn description(mut self, description: impl IntoMaybeUndefined<String>) -> Self {
1074 self.description = description.into_maybe_undefined();
1075 self
1076 }
1077
1078 #[must_use]
1080 pub fn capabilities(
1081 mut self,
1082 capabilities: impl IntoMaybeUndefined<SubagentSessionCapabilities>,
1083 ) -> Self {
1084 self.capabilities = capabilities.into_maybe_undefined();
1085 self
1086 }
1087
1088 #[must_use]
1090 pub fn state(mut self, state: impl IntoMaybeUndefined<StateUpdate>) -> Self {
1091 self.state = state.into_maybe_undefined();
1092 self
1093 }
1094
1095 #[must_use]
1099 pub fn cwd(mut self, cwd: impl IntoMaybeUndefined<PathBuf>) -> Self {
1100 self.cwd = cwd.into_maybe_undefined();
1101 self
1102 }
1103
1104 #[must_use]
1108 pub fn additional_directories(
1109 mut self,
1110 additional_directories: impl IntoMaybeUndefined<Vec<PathBuf>>,
1111 ) -> Self {
1112 self.additional_directories = additional_directories.into_maybe_undefined();
1113 self
1114 }
1115
1116 #[must_use]
1120 pub fn meta(mut self, meta: impl IntoMaybeUndefined<Meta>) -> Self {
1121 self.meta = meta.into_maybe_undefined();
1122 self
1123 }
1124}
1125
1126#[cfg(feature = "unstable_subagents")]
1135#[serde_as]
1136#[skip_serializing_none]
1137#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1138#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1139#[serde(rename_all = "camelCase")]
1140#[non_exhaustive]
1141pub struct SubagentSessionCapabilities {
1142 #[serde_as(deserialize_as = "DefaultOnError")]
1146 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1147 #[serde(default)]
1148 pub cancel: Option<SessionCancelCapabilities>,
1149 #[serde_as(deserialize_as = "DefaultOnError")]
1153 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1154 #[serde(default)]
1155 #[serde(rename = "_meta")]
1156 pub meta: Option<Meta>,
1157}
1158
1159#[cfg(feature = "unstable_subagents")]
1160impl SubagentSessionCapabilities {
1161 #[must_use]
1163 pub fn new() -> Self {
1164 Self::default()
1165 }
1166
1167 #[must_use]
1169 pub fn cancel(mut self, cancel: impl IntoOption<SessionCancelCapabilities>) -> Self {
1170 self.cancel = cancel.into_option();
1171 self
1172 }
1173
1174 #[must_use]
1178 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1179 self.meta = meta.into_option();
1180 self
1181 }
1182}
1183
1184#[cfg(feature = "unstable_subagents")]
1192#[serde_as]
1193#[skip_serializing_none]
1194#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1195#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1196#[non_exhaustive]
1197pub struct SessionCancelCapabilities {
1198 #[serde_as(deserialize_as = "DefaultOnError")]
1204 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1205 #[serde(default)]
1206 #[serde(rename = "_meta")]
1207 pub meta: Option<Meta>,
1208}
1209
1210#[cfg(feature = "unstable_subagents")]
1211impl SessionCancelCapabilities {
1212 #[must_use]
1214 pub fn new() -> Self {
1215 Self::default()
1216 }
1217
1218 #[must_use]
1224 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1225 self.meta = meta.into_option();
1226 self
1227 }
1228}
1229
1230#[cfg(feature = "unstable_subagents")]
1240#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1241#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1242#[serde(tag = "state", rename_all = "snake_case")]
1243#[non_exhaustive]
1244pub enum StateUpdate {
1245 Running(RunningStateUpdate),
1247 Idle(IdleStateUpdate),
1249 RequiresAction(RequiresActionStateUpdate),
1251 Unknown(UnknownStateUpdate),
1255 #[serde(untagged)]
1260 Other(OtherStateUpdate),
1261}
1262
1263#[cfg(feature = "unstable_subagents")]
1265#[serde_as]
1266#[skip_serializing_none]
1267#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1268#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1269#[serde(rename_all = "camelCase")]
1270#[non_exhaustive]
1271pub struct RunningStateUpdate {
1272 #[serde_as(deserialize_as = "DefaultOnError")]
1276 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1277 #[serde(default, rename = "_meta")]
1278 pub meta: Option<Meta>,
1279}
1280
1281#[cfg(feature = "unstable_subagents")]
1282impl RunningStateUpdate {
1283 #[must_use]
1285 pub fn new() -> Self {
1286 Self::default()
1287 }
1288
1289 #[must_use]
1291 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1292 self.meta = meta.into_option();
1293 self
1294 }
1295}
1296
1297#[cfg(feature = "unstable_subagents")]
1301#[serde_as]
1302#[skip_serializing_none]
1303#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1304#[cfg_attr(feature = "schemars", schemars(transform = idle_state_update_schema))]
1305#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1306#[serde(rename_all = "camelCase")]
1307#[non_exhaustive]
1308pub struct IdleStateUpdate {
1309 #[serde(flatten)]
1311 pub stop_reason: Option<IdleStopReason>,
1312 #[cfg(feature = "unstable_end_turn_token_usage")]
1316 #[serde_as(deserialize_as = "DefaultOnError")]
1317 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1318 #[serde(default)]
1319 pub usage: Option<Box<Usage>>,
1320 #[serde_as(deserialize_as = "DefaultOnError")]
1324 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1325 #[serde(default, rename = "_meta")]
1326 pub meta: Option<Meta>,
1327}
1328
1329#[cfg(feature = "unstable_subagents")]
1330impl IdleStateUpdate {
1331 #[must_use]
1333 pub fn new() -> Self {
1334 Self::default()
1335 }
1336
1337 #[must_use]
1339 pub fn stop_reason(mut self, stop_reason: impl IntoOption<IdleStopReason>) -> Self {
1340 self.stop_reason = stop_reason.into_option();
1341 self
1342 }
1343
1344 #[cfg(feature = "unstable_end_turn_token_usage")]
1346 #[must_use]
1347 pub fn usage(mut self, usage: impl IntoOption<Usage>) -> Self {
1348 self.usage = usage.into_option().map(Box::new);
1349 self
1350 }
1351
1352 #[must_use]
1354 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1355 self.meta = meta.into_option();
1356 self
1357 }
1358}
1359
1360#[cfg(all(feature = "unstable_subagents", feature = "schemars"))]
1369fn idle_state_update_schema(schema: &mut Schema) {
1370 if let Some(properties) = schema
1371 .get_mut("properties")
1372 .and_then(serde_json::Value::as_object_mut)
1373 {
1374 properties.insert(
1375 "stopReason".into(),
1376 serde_json::json!({
1377 "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: [Current work state](https://agentclientprotocol.com/rfds/subagents#current-work-state)",
1378 "type": ["string", "null"],
1379 "x-deserialize-default-on-error": true
1380 }),
1381 );
1382 }
1383 let Some(variants) = schema
1384 .get_mut("anyOf")
1385 .and_then(serde_json::Value::as_array_mut)
1386 else {
1387 return;
1388 };
1389 for variant in variants {
1390 if variant.as_object().is_some_and(serde_json::Map::is_empty) {
1391 *variant = serde_json::json!({
1392 "title": "none",
1393 "description": "No stop reason: `stopReason` is omitted or `null`.",
1394 "type": "object",
1395 "properties": {
1396 "stopReason": { "type": "null" }
1397 }
1398 });
1399 }
1400 }
1401}
1402
1403#[cfg(feature = "unstable_subagents")]
1416#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1417#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1418#[serde(tag = "stopReason", rename_all = "snake_case")]
1419#[non_exhaustive]
1420pub enum IdleStopReason {
1421 EndTurn,
1423 MaxTokens,
1425 MaxTurnRequests,
1428 Refusal,
1430 Cancelled,
1432 Error(ErrorStopReason),
1434 #[serde(untagged)]
1439 Other(OtherStopReason),
1440}
1441
1442#[cfg(feature = "unstable_subagents")]
1443impl From<ErrorStopReason> for IdleStopReason {
1444 fn from(value: ErrorStopReason) -> Self {
1445 Self::Error(value)
1446 }
1447}
1448
1449#[cfg(feature = "unstable_subagents")]
1455#[serde_as]
1456#[skip_serializing_none]
1457#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1458#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1459#[serde(rename_all = "camelCase")]
1460#[non_exhaustive]
1461pub struct ErrorStopReason {
1462 #[serde_as(deserialize_as = "DefaultOnError")]
1467 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1468 #[serde(default)]
1469 pub error: Option<Box<Error>>,
1470}
1471
1472#[cfg(feature = "unstable_subagents")]
1473impl ErrorStopReason {
1474 #[must_use]
1476 pub fn new() -> Self {
1477 Self::default()
1478 }
1479
1480 #[must_use]
1482 pub fn error(mut self, error: impl IntoOption<Error>) -> Self {
1483 self.error = error.into_option().map(Box::new);
1484 self
1485 }
1486}
1487
1488#[cfg(feature = "unstable_subagents")]
1494#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1495#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
1496#[cfg_attr(feature = "schemars", schemars(inline))]
1497#[cfg_attr(feature = "schemars", schemars(transform = other_stop_reason_schema))]
1498#[serde(rename_all = "camelCase")]
1499#[non_exhaustive]
1500pub struct OtherStopReason {
1501 pub stop_reason: String,
1503 #[serde(flatten)]
1505 pub fields: BTreeMap<String, serde_json::Value>,
1506}
1507
1508#[cfg(feature = "unstable_subagents")]
1509impl OtherStopReason {
1510 #[must_use]
1512 pub fn new(
1513 stop_reason: impl Into<String>,
1514 mut fields: BTreeMap<String, serde_json::Value>,
1515 ) -> Self {
1516 remove_idle_state_update_fields(&mut fields);
1517 Self {
1518 stop_reason: stop_reason.into(),
1519 fields,
1520 }
1521 }
1522}
1523
1524#[cfg(feature = "unstable_subagents")]
1525impl<'de> Deserialize<'de> for OtherStopReason {
1526 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1527 where
1528 D: serde::Deserializer<'de>,
1529 {
1530 let mut fields = BTreeMap::<String, serde_json::Value>::deserialize(deserializer)?;
1531 let stop_reason = fields
1532 .remove("stopReason")
1533 .ok_or_else(|| serde::de::Error::missing_field("stopReason"))?;
1534 let serde_json::Value::String(stop_reason) = stop_reason else {
1535 return Err(serde::de::Error::custom("`stopReason` must be a string"));
1536 };
1537 if KNOWN_STOP_REASONS.contains(&stop_reason.as_str()) {
1538 return Err(serde::de::Error::custom(format!(
1539 "known stop reason `{stop_reason}` did not match its schema"
1540 )));
1541 }
1542 remove_idle_state_update_fields(&mut fields);
1543 Ok(Self {
1544 stop_reason,
1545 fields,
1546 })
1547 }
1548}
1549
1550#[cfg(feature = "unstable_subagents")]
1551const KNOWN_STOP_REASONS: &[&str] = &[
1552 "end_turn",
1553 "max_tokens",
1554 "max_turn_requests",
1555 "refusal",
1556 "cancelled",
1557 "error",
1558];
1559
1560#[cfg(feature = "unstable_subagents")]
1562fn remove_idle_state_update_fields(fields: &mut BTreeMap<String, serde_json::Value>) {
1563 fields.remove("stopReason");
1564 fields.remove("usage");
1565 fields.remove("_meta");
1566}
1567
1568#[cfg(all(feature = "unstable_subagents", feature = "schemars"))]
1569fn other_stop_reason_schema(schema: &mut Schema) {
1570 let known = KNOWN_STOP_REASONS
1571 .iter()
1572 .map(|stop_reason| {
1573 serde_json::json!({
1574 "properties": { "stopReason": { "const": stop_reason, "type": "string" } },
1575 "required": ["stopReason"],
1576 "type": "object"
1577 })
1578 })
1579 .collect::<Vec<_>>();
1580 schema.insert("not".into(), serde_json::json!({ "anyOf": known }));
1581}
1582
1583#[cfg(feature = "unstable_subagents")]
1585#[serde_as]
1586#[skip_serializing_none]
1587#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1588#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1589#[serde(rename_all = "camelCase")]
1590#[non_exhaustive]
1591pub struct RequiresActionStateUpdate {
1592 #[serde_as(deserialize_as = "DefaultOnError")]
1596 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1597 #[serde(default, rename = "_meta")]
1598 pub meta: Option<Meta>,
1599}
1600
1601#[cfg(feature = "unstable_subagents")]
1602impl RequiresActionStateUpdate {
1603 #[must_use]
1605 pub fn new() -> Self {
1606 Self::default()
1607 }
1608
1609 #[must_use]
1611 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1612 self.meta = meta.into_option();
1613 self
1614 }
1615}
1616
1617#[cfg(feature = "unstable_subagents")]
1634#[serde_as]
1635#[skip_serializing_none]
1636#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1637#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1638#[serde(rename_all = "camelCase")]
1639#[non_exhaustive]
1640pub struct UnknownStateUpdate {
1641 #[serde_as(deserialize_as = "DefaultOnError")]
1645 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1646 #[serde(default, rename = "_meta")]
1647 pub meta: Option<Meta>,
1648}
1649
1650#[cfg(feature = "unstable_subagents")]
1651impl UnknownStateUpdate {
1652 #[must_use]
1654 pub fn new() -> Self {
1655 Self::default()
1656 }
1657
1658 #[must_use]
1660 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1661 self.meta = meta.into_option();
1662 self
1663 }
1664}
1665
1666#[cfg(feature = "unstable_subagents")]
1668#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1669#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
1670#[cfg_attr(feature = "schemars", schemars(inline))]
1671#[cfg_attr(feature = "schemars", schemars(transform = other_state_update_schema))]
1672#[serde(rename_all = "camelCase")]
1673#[non_exhaustive]
1674pub struct OtherStateUpdate {
1675 pub state: String,
1677 #[serde(flatten)]
1679 pub fields: BTreeMap<String, serde_json::Value>,
1680}
1681
1682#[cfg(feature = "unstable_subagents")]
1683impl OtherStateUpdate {
1684 #[must_use]
1686 pub fn new(state: impl Into<String>, mut fields: BTreeMap<String, serde_json::Value>) -> Self {
1687 fields.remove("state");
1688 Self {
1689 state: state.into(),
1690 fields,
1691 }
1692 }
1693}
1694
1695#[cfg(feature = "unstable_subagents")]
1696impl<'de> Deserialize<'de> for OtherStateUpdate {
1697 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1698 where
1699 D: serde::Deserializer<'de>,
1700 {
1701 let mut fields = BTreeMap::<String, serde_json::Value>::deserialize(deserializer)?;
1702 let state = fields
1703 .remove("state")
1704 .ok_or_else(|| serde::de::Error::missing_field("state"))?;
1705 let serde_json::Value::String(state) = state else {
1706 return Err(serde::de::Error::custom("`state` must be a string"));
1707 };
1708 if is_known_state_update(&state) {
1709 return Err(serde::de::Error::custom(format!(
1710 "known state update `{state}` did not match its schema"
1711 )));
1712 }
1713 Ok(Self { state, fields })
1714 }
1715}
1716
1717#[cfg(feature = "unstable_subagents")]
1718const KNOWN_STATE_UPDATE_STATES: &[&str] = &["running", "idle", "requires_action", "unknown"];
1719
1720#[cfg(feature = "unstable_subagents")]
1721fn is_known_state_update(state: &str) -> bool {
1722 KNOWN_STATE_UPDATE_STATES.contains(&state)
1723}
1724
1725#[cfg(all(feature = "unstable_subagents", feature = "schemars"))]
1726fn other_state_update_schema(schema: &mut Schema) {
1727 let known = KNOWN_STATE_UPDATE_STATES
1728 .iter()
1729 .map(|state| {
1730 serde_json::json!({
1731 "properties": { "state": { "const": state, "type": "string" } },
1732 "required": ["state"],
1733 "type": "object"
1734 })
1735 })
1736 .collect::<Vec<_>>();
1737 schema.insert("not".into(), serde_json::json!({ "anyOf": known }));
1738}
1739
1740#[serde_as]
1744#[skip_serializing_none]
1745#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1746#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1747#[serde(rename_all = "camelCase")]
1748#[non_exhaustive]
1749pub struct CurrentModeUpdate {
1750 pub current_mode_id: SessionModeId,
1752 #[serde_as(deserialize_as = "DefaultOnError")]
1758 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1759 #[serde(default)]
1760 #[serde(rename = "_meta")]
1761 pub meta: Option<Meta>,
1762}
1763
1764impl CurrentModeUpdate {
1765 #[must_use]
1767 pub fn new(current_mode_id: impl Into<SessionModeId>) -> Self {
1768 Self {
1769 current_mode_id: current_mode_id.into(),
1770 meta: None,
1771 }
1772 }
1773
1774 #[must_use]
1780 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1781 self.meta = meta.into_option();
1782 self
1783 }
1784}
1785
1786#[serde_as]
1788#[skip_serializing_none]
1789#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1790#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1791#[serde(rename_all = "camelCase")]
1792#[non_exhaustive]
1793pub struct ConfigOptionUpdate {
1794 #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
1796 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
1797 pub config_options: Vec<SessionConfigOption>,
1798 #[serde_as(deserialize_as = "DefaultOnError")]
1804 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1805 #[serde(default)]
1806 #[serde(rename = "_meta")]
1807 pub meta: Option<Meta>,
1808}
1809
1810impl ConfigOptionUpdate {
1811 #[must_use]
1813 pub fn new(config_options: Vec<SessionConfigOption>) -> Self {
1814 Self {
1815 config_options,
1816 meta: None,
1817 }
1818 }
1819
1820 #[must_use]
1826 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1827 self.meta = meta.into_option();
1828 self
1829 }
1830}
1831
1832#[serde_as]
1837#[skip_serializing_none]
1838#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1839#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1840#[serde(rename_all = "camelCase")]
1841#[non_exhaustive]
1842pub struct SessionInfoUpdate {
1843 #[serde_as(deserialize_as = "DefaultOnError")]
1845 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1846 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
1847 pub title: MaybeUndefined<String>,
1848 #[serde_as(deserialize_as = "DefaultOnError")]
1850 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1851 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
1852 pub updated_at: MaybeUndefined<String>,
1853 #[serde_as(deserialize_as = "DefaultOnError")]
1859 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1860 #[serde(default)]
1861 #[serde(rename = "_meta")]
1862 pub meta: Option<Meta>,
1863}
1864
1865impl SessionInfoUpdate {
1866 #[must_use]
1868 pub fn new() -> Self {
1869 Self::default()
1870 }
1871
1872 #[must_use]
1874 pub fn title(mut self, title: impl IntoMaybeUndefined<String>) -> Self {
1875 self.title = title.into_maybe_undefined();
1876 self
1877 }
1878
1879 #[must_use]
1881 pub fn updated_at(mut self, updated_at: impl IntoMaybeUndefined<String>) -> Self {
1882 self.updated_at = updated_at.into_maybe_undefined();
1883 self
1884 }
1885
1886 #[must_use]
1892 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1893 self.meta = meta.into_option();
1894 self
1895 }
1896}
1897
1898#[serde_as]
1900#[skip_serializing_none]
1901#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1902#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1903#[serde(rename_all = "camelCase")]
1904#[non_exhaustive]
1905pub struct UsageUpdate {
1906 pub used: u64,
1908 pub size: u64,
1910 #[serde_as(deserialize_as = "DefaultOnError")]
1912 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1913 #[serde(default)]
1914 pub cost: Option<Cost>,
1915 #[serde_as(deserialize_as = "DefaultOnError")]
1921 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1922 #[serde(default)]
1923 #[serde(rename = "_meta")]
1924 pub meta: Option<Meta>,
1925}
1926
1927impl UsageUpdate {
1928 #[must_use]
1930 pub fn new(used: u64, size: u64) -> Self {
1931 Self {
1932 used,
1933 size,
1934 cost: None,
1935 meta: None,
1936 }
1937 }
1938
1939 #[must_use]
1941 pub fn cost(mut self, cost: impl IntoOption<Cost>) -> Self {
1942 self.cost = cost.into_option();
1943 self
1944 }
1945
1946 #[must_use]
1952 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1953 self.meta = meta.into_option();
1954 self
1955 }
1956}
1957
1958#[serde_as]
1960#[skip_serializing_none]
1961#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1962#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1963#[serde(rename_all = "camelCase")]
1964#[non_exhaustive]
1965pub struct Cost {
1966 pub amount: f64,
1968 pub currency: String,
1971 #[serde_as(deserialize_as = "DefaultOnError")]
1977 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1978 #[serde(default)]
1979 #[serde(rename = "_meta")]
1980 pub meta: Option<Meta>,
1981}
1982
1983impl Cost {
1984 #[must_use]
1986 pub fn new(amount: f64, currency: impl Into<String>) -> Self {
1987 Self {
1988 amount,
1989 currency: currency.into(),
1990 meta: None,
1991 }
1992 }
1993
1994 #[must_use]
2000 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2001 self.meta = meta.into_option();
2002 self
2003 }
2004}
2005
2006#[serde_as]
2008#[skip_serializing_none]
2009#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2010#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2011#[serde(rename_all = "camelCase")]
2012#[non_exhaustive]
2013pub struct ContentChunk {
2014 pub content: ContentBlock,
2016 #[serde_as(deserialize_as = "DefaultOnError")]
2021 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2022 #[serde(default)]
2023 pub message_id: Option<MessageId>,
2024 #[serde_as(deserialize_as = "DefaultOnError")]
2030 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2031 #[serde(default)]
2032 #[serde(rename = "_meta")]
2033 pub meta: Option<Meta>,
2034}
2035
2036impl ContentChunk {
2037 #[must_use]
2039 pub fn new(content: ContentBlock) -> Self {
2040 Self {
2041 content,
2042 message_id: None,
2043 meta: None,
2044 }
2045 }
2046
2047 #[must_use]
2052 pub fn message_id(mut self, message_id: impl IntoOption<MessageId>) -> Self {
2053 self.message_id = message_id.into_option();
2054 self
2055 }
2056
2057 #[must_use]
2063 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2064 self.meta = meta.into_option();
2065 self
2066 }
2067}
2068
2069#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2071#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
2072#[serde(transparent)]
2073#[from(Arc<str>, String, &'static str)]
2074#[non_exhaustive]
2075pub struct MessageId(pub Arc<str>);
2076
2077impl MessageId {
2078 #[must_use]
2080 pub fn new(id: impl Into<Arc<str>>) -> Self {
2081 Self(id.into())
2082 }
2083}
2084
2085impl IntoOption<MessageId> for &str {
2086 fn into_option(self) -> Option<MessageId> {
2087 Some(MessageId::new(self))
2088 }
2089}
2090
2091#[cfg(feature = "unstable_prompt_suggestions")]
2108#[serde_as]
2109#[skip_serializing_none]
2110#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2111#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2112#[serde(rename_all = "camelCase")]
2113#[non_exhaustive]
2114pub struct PromptSuggestionsUpdate {
2115 #[serde_as(deserialize_as = "VecSkipError<_>")]
2121 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-skip-invalid-items" = true)))]
2122 pub suggestions: Vec<PromptSuggestion>,
2123 #[serde_as(deserialize_as = "DefaultOnError")]
2129 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2130 #[serde(default)]
2131 #[serde(rename = "_meta")]
2132 pub meta: Option<Meta>,
2133}
2134
2135#[cfg(feature = "unstable_prompt_suggestions")]
2136impl PromptSuggestionsUpdate {
2137 #[must_use]
2141 pub fn new(suggestions: Vec<PromptSuggestion>) -> Self {
2142 Self {
2143 suggestions,
2144 meta: None,
2145 }
2146 }
2147
2148 #[must_use]
2154 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2155 self.meta = meta.into_option();
2156 self
2157 }
2158}
2159
2160#[cfg(feature = "unstable_prompt_suggestions")]
2166#[serde_as]
2167#[skip_serializing_none]
2168#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2169#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2170#[serde(rename_all = "camelCase")]
2171#[non_exhaustive]
2172pub struct PromptSuggestion {
2173 #[cfg_attr(feature = "schemars", schemars(length(min = 1)))]
2185 pub prompt: Vec<ContentBlock>,
2186 #[serde_as(deserialize_as = "DefaultOnError")]
2192 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2193 #[serde(default)]
2194 #[serde(rename = "_meta")]
2195 pub meta: Option<Meta>,
2196}
2197
2198#[cfg(feature = "unstable_prompt_suggestions")]
2199impl PromptSuggestion {
2200 #[must_use]
2202 pub fn new(prompt: Vec<ContentBlock>) -> Self {
2203 Self { prompt, meta: None }
2204 }
2205
2206 #[must_use]
2212 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2213 self.meta = meta.into_option();
2214 self
2215 }
2216}
2217
2218#[serde_as]
2220#[skip_serializing_none]
2221#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2222#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2223#[serde(rename_all = "camelCase")]
2224#[non_exhaustive]
2225pub struct AvailableCommandsUpdate {
2226 #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
2228 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
2229 pub available_commands: Vec<AvailableCommand>,
2230 #[serde_as(deserialize_as = "DefaultOnError")]
2236 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2237 #[serde(default)]
2238 #[serde(rename = "_meta")]
2239 pub meta: Option<Meta>,
2240}
2241
2242impl AvailableCommandsUpdate {
2243 #[must_use]
2245 pub fn new(available_commands: Vec<AvailableCommand>) -> Self {
2246 Self {
2247 available_commands,
2248 meta: None,
2249 }
2250 }
2251
2252 #[must_use]
2258 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2259 self.meta = meta.into_option();
2260 self
2261 }
2262}
2263
2264#[serde_as]
2266#[skip_serializing_none]
2267#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2268#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2269#[serde(rename_all = "camelCase")]
2270#[non_exhaustive]
2271pub struct AvailableCommand {
2272 pub name: String,
2274 pub description: String,
2276 #[serde_as(deserialize_as = "DefaultOnError")]
2278 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2279 #[serde(default)]
2280 pub input: Option<AvailableCommandInput>,
2281 #[serde_as(deserialize_as = "DefaultOnError")]
2287 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2288 #[serde(default)]
2289 #[serde(rename = "_meta")]
2290 pub meta: Option<Meta>,
2291}
2292
2293impl AvailableCommand {
2294 #[must_use]
2296 pub fn new(name: impl Into<String>, description: impl Into<String>) -> Self {
2297 Self {
2298 name: name.into(),
2299 description: description.into(),
2300 input: None,
2301 meta: None,
2302 }
2303 }
2304
2305 #[must_use]
2307 pub fn input(mut self, input: impl IntoOption<AvailableCommandInput>) -> Self {
2308 self.input = input.into_option();
2309 self
2310 }
2311
2312 #[must_use]
2318 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2319 self.meta = meta.into_option();
2320 self
2321 }
2322}
2323
2324#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2326#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2327#[serde(untagged, rename_all = "camelCase")]
2328#[non_exhaustive]
2329pub enum AvailableCommandInput {
2330 Unstructured(UnstructuredCommandInput),
2332}
2333
2334#[serde_as]
2336#[skip_serializing_none]
2337#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2338#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2339#[serde(rename_all = "camelCase")]
2340#[non_exhaustive]
2341pub struct UnstructuredCommandInput {
2342 pub hint: String,
2344 #[serde_as(deserialize_as = "DefaultOnError")]
2350 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2351 #[serde(default)]
2352 #[serde(rename = "_meta")]
2353 pub meta: Option<Meta>,
2354}
2355
2356impl UnstructuredCommandInput {
2357 #[must_use]
2359 pub fn new(hint: impl Into<String>) -> Self {
2360 Self {
2361 hint: hint.into(),
2362 meta: None,
2363 }
2364 }
2365
2366 #[must_use]
2372 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2373 self.meta = meta.into_option();
2374 self
2375 }
2376}
2377
2378#[serde_as]
2386#[skip_serializing_none]
2387#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2388#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2389#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = SESSION_REQUEST_PERMISSION_METHOD_NAME)))]
2390#[serde(rename_all = "camelCase")]
2391#[non_exhaustive]
2392pub struct RequestPermissionRequest {
2393 pub session_id: SessionId,
2395 pub tool_call: ToolCallUpdate,
2397 pub options: Vec<PermissionOption>,
2399 #[serde_as(deserialize_as = "DefaultOnError")]
2405 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2406 #[serde(default)]
2407 #[serde(rename = "_meta")]
2408 pub meta: Option<Meta>,
2409}
2410
2411impl RequestPermissionRequest {
2412 #[must_use]
2414 pub fn new(
2415 session_id: impl Into<SessionId>,
2416 tool_call: ToolCallUpdate,
2417 options: Vec<PermissionOption>,
2418 ) -> Self {
2419 Self {
2420 session_id: session_id.into(),
2421 tool_call,
2422 options,
2423 meta: None,
2424 }
2425 }
2426
2427 #[must_use]
2433 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2434 self.meta = meta.into_option();
2435 self
2436 }
2437}
2438
2439#[serde_as]
2441#[skip_serializing_none]
2442#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2443#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2444#[serde(rename_all = "camelCase")]
2445#[non_exhaustive]
2446pub struct PermissionOption {
2447 pub option_id: PermissionOptionId,
2449 pub name: String,
2451 pub kind: PermissionOptionKind,
2453 #[serde_as(deserialize_as = "DefaultOnError")]
2459 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2460 #[serde(default)]
2461 #[serde(rename = "_meta")]
2462 pub meta: Option<Meta>,
2463}
2464
2465impl PermissionOption {
2466 #[must_use]
2468 pub fn new(
2469 option_id: impl Into<PermissionOptionId>,
2470 name: impl Into<String>,
2471 kind: PermissionOptionKind,
2472 ) -> Self {
2473 Self {
2474 option_id: option_id.into(),
2475 name: name.into(),
2476 kind,
2477 meta: None,
2478 }
2479 }
2480
2481 #[must_use]
2487 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2488 self.meta = meta.into_option();
2489 self
2490 }
2491}
2492
2493#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2495#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
2496#[serde(transparent)]
2497#[from(Arc<str>, String, &'static str)]
2498#[non_exhaustive]
2499pub struct PermissionOptionId(pub Arc<str>);
2500
2501impl PermissionOptionId {
2502 #[must_use]
2504 pub fn new(id: impl Into<Arc<str>>) -> Self {
2505 Self(id.into())
2506 }
2507}
2508
2509#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2513#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
2514#[serde(rename_all = "snake_case")]
2515#[non_exhaustive]
2516pub enum PermissionOptionKind {
2517 AllowOnce,
2519 AllowAlways,
2521 RejectOnce,
2523 RejectAlways,
2525}
2526
2527#[serde_as]
2529#[skip_serializing_none]
2530#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2531#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2532#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = SESSION_REQUEST_PERMISSION_METHOD_NAME)))]
2533#[serde(rename_all = "camelCase")]
2534#[non_exhaustive]
2535pub struct RequestPermissionResponse {
2536 pub outcome: RequestPermissionOutcome,
2539 #[serde_as(deserialize_as = "DefaultOnError")]
2545 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2546 #[serde(default)]
2547 #[serde(rename = "_meta")]
2548 pub meta: Option<Meta>,
2549}
2550
2551impl RequestPermissionResponse {
2552 #[must_use]
2554 pub fn new(outcome: RequestPermissionOutcome) -> Self {
2555 Self {
2556 outcome,
2557 meta: None,
2558 }
2559 }
2560
2561 #[must_use]
2567 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2568 self.meta = meta.into_option();
2569 self
2570 }
2571}
2572
2573#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2575#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2576#[serde(tag = "outcome", rename_all = "snake_case")]
2577#[cfg_attr(feature = "schemars", schemars(extend("discriminator" = {"propertyName": "outcome"})))]
2578#[non_exhaustive]
2579pub enum RequestPermissionOutcome {
2580 Cancelled,
2588 #[serde(rename_all = "camelCase")]
2590 Selected(SelectedPermissionOutcome),
2591}
2592
2593#[serde_as]
2595#[skip_serializing_none]
2596#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2597#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2598#[serde(rename_all = "camelCase")]
2599#[non_exhaustive]
2600pub struct SelectedPermissionOutcome {
2601 pub option_id: PermissionOptionId,
2603 #[serde_as(deserialize_as = "DefaultOnError")]
2609 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2610 #[serde(default)]
2611 #[serde(rename = "_meta")]
2612 pub meta: Option<Meta>,
2613}
2614
2615impl SelectedPermissionOutcome {
2616 #[must_use]
2618 pub fn new(option_id: impl Into<PermissionOptionId>) -> Self {
2619 Self {
2620 option_id: option_id.into(),
2621 meta: None,
2622 }
2623 }
2624
2625 #[must_use]
2631 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2632 self.meta = meta.into_option();
2633 self
2634 }
2635}
2636
2637#[serde_as]
2643#[skip_serializing_none]
2644#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2645#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2646#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = FS_WRITE_TEXT_FILE_METHOD_NAME)))]
2647#[serde(rename_all = "camelCase")]
2648#[non_exhaustive]
2649pub struct WriteTextFileRequest {
2650 pub session_id: SessionId,
2652 pub path: PathBuf,
2654 pub content: String,
2656 #[serde_as(deserialize_as = "DefaultOnError")]
2662 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2663 #[serde(default)]
2664 #[serde(rename = "_meta")]
2665 pub meta: Option<Meta>,
2666}
2667
2668impl WriteTextFileRequest {
2669 #[must_use]
2671 pub fn new(
2672 session_id: impl Into<SessionId>,
2673 path: impl Into<PathBuf>,
2674 content: impl Into<String>,
2675 ) -> Self {
2676 Self {
2677 session_id: session_id.into(),
2678 path: path.into(),
2679 content: content.into(),
2680 meta: None,
2681 }
2682 }
2683
2684 #[must_use]
2690 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2691 self.meta = meta.into_option();
2692 self
2693 }
2694}
2695
2696crate::serde_util::default_on_null! {
2697 #[serde_as]
2699 #[skip_serializing_none]
2700 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2701 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2702 #[serde(rename_all = "camelCase")]
2703 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = FS_WRITE_TEXT_FILE_METHOD_NAME)))]
2704 #[non_exhaustive]
2705 pub struct WriteTextFileResponse {
2706 #[serde_as(deserialize_as = "DefaultOnError")]
2712 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2713 #[serde(default)]
2714 #[serde(rename = "_meta")]
2715 pub meta: Option<Meta>,
2716 }
2717}
2718
2719impl WriteTextFileResponse {
2720 #[must_use]
2722 pub fn new() -> Self {
2723 Self::default()
2724 }
2725
2726 #[must_use]
2732 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2733 self.meta = meta.into_option();
2734 self
2735 }
2736}
2737
2738#[serde_as]
2744#[skip_serializing_none]
2745#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2746#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2747#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = FS_READ_TEXT_FILE_METHOD_NAME)))]
2748#[serde(rename_all = "camelCase")]
2749#[non_exhaustive]
2750pub struct ReadTextFileRequest {
2751 pub session_id: SessionId,
2753 pub path: PathBuf,
2755 #[serde(default)]
2757 pub line: Option<u32>,
2758 #[serde(default)]
2760 pub limit: Option<u32>,
2761 #[serde_as(deserialize_as = "DefaultOnError")]
2767 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2768 #[serde(default)]
2769 #[serde(rename = "_meta")]
2770 pub meta: Option<Meta>,
2771}
2772
2773impl ReadTextFileRequest {
2774 #[must_use]
2776 pub fn new(session_id: impl Into<SessionId>, path: impl Into<PathBuf>) -> Self {
2777 Self {
2778 session_id: session_id.into(),
2779 path: path.into(),
2780 line: None,
2781 limit: None,
2782 meta: None,
2783 }
2784 }
2785
2786 #[must_use]
2788 pub fn line(mut self, line: impl IntoOption<u32>) -> Self {
2789 self.line = line.into_option();
2790 self
2791 }
2792
2793 #[must_use]
2795 pub fn limit(mut self, limit: impl IntoOption<u32>) -> Self {
2796 self.limit = limit.into_option();
2797 self
2798 }
2799
2800 #[must_use]
2806 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2807 self.meta = meta.into_option();
2808 self
2809 }
2810}
2811
2812#[serde_as]
2814#[skip_serializing_none]
2815#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2816#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2817#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = FS_READ_TEXT_FILE_METHOD_NAME)))]
2818#[serde(rename_all = "camelCase")]
2819#[non_exhaustive]
2820pub struct ReadTextFileResponse {
2821 pub content: String,
2823 #[serde_as(deserialize_as = "DefaultOnError")]
2829 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2830 #[serde(default)]
2831 #[serde(rename = "_meta")]
2832 pub meta: Option<Meta>,
2833}
2834
2835impl ReadTextFileResponse {
2836 #[must_use]
2838 pub fn new(content: impl Into<String>) -> Self {
2839 Self {
2840 content: content.into(),
2841 meta: None,
2842 }
2843 }
2844
2845 #[must_use]
2851 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2852 self.meta = meta.into_option();
2853 self
2854 }
2855}
2856
2857#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2861#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
2862#[serde(transparent)]
2863#[from(Arc<str>, String, &'static str)]
2864#[non_exhaustive]
2865pub struct TerminalId(pub Arc<str>);
2866
2867impl TerminalId {
2868 #[must_use]
2870 pub fn new(id: impl Into<Arc<str>>) -> Self {
2871 Self(id.into())
2872 }
2873}
2874
2875#[serde_as]
2877#[skip_serializing_none]
2878#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2879#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2880#[serde(rename_all = "camelCase")]
2881#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = TERMINAL_CREATE_METHOD_NAME)))]
2882#[non_exhaustive]
2883pub struct CreateTerminalRequest {
2884 pub session_id: SessionId,
2886 pub command: String,
2888 #[serde_as(deserialize_as = "DefaultOnNull")]
2890 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
2891 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2892 pub args: Vec<String>,
2893 #[serde_as(deserialize_as = "DefaultOnNull")]
2895 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
2896 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2897 pub env: Vec<EnvVariable>,
2898 #[serde(default)]
2900 pub cwd: Option<PathBuf>,
2901 #[serde(default)]
2910 pub output_byte_limit: Option<u64>,
2911 #[serde_as(deserialize_as = "DefaultOnError")]
2917 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2918 #[serde(default)]
2919 #[serde(rename = "_meta")]
2920 pub meta: Option<Meta>,
2921}
2922
2923impl CreateTerminalRequest {
2924 #[must_use]
2926 pub fn new(session_id: impl Into<SessionId>, command: impl Into<String>) -> Self {
2927 Self {
2928 session_id: session_id.into(),
2929 command: command.into(),
2930 args: Vec::new(),
2931 env: Vec::new(),
2932 cwd: None,
2933 output_byte_limit: None,
2934 meta: None,
2935 }
2936 }
2937
2938 #[must_use]
2940 pub fn args(mut self, args: Vec<String>) -> Self {
2941 self.args = args;
2942 self
2943 }
2944
2945 #[must_use]
2947 pub fn env(mut self, env: Vec<EnvVariable>) -> Self {
2948 self.env = env;
2949 self
2950 }
2951
2952 #[must_use]
2954 pub fn cwd(mut self, cwd: impl IntoOption<PathBuf>) -> Self {
2955 self.cwd = cwd.into_option();
2956 self
2957 }
2958
2959 #[must_use]
2968 pub fn output_byte_limit(mut self, output_byte_limit: impl IntoOption<u64>) -> Self {
2969 self.output_byte_limit = output_byte_limit.into_option();
2970 self
2971 }
2972
2973 #[must_use]
2979 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2980 self.meta = meta.into_option();
2981 self
2982 }
2983}
2984
2985#[serde_as]
2987#[skip_serializing_none]
2988#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2989#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2990#[serde(rename_all = "camelCase")]
2991#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = TERMINAL_CREATE_METHOD_NAME)))]
2992#[non_exhaustive]
2993pub struct CreateTerminalResponse {
2994 pub terminal_id: TerminalId,
2996 #[serde_as(deserialize_as = "DefaultOnError")]
3002 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3003 #[serde(default)]
3004 #[serde(rename = "_meta")]
3005 pub meta: Option<Meta>,
3006}
3007
3008impl CreateTerminalResponse {
3009 #[must_use]
3011 pub fn new(terminal_id: impl Into<TerminalId>) -> Self {
3012 Self {
3013 terminal_id: terminal_id.into(),
3014 meta: None,
3015 }
3016 }
3017
3018 #[must_use]
3024 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3025 self.meta = meta.into_option();
3026 self
3027 }
3028}
3029
3030#[serde_as]
3032#[skip_serializing_none]
3033#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3034#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3035#[serde(rename_all = "camelCase")]
3036#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = TERMINAL_OUTPUT_METHOD_NAME)))]
3037#[non_exhaustive]
3038pub struct TerminalOutputRequest {
3039 pub session_id: SessionId,
3041 pub terminal_id: TerminalId,
3043 #[serde_as(deserialize_as = "DefaultOnError")]
3049 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3050 #[serde(default)]
3051 #[serde(rename = "_meta")]
3052 pub meta: Option<Meta>,
3053}
3054
3055impl TerminalOutputRequest {
3056 #[must_use]
3058 pub fn new(session_id: impl Into<SessionId>, terminal_id: impl Into<TerminalId>) -> Self {
3059 Self {
3060 session_id: session_id.into(),
3061 terminal_id: terminal_id.into(),
3062 meta: None,
3063 }
3064 }
3065
3066 #[must_use]
3072 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3073 self.meta = meta.into_option();
3074 self
3075 }
3076}
3077
3078#[serde_as]
3080#[skip_serializing_none]
3081#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3082#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3083#[serde(rename_all = "camelCase")]
3084#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = TERMINAL_OUTPUT_METHOD_NAME)))]
3085#[non_exhaustive]
3086pub struct TerminalOutputResponse {
3087 pub output: String,
3089 pub truncated: bool,
3091 #[serde_as(deserialize_as = "DefaultOnError")]
3093 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3094 #[serde(default)]
3095 pub exit_status: Option<TerminalExitStatus>,
3096 #[serde_as(deserialize_as = "DefaultOnError")]
3102 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3103 #[serde(default)]
3104 #[serde(rename = "_meta")]
3105 pub meta: Option<Meta>,
3106}
3107
3108impl TerminalOutputResponse {
3109 #[must_use]
3111 pub fn new(output: impl Into<String>, truncated: bool) -> Self {
3112 Self {
3113 output: output.into(),
3114 truncated,
3115 exit_status: None,
3116 meta: None,
3117 }
3118 }
3119
3120 #[must_use]
3122 pub fn exit_status(mut self, exit_status: impl IntoOption<TerminalExitStatus>) -> Self {
3123 self.exit_status = exit_status.into_option();
3124 self
3125 }
3126
3127 #[must_use]
3133 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3134 self.meta = meta.into_option();
3135 self
3136 }
3137}
3138
3139#[serde_as]
3141#[skip_serializing_none]
3142#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3143#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3144#[serde(rename_all = "camelCase")]
3145#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = TERMINAL_RELEASE_METHOD_NAME)))]
3146#[non_exhaustive]
3147pub struct ReleaseTerminalRequest {
3148 pub session_id: SessionId,
3150 pub terminal_id: TerminalId,
3152 #[serde_as(deserialize_as = "DefaultOnError")]
3158 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3159 #[serde(default)]
3160 #[serde(rename = "_meta")]
3161 pub meta: Option<Meta>,
3162}
3163
3164impl ReleaseTerminalRequest {
3165 #[must_use]
3167 pub fn new(session_id: impl Into<SessionId>, terminal_id: impl Into<TerminalId>) -> Self {
3168 Self {
3169 session_id: session_id.into(),
3170 terminal_id: terminal_id.into(),
3171 meta: None,
3172 }
3173 }
3174
3175 #[must_use]
3181 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3182 self.meta = meta.into_option();
3183 self
3184 }
3185}
3186
3187crate::serde_util::default_on_null! {
3188 #[serde_as]
3190 #[skip_serializing_none]
3191 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3192 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
3193 #[serde(rename_all = "camelCase")]
3194 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = TERMINAL_RELEASE_METHOD_NAME)))]
3195 #[non_exhaustive]
3196 pub struct ReleaseTerminalResponse {
3197 #[serde_as(deserialize_as = "DefaultOnError")]
3203 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3204 #[serde(default)]
3205 #[serde(rename = "_meta")]
3206 pub meta: Option<Meta>,
3207 }
3208}
3209
3210impl ReleaseTerminalResponse {
3211 #[must_use]
3213 pub fn new() -> Self {
3214 Self::default()
3215 }
3216
3217 #[must_use]
3223 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3224 self.meta = meta.into_option();
3225 self
3226 }
3227}
3228
3229#[serde_as]
3231#[skip_serializing_none]
3232#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3233#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3234#[serde(rename_all = "camelCase")]
3235#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = TERMINAL_KILL_METHOD_NAME)))]
3236#[non_exhaustive]
3237pub struct KillTerminalRequest {
3238 pub session_id: SessionId,
3240 pub terminal_id: TerminalId,
3242 #[serde_as(deserialize_as = "DefaultOnError")]
3248 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3249 #[serde(default)]
3250 #[serde(rename = "_meta")]
3251 pub meta: Option<Meta>,
3252}
3253
3254impl KillTerminalRequest {
3255 #[must_use]
3257 pub fn new(session_id: impl Into<SessionId>, terminal_id: impl Into<TerminalId>) -> Self {
3258 Self {
3259 session_id: session_id.into(),
3260 terminal_id: terminal_id.into(),
3261 meta: None,
3262 }
3263 }
3264
3265 #[must_use]
3271 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3272 self.meta = meta.into_option();
3273 self
3274 }
3275}
3276
3277crate::serde_util::default_on_null! {
3278 #[serde_as]
3280 #[skip_serializing_none]
3281 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3282 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
3283 #[serde(rename_all = "camelCase")]
3284 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = TERMINAL_KILL_METHOD_NAME)))]
3285 #[non_exhaustive]
3286 pub struct KillTerminalResponse {
3287 #[serde_as(deserialize_as = "DefaultOnError")]
3293 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3294 #[serde(default)]
3295 #[serde(rename = "_meta")]
3296 pub meta: Option<Meta>,
3297 }
3298}
3299
3300impl KillTerminalResponse {
3301 #[must_use]
3303 pub fn new() -> Self {
3304 Self::default()
3305 }
3306
3307 #[must_use]
3313 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3314 self.meta = meta.into_option();
3315 self
3316 }
3317}
3318
3319#[serde_as]
3321#[skip_serializing_none]
3322#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3323#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3324#[serde(rename_all = "camelCase")]
3325#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = TERMINAL_WAIT_FOR_EXIT_METHOD_NAME)))]
3326#[non_exhaustive]
3327pub struct WaitForTerminalExitRequest {
3328 pub session_id: SessionId,
3330 pub terminal_id: TerminalId,
3332 #[serde_as(deserialize_as = "DefaultOnError")]
3338 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3339 #[serde(default)]
3340 #[serde(rename = "_meta")]
3341 pub meta: Option<Meta>,
3342}
3343
3344impl WaitForTerminalExitRequest {
3345 #[must_use]
3347 pub fn new(session_id: impl Into<SessionId>, terminal_id: impl Into<TerminalId>) -> Self {
3348 Self {
3349 session_id: session_id.into(),
3350 terminal_id: terminal_id.into(),
3351 meta: None,
3352 }
3353 }
3354
3355 #[must_use]
3361 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3362 self.meta = meta.into_option();
3363 self
3364 }
3365}
3366
3367crate::serde_util::default_on_null! {
3368 #[serde_as]
3370 #[skip_serializing_none]
3371 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3372 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
3373 #[serde(rename_all = "camelCase")]
3374 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = TERMINAL_WAIT_FOR_EXIT_METHOD_NAME)))]
3375 #[non_exhaustive]
3376 pub struct WaitForTerminalExitResponse {
3377 #[serde(flatten)]
3379 pub exit_status: TerminalExitStatus,
3380 #[serde_as(deserialize_as = "DefaultOnError")]
3386 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3387 #[serde(default)]
3388 #[serde(rename = "_meta")]
3389 pub meta: Option<Meta>,
3390 }
3391}
3392
3393impl WaitForTerminalExitResponse {
3394 #[must_use]
3396 pub fn new(exit_status: TerminalExitStatus) -> Self {
3397 Self {
3398 exit_status,
3399 meta: None,
3400 }
3401 }
3402
3403 #[must_use]
3409 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3410 self.meta = meta.into_option();
3411 self
3412 }
3413}
3414
3415#[serde_as]
3417#[skip_serializing_none]
3418#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3419#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3420#[serde(rename_all = "camelCase")]
3421#[non_exhaustive]
3422pub struct TerminalExitStatus {
3423 #[serde_as(deserialize_as = "DefaultOnError")]
3425 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3426 #[serde(default)]
3427 pub exit_code: Option<u32>,
3428 #[serde_as(deserialize_as = "DefaultOnError")]
3430 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3431 #[serde(default)]
3432 pub signal: Option<String>,
3433 #[serde_as(deserialize_as = "DefaultOnError")]
3439 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3440 #[serde(default)]
3441 #[serde(rename = "_meta")]
3442 pub meta: Option<Meta>,
3443}
3444
3445impl TerminalExitStatus {
3446 #[must_use]
3448 pub fn new() -> Self {
3449 Self::default()
3450 }
3451
3452 #[must_use]
3454 pub fn exit_code(mut self, exit_code: impl IntoOption<u32>) -> Self {
3455 self.exit_code = exit_code.into_option();
3456 self
3457 }
3458
3459 #[must_use]
3461 pub fn signal(mut self, signal: impl IntoOption<String>) -> Self {
3462 self.signal = signal.into_option();
3463 self
3464 }
3465
3466 #[must_use]
3472 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3473 self.meta = meta.into_option();
3474 self
3475 }
3476}
3477
3478#[serde_as]
3487#[skip_serializing_none]
3488#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3489#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3490#[serde(rename_all = "camelCase")]
3491#[non_exhaustive]
3492pub struct ClientCapabilities {
3493 #[serde_as(deserialize_as = "DefaultOnError")]
3496 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3497 #[serde(default)]
3498 pub fs: FileSystemCapabilities,
3499 #[serde_as(deserialize_as = "DefaultOnError")]
3501 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3502 #[serde(default)]
3503 pub terminal: bool,
3504 #[serde_as(deserialize_as = "DefaultOnError")]
3509 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3510 #[serde(default)]
3511 pub session: Option<ClientSessionCapabilities>,
3512 #[cfg(feature = "unstable_subagents")]
3523 #[serde_as(deserialize_as = "DefaultOnError")]
3524 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3525 #[serde(default)]
3526 pub subagents: Option<SubagentCapabilities>,
3527 #[cfg(feature = "unstable_plan_operations")]
3536 #[serde_as(deserialize_as = "DefaultOnError")]
3537 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3538 #[serde(default)]
3539 pub plan: Option<PlanCapabilities>,
3540 #[serde_as(deserialize_as = "DefaultOnError")]
3544 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3545 #[serde(default)]
3546 pub auth: AuthCapabilities,
3547 #[serde_as(deserialize_as = "DefaultOnError")]
3553 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3554 #[serde(default)]
3555 pub elicitation: Option<ElicitationCapabilities>,
3556 #[serde_as(deserialize_as = "DefaultOnError")]
3562 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3563 #[serde(default)]
3564 #[serde(rename = "_meta")]
3565 pub meta: Option<Meta>,
3566}
3567
3568impl ClientCapabilities {
3569 #[must_use]
3571 pub fn new() -> Self {
3572 Self::default()
3573 }
3574
3575 #[must_use]
3578 pub fn fs(mut self, fs: FileSystemCapabilities) -> Self {
3579 self.fs = fs;
3580 self
3581 }
3582
3583 #[must_use]
3585 pub fn terminal(mut self, terminal: bool) -> Self {
3586 self.terminal = terminal;
3587 self
3588 }
3589
3590 #[must_use]
3592 pub fn session(mut self, session: impl IntoOption<ClientSessionCapabilities>) -> Self {
3593 self.session = session.into_option();
3594 self
3595 }
3596
3597 #[cfg(feature = "unstable_subagents")]
3603 #[must_use]
3604 pub fn subagents(mut self, subagents: impl IntoOption<SubagentCapabilities>) -> Self {
3605 self.subagents = subagents.into_option();
3606 self
3607 }
3608
3609 #[cfg(feature = "unstable_plan_operations")]
3618 #[must_use]
3619 pub fn plan(mut self, plan: impl IntoOption<PlanCapabilities>) -> Self {
3620 self.plan = plan.into_option();
3621 self
3622 }
3623
3624 #[must_use]
3628 pub fn auth(mut self, auth: AuthCapabilities) -> Self {
3629 self.auth = auth;
3630 self
3631 }
3632
3633 #[must_use]
3636 pub fn elicitation(mut self, elicitation: impl IntoOption<ElicitationCapabilities>) -> Self {
3637 self.elicitation = elicitation.into_option();
3638 self
3639 }
3640
3641 #[must_use]
3647 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3648 self.meta = meta.into_option();
3649 self
3650 }
3651}
3652
3653#[cfg(feature = "unstable_subagents")]
3664#[serde_as]
3665#[skip_serializing_none]
3666#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3667#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3668#[non_exhaustive]
3669pub struct SubagentCapabilities {
3670 #[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
3680#[cfg(feature = "unstable_subagents")]
3681impl SubagentCapabilities {
3682 #[must_use]
3684 pub fn new() -> Self {
3685 Self::default()
3686 }
3687
3688 #[must_use]
3692 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3693 self.meta = meta.into_option();
3694 self
3695 }
3696}
3697
3698#[serde_as]
3700#[skip_serializing_none]
3701#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3702#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3703#[serde(rename_all = "camelCase")]
3704#[non_exhaustive]
3705pub struct ClientSessionCapabilities {
3706 #[serde_as(deserialize_as = "DefaultOnError")]
3709 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3710 #[serde(default)]
3711 pub compaction: Option<CompactionCapabilities>,
3712 #[serde_as(deserialize_as = "DefaultOnError")]
3717 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3718 #[serde(default)]
3719 pub config_options: Option<SessionConfigOptionsCapabilities>,
3720 #[serde_as(deserialize_as = "DefaultOnError")]
3725 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3726 #[serde(default)]
3727 pub notices: Option<NoticeCapabilities>,
3728 #[cfg(feature = "unstable_prompt_suggestions")]
3738 #[serde_as(deserialize_as = "DefaultOnError")]
3739 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3740 #[serde(default)]
3741 pub prompt_suggestions: Option<PromptSuggestionsCapabilities>,
3742 #[serde_as(deserialize_as = "DefaultOnError")]
3748 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3749 #[serde(default)]
3750 #[serde(rename = "_meta")]
3751 pub meta: Option<Meta>,
3752}
3753
3754impl ClientSessionCapabilities {
3755 #[must_use]
3757 pub fn new() -> Self {
3758 Self::default()
3759 }
3760
3761 #[must_use]
3763 pub fn compaction(mut self, compaction: impl IntoOption<CompactionCapabilities>) -> Self {
3764 self.compaction = compaction.into_option();
3765 self
3766 }
3767
3768 #[must_use]
3773 pub fn config_options(
3774 mut self,
3775 config_options: impl IntoOption<SessionConfigOptionsCapabilities>,
3776 ) -> Self {
3777 self.config_options = config_options.into_option();
3778 self
3779 }
3780
3781 #[must_use]
3783 pub fn notices(mut self, notices: impl IntoOption<NoticeCapabilities>) -> Self {
3784 self.notices = notices.into_option();
3785 self
3786 }
3787
3788 #[cfg(feature = "unstable_prompt_suggestions")]
3794 #[must_use]
3795 pub fn prompt_suggestions(
3796 mut self,
3797 prompt_suggestions: impl IntoOption<PromptSuggestionsCapabilities>,
3798 ) -> Self {
3799 self.prompt_suggestions = prompt_suggestions.into_option();
3800 self
3801 }
3802
3803 #[must_use]
3809 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3810 self.meta = meta.into_option();
3811 self
3812 }
3813}
3814
3815#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3817#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3818#[serde(rename_all = "camelCase")]
3819#[non_exhaustive]
3820pub struct CompactionCapabilities {}
3821
3822impl CompactionCapabilities {
3823 #[must_use]
3825 pub fn new() -> Self {
3826 Self {}
3827 }
3828}
3829
3830#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3832#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3833#[serde(rename_all = "camelCase")]
3834#[non_exhaustive]
3835pub struct NoticeCapabilities {}
3836
3837impl NoticeCapabilities {
3838 #[must_use]
3840 pub fn new() -> Self {
3841 Self {}
3842 }
3843}
3844
3845#[cfg(feature = "unstable_prompt_suggestions")]
3856#[serde_as]
3857#[skip_serializing_none]
3858#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3859#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3860#[serde(rename_all = "camelCase")]
3861#[non_exhaustive]
3862pub struct PromptSuggestionsCapabilities {
3863 #[serde_as(deserialize_as = "DefaultOnError")]
3868 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3869 #[serde(default)]
3870 pub image: Option<PromptSuggestionsImageCapabilities>,
3871 #[serde_as(deserialize_as = "DefaultOnError")]
3876 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3877 #[serde(default)]
3878 pub audio: Option<PromptSuggestionsAudioCapabilities>,
3879 #[serde_as(deserialize_as = "DefaultOnError")]
3885 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3886 #[serde(default)]
3887 pub embedded_context: Option<PromptSuggestionsEmbeddedContextCapabilities>,
3888 #[serde_as(deserialize_as = "DefaultOnError")]
3894 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3895 #[serde(default)]
3896 #[serde(rename = "_meta")]
3897 pub meta: Option<Meta>,
3898}
3899
3900#[cfg(feature = "unstable_prompt_suggestions")]
3901impl PromptSuggestionsCapabilities {
3902 #[must_use]
3904 pub fn new() -> Self {
3905 Self::default()
3906 }
3907
3908 #[must_use]
3910 pub fn image(mut self, image: impl IntoOption<PromptSuggestionsImageCapabilities>) -> Self {
3911 self.image = image.into_option();
3912 self
3913 }
3914
3915 #[must_use]
3917 pub fn audio(mut self, audio: impl IntoOption<PromptSuggestionsAudioCapabilities>) -> Self {
3918 self.audio = audio.into_option();
3919 self
3920 }
3921
3922 #[must_use]
3924 pub fn embedded_context(
3925 mut self,
3926 embedded_context: impl IntoOption<PromptSuggestionsEmbeddedContextCapabilities>,
3927 ) -> Self {
3928 self.embedded_context = embedded_context.into_option();
3929 self
3930 }
3931
3932 #[must_use]
3938 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3939 self.meta = meta.into_option();
3940 self
3941 }
3942}
3943
3944#[cfg(feature = "unstable_prompt_suggestions")]
3952#[serde_as]
3953#[skip_serializing_none]
3954#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3955#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3956#[non_exhaustive]
3957pub struct PromptSuggestionsImageCapabilities {
3958 #[serde_as(deserialize_as = "DefaultOnError")]
3964 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3965 #[serde(default)]
3966 #[serde(rename = "_meta")]
3967 pub meta: Option<Meta>,
3968}
3969
3970#[cfg(feature = "unstable_prompt_suggestions")]
3971impl PromptSuggestionsImageCapabilities {
3972 #[must_use]
3974 pub fn new() -> Self {
3975 Self::default()
3976 }
3977
3978 #[must_use]
3984 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3985 self.meta = meta.into_option();
3986 self
3987 }
3988}
3989
3990#[cfg(feature = "unstable_prompt_suggestions")]
3998#[serde_as]
3999#[skip_serializing_none]
4000#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4001#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4002#[non_exhaustive]
4003pub struct PromptSuggestionsAudioCapabilities {
4004 #[serde_as(deserialize_as = "DefaultOnError")]
4010 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4011 #[serde(default)]
4012 #[serde(rename = "_meta")]
4013 pub meta: Option<Meta>,
4014}
4015
4016#[cfg(feature = "unstable_prompt_suggestions")]
4017impl PromptSuggestionsAudioCapabilities {
4018 #[must_use]
4020 pub fn new() -> Self {
4021 Self::default()
4022 }
4023
4024 #[must_use]
4030 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4031 self.meta = meta.into_option();
4032 self
4033 }
4034}
4035
4036#[cfg(feature = "unstable_prompt_suggestions")]
4045#[serde_as]
4046#[skip_serializing_none]
4047#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4048#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4049#[non_exhaustive]
4050pub struct PromptSuggestionsEmbeddedContextCapabilities {
4051 #[serde_as(deserialize_as = "DefaultOnError")]
4057 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4058 #[serde(default)]
4059 #[serde(rename = "_meta")]
4060 pub meta: Option<Meta>,
4061}
4062
4063#[cfg(feature = "unstable_prompt_suggestions")]
4064impl PromptSuggestionsEmbeddedContextCapabilities {
4065 #[must_use]
4067 pub fn new() -> Self {
4068 Self::default()
4069 }
4070
4071 #[must_use]
4077 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4078 self.meta = meta.into_option();
4079 self
4080 }
4081}
4082
4083#[serde_as]
4085#[skip_serializing_none]
4086#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4087#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4088#[serde(rename_all = "camelCase")]
4089#[non_exhaustive]
4090pub struct SessionConfigOptionsCapabilities {
4091 #[serde_as(deserialize_as = "DefaultOnError")]
4098 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4099 #[serde(default)]
4100 pub boolean: Option<BooleanConfigOptionCapabilities>,
4101 #[serde_as(deserialize_as = "DefaultOnError")]
4107 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4108 #[serde(default)]
4109 #[serde(rename = "_meta")]
4110 pub meta: Option<Meta>,
4111}
4112
4113impl SessionConfigOptionsCapabilities {
4114 #[must_use]
4116 pub fn new() -> Self {
4117 Self::default()
4118 }
4119
4120 #[must_use]
4127 pub fn boolean(mut self, boolean: impl IntoOption<BooleanConfigOptionCapabilities>) -> Self {
4128 self.boolean = boolean.into_option();
4129 self
4130 }
4131
4132 #[must_use]
4138 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4139 self.meta = meta.into_option();
4140 self
4141 }
4142}
4143
4144#[serde_as]
4148#[skip_serializing_none]
4149#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4150#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4151#[non_exhaustive]
4152pub struct BooleanConfigOptionCapabilities {
4153 #[serde_as(deserialize_as = "DefaultOnError")]
4159 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4160 #[serde(default)]
4161 #[serde(rename = "_meta")]
4162 pub meta: Option<Meta>,
4163}
4164
4165impl BooleanConfigOptionCapabilities {
4166 #[must_use]
4168 pub fn new() -> Self {
4169 Self::default()
4170 }
4171
4172 #[must_use]
4178 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4179 self.meta = meta.into_option();
4180 self
4181 }
4182}
4183
4184#[serde_as]
4190#[skip_serializing_none]
4191#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4192#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4193#[serde(rename_all = "camelCase")]
4194#[non_exhaustive]
4195pub struct AuthCapabilities {
4196 #[serde_as(deserialize_as = "DefaultOnError")]
4202 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4203 #[serde(default)]
4204 pub terminal: bool,
4205 #[serde_as(deserialize_as = "DefaultOnError")]
4211 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4212 #[serde(default)]
4213 #[serde(rename = "_meta")]
4214 pub meta: Option<Meta>,
4215}
4216
4217impl AuthCapabilities {
4218 #[must_use]
4220 pub fn new() -> Self {
4221 Self::default()
4222 }
4223
4224 #[must_use]
4231 pub fn terminal(mut self, terminal: bool) -> Self {
4232 self.terminal = terminal;
4233 self
4234 }
4235
4236 #[must_use]
4242 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4243 self.meta = meta.into_option();
4244 self
4245 }
4246}
4247
4248#[serde_as]
4252#[skip_serializing_none]
4253#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4254#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4255#[serde(rename_all = "camelCase")]
4256#[non_exhaustive]
4257pub struct FileSystemCapabilities {
4258 #[serde_as(deserialize_as = "DefaultOnError")]
4260 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4261 #[serde(default)]
4262 pub read_text_file: bool,
4263 #[serde_as(deserialize_as = "DefaultOnError")]
4265 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4266 #[serde(default)]
4267 pub write_text_file: bool,
4268 #[serde_as(deserialize_as = "DefaultOnError")]
4274 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4275 #[serde(default)]
4276 #[serde(rename = "_meta")]
4277 pub meta: Option<Meta>,
4278}
4279
4280impl FileSystemCapabilities {
4281 #[must_use]
4283 pub fn new() -> Self {
4284 Self::default()
4285 }
4286
4287 #[must_use]
4289 pub fn read_text_file(mut self, read_text_file: bool) -> Self {
4290 self.read_text_file = read_text_file;
4291 self
4292 }
4293
4294 #[must_use]
4296 pub fn write_text_file(mut self, write_text_file: bool) -> Self {
4297 self.write_text_file = write_text_file;
4298 self
4299 }
4300
4301 #[must_use]
4307 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4308 self.meta = meta.into_option();
4309 self
4310 }
4311}
4312
4313#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4319#[non_exhaustive]
4320pub struct ClientMethodNames {
4321 pub session_request_permission: &'static str,
4323 pub session_update: &'static str,
4325 pub fs_write_text_file: &'static str,
4327 pub fs_read_text_file: &'static str,
4329 pub terminal_create: &'static str,
4331 pub terminal_output: &'static str,
4333 pub terminal_release: &'static str,
4335 pub terminal_wait_for_exit: &'static str,
4337 pub terminal_kill: &'static str,
4339 #[cfg(feature = "unstable_mcp_over_acp")]
4341 pub mcp_message: &'static str,
4342 pub elicitation_create: &'static str,
4344 pub elicitation_complete: &'static str,
4346 #[cfg(feature = "unstable_auth_status")]
4348 pub auth_status_update: &'static str,
4349}
4350
4351pub const CLIENT_METHOD_NAMES: ClientMethodNames = ClientMethodNames {
4353 session_update: SESSION_UPDATE_NOTIFICATION,
4354 session_request_permission: SESSION_REQUEST_PERMISSION_METHOD_NAME,
4355 fs_write_text_file: FS_WRITE_TEXT_FILE_METHOD_NAME,
4356 fs_read_text_file: FS_READ_TEXT_FILE_METHOD_NAME,
4357 terminal_create: TERMINAL_CREATE_METHOD_NAME,
4358 terminal_output: TERMINAL_OUTPUT_METHOD_NAME,
4359 terminal_release: TERMINAL_RELEASE_METHOD_NAME,
4360 terminal_wait_for_exit: TERMINAL_WAIT_FOR_EXIT_METHOD_NAME,
4361 terminal_kill: TERMINAL_KILL_METHOD_NAME,
4362 #[cfg(feature = "unstable_mcp_over_acp")]
4363 mcp_message: MCP_MESSAGE_METHOD_NAME,
4364 elicitation_create: ELICITATION_CREATE_METHOD_NAME,
4365 elicitation_complete: ELICITATION_COMPLETE_NOTIFICATION,
4366 #[cfg(feature = "unstable_auth_status")]
4367 auth_status_update: AUTH_STATUS_UPDATE_NOTIFICATION,
4368};
4369
4370pub(crate) const SESSION_UPDATE_NOTIFICATION: &str = "session/update";
4372pub(crate) const SESSION_REQUEST_PERMISSION_METHOD_NAME: &str = "session/request_permission";
4374pub(crate) const FS_WRITE_TEXT_FILE_METHOD_NAME: &str = "fs/write_text_file";
4376pub(crate) const FS_READ_TEXT_FILE_METHOD_NAME: &str = "fs/read_text_file";
4378pub(crate) const TERMINAL_CREATE_METHOD_NAME: &str = "terminal/create";
4380pub(crate) const TERMINAL_OUTPUT_METHOD_NAME: &str = "terminal/output";
4382pub(crate) const TERMINAL_RELEASE_METHOD_NAME: &str = "terminal/release";
4384pub(crate) const TERMINAL_WAIT_FOR_EXIT_METHOD_NAME: &str = "terminal/wait_for_exit";
4386pub(crate) const TERMINAL_KILL_METHOD_NAME: &str = "terminal/kill";
4388pub(crate) const ELICITATION_CREATE_METHOD_NAME: &str = "elicitation/create";
4390pub(crate) const ELICITATION_COMPLETE_NOTIFICATION: &str = "elicitation/complete";
4392#[cfg(feature = "unstable_auth_status")]
4394pub(crate) const AUTH_STATUS_UPDATE_NOTIFICATION: &str = "auth/status_update";
4395
4396#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4403#[derive(Clone, Debug, Serialize, Deserialize)]
4404#[serde(untagged)]
4405#[cfg_attr(feature = "schemars", schemars(inline))]
4406#[non_exhaustive]
4407#[allow(clippy::large_enum_variant)]
4408pub enum AgentRequest {
4409 WriteTextFileRequest(WriteTextFileRequest),
4416 ReadTextFileRequest(ReadTextFileRequest),
4423 RequestPermissionRequest(RequestPermissionRequest),
4434 CreateTerminalRequest(CreateTerminalRequest),
4449 TerminalOutputRequest(TerminalOutputRequest),
4456 ReleaseTerminalRequest(ReleaseTerminalRequest),
4469 WaitForTerminalExitRequest(WaitForTerminalExitRequest),
4473 KillTerminalRequest(KillTerminalRequest),
4486 CreateElicitationRequest(CreateElicitationRequest),
4490 #[cfg(feature = "unstable_mcp_over_acp")]
4496 MessageMcpRequest(MessageMcpRequest),
4497 ExtMethodRequest(ExtRequest),
4505}
4506
4507impl AgentRequest {
4508 #[must_use]
4510 pub fn method(&self) -> &str {
4511 match self {
4512 Self::WriteTextFileRequest(_) => CLIENT_METHOD_NAMES.fs_write_text_file,
4513 Self::ReadTextFileRequest(_) => CLIENT_METHOD_NAMES.fs_read_text_file,
4514 Self::RequestPermissionRequest(_) => CLIENT_METHOD_NAMES.session_request_permission,
4515 Self::CreateTerminalRequest(_) => CLIENT_METHOD_NAMES.terminal_create,
4516 Self::TerminalOutputRequest(_) => CLIENT_METHOD_NAMES.terminal_output,
4517 Self::ReleaseTerminalRequest(_) => CLIENT_METHOD_NAMES.terminal_release,
4518 Self::WaitForTerminalExitRequest(_) => CLIENT_METHOD_NAMES.terminal_wait_for_exit,
4519 Self::KillTerminalRequest(_) => CLIENT_METHOD_NAMES.terminal_kill,
4520 Self::CreateElicitationRequest(_) => CLIENT_METHOD_NAMES.elicitation_create,
4521 #[cfg(feature = "unstable_mcp_over_acp")]
4522 Self::MessageMcpRequest(_) => CLIENT_METHOD_NAMES.mcp_message,
4523 Self::ExtMethodRequest(ext_request) => &ext_request.method,
4524 }
4525 }
4526}
4527
4528#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4535#[derive(Clone, Debug, Serialize, Deserialize)]
4536#[serde(untagged)]
4537#[cfg_attr(feature = "schemars", schemars(inline))]
4538#[non_exhaustive]
4539pub enum ClientResponse {
4540 WriteTextFileResponse(#[serde(default)] WriteTextFileResponse),
4542 ReadTextFileResponse(ReadTextFileResponse),
4544 RequestPermissionResponse(RequestPermissionResponse),
4546 CreateTerminalResponse(CreateTerminalResponse),
4548 TerminalOutputResponse(TerminalOutputResponse),
4550 ReleaseTerminalResponse(#[serde(default)] ReleaseTerminalResponse),
4552 WaitForTerminalExitResponse(WaitForTerminalExitResponse),
4554 KillTerminalResponse(#[serde(default)] KillTerminalResponse),
4556 CreateElicitationResponse(CreateElicitationResponse),
4558 #[cfg(feature = "unstable_mcp_over_acp")]
4560 MessageMcpResponse(MessageMcpResponse),
4561 ExtMethodResponse(ExtResponse),
4563}
4564
4565#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4572#[derive(Clone, Debug, Serialize, Deserialize)]
4573#[serde(untagged)]
4574#[expect(clippy::large_enum_variant)]
4575#[cfg_attr(feature = "schemars", schemars(inline))]
4576#[non_exhaustive]
4577pub enum AgentNotification {
4578 SessionNotification(SessionNotification),
4590 CompleteElicitationNotification(CompleteElicitationNotification),
4594 #[cfg(feature = "unstable_auth_status")]
4602 AuthStatusUpdateNotification(AuthStatusUpdateNotification),
4603 ExtNotification(ExtNotification),
4611}
4612
4613impl AgentNotification {
4614 #[must_use]
4616 pub fn method(&self) -> &str {
4617 match self {
4618 Self::SessionNotification(_) => CLIENT_METHOD_NAMES.session_update,
4619 Self::CompleteElicitationNotification(_) => CLIENT_METHOD_NAMES.elicitation_complete,
4620 #[cfg(feature = "unstable_auth_status")]
4621 Self::AuthStatusUpdateNotification(_) => CLIENT_METHOD_NAMES.auth_status_update,
4622 Self::ExtNotification(ext_notification) => &ext_notification.method,
4623 }
4624 }
4625}
4626
4627#[cfg(test)]
4628mod tests {
4629 use super::*;
4630
4631 #[test]
4632 fn notice_preserves_wire_shape_nullable_fields_and_open_severity() {
4633 use serde_json::json;
4634
4635 let mut meta = Meta::new();
4636 meta.insert("source".into(), json!("fallback"));
4637 assert_eq!(
4638 serde_json::to_value(SessionUpdate::Notice(
4639 Notice::new(NoticeSeverity::Warning, "MCP server unavailable")
4640 .description("Continuing without it.")
4641 .meta(meta),
4642 ))
4643 .unwrap(),
4644 json!({
4645 "sessionUpdate": "notice",
4646 "severity": "warning",
4647 "title": "MCP server unavailable",
4648 "description": "Continuing without it.",
4649 "_meta": { "source": "fallback" }
4650 })
4651 );
4652
4653 assert_eq!(
4654 serde_json::to_value(SessionUpdate::Notice(Notice::new(
4655 NoticeSeverity::Info,
4656 "Indexing workspace",
4657 )))
4658 .unwrap(),
4659 json!({
4660 "sessionUpdate": "notice",
4661 "severity": "info",
4662 "title": "Indexing workspace"
4663 })
4664 );
4665
4666 let SessionUpdate::Notice(notice) = serde_json::from_value(json!({
4667 "sessionUpdate": "notice",
4668 "severity": "critical",
4669 "title": "Provider degraded",
4670 "description": null,
4671 "_meta": null
4672 }))
4673 .unwrap() else {
4674 panic!("expected notice");
4675 };
4676
4677 assert_eq!(
4678 notice.severity,
4679 NoticeSeverity::Other("critical".to_string())
4680 );
4681 assert_eq!(notice.description, None);
4682 assert_eq!(notice.meta, None);
4683 assert_eq!(
4684 serde_json::to_value(SessionUpdate::Notice(notice)).unwrap(),
4685 json!({
4686 "sessionUpdate": "notice",
4687 "severity": "critical",
4688 "title": "Provider degraded"
4689 })
4690 );
4691 }
4692
4693 #[test]
4694 fn notice_requires_string_severity_and_title() {
4695 use serde_json::json;
4696
4697 for malformed in [
4698 json!({
4699 "sessionUpdate": "notice",
4700 "severity": "warning",
4701 "title": 42
4702 }),
4703 json!({
4704 "sessionUpdate": "notice",
4705 "severity": 42,
4706 "title": "MCP server unavailable"
4707 }),
4708 json!({
4709 "sessionUpdate": "notice",
4710 "severity": "warning"
4711 }),
4712 json!({
4713 "sessionUpdate": "notice",
4714 "severity": "warning",
4715 "title": null
4716 }),
4717 json!({
4718 "sessionUpdate": "notice",
4719 "title": "MCP server unavailable"
4720 }),
4721 json!({
4722 "sessionUpdate": "notice",
4723 "severity": null,
4724 "title": "MCP server unavailable"
4725 }),
4726 ] {
4727 assert!(serde_json::from_str::<SessionUpdate>(&malformed.to_string()).is_err());
4728 assert!(serde_json::from_value::<SessionUpdate>(malformed).is_err());
4729 }
4730 }
4731
4732 #[test]
4733 fn notice_tolerates_invalid_optional_display_fields_and_custom_severity() {
4734 use serde_json::json;
4735
4736 let wire = json!({
4737 "sessionUpdate": "notice",
4738 "severity": "_custom",
4739 "title": "Provider degraded",
4740 "description": 42,
4741 "_meta": false
4742 });
4743 let SessionUpdate::Notice(notice) = serde_json::from_value(wire.clone()).unwrap() else {
4744 panic!("expected notice");
4745 };
4746 assert_eq!(
4748 serde_json::from_str::<SessionUpdate>(&wire.to_string()).unwrap(),
4749 SessionUpdate::Notice(notice.clone())
4750 );
4751 assert_eq!(notice.severity, NoticeSeverity::Other("_custom".into()));
4752 assert_eq!(notice.description, None);
4753 assert_eq!(notice.meta, None);
4754 assert_eq!(
4755 serde_json::to_value(notice).unwrap(),
4756 json!({"severity": "_custom", "title": "Provider degraded"})
4757 );
4758 }
4759
4760 #[cfg(feature = "schemars")]
4761 #[test]
4762 fn notice_schema_preserves_required_and_nullable_fields() {
4763 use serde_json::json;
4764
4765 let schema = serde_json::to_value(schemars::schema_for!(Notice)).unwrap();
4766 assert_eq!(schema["required"], json!(["severity", "title"]));
4767 assert_eq!(schema["properties"]["title"]["minLength"], 1);
4768 for field in ["description", "_meta"] {
4769 assert!(
4770 schema["properties"][field]["type"]
4771 .as_array()
4772 .unwrap()
4773 .contains(&json!("null"))
4774 );
4775 }
4776 let capabilities =
4777 serde_json::to_value(schemars::schema_for!(ClientSessionCapabilities)).unwrap();
4778 assert!(
4779 capabilities["properties"]["notices"]["anyOf"]
4780 .as_array()
4781 .unwrap()
4782 .contains(&json!({"type": "null"}))
4783 );
4784 assert!(
4785 !capabilities["required"]
4786 .as_array()
4787 .is_some_and(|required| required.contains(&json!("notices")))
4788 );
4789 }
4790
4791 #[test]
4792 fn notice_capability_advertises_support_only_when_present() {
4793 use serde_json::json;
4794
4795 let capabilities = ClientCapabilities::new()
4796 .session(ClientSessionCapabilities::new().notices(NoticeCapabilities::new()));
4797 let value = serde_json::to_value(&capabilities).unwrap();
4798 assert_eq!(value["session"], json!({ "notices": {} }));
4799 assert_eq!(
4800 serde_json::from_value::<ClientCapabilities>(value).unwrap(),
4801 capabilities
4802 );
4803
4804 for unsupported in [
4805 json!({}),
4806 json!({ "session": null }),
4807 json!({ "session": {} }),
4808 json!({ "session": { "notices": null } }),
4809 json!({ "session": { "notices": false } }),
4810 json!({ "session": { "notices": true } }),
4811 json!({ "session": { "notices": "supported" } }),
4812 ] {
4813 let capabilities: ClientCapabilities = serde_json::from_value(unsupported).unwrap();
4814 assert!(
4815 capabilities
4816 .session
4817 .and_then(|session| session.notices)
4818 .is_none()
4819 );
4820 }
4821
4822 assert_eq!(
4823 serde_json::to_value(
4824 ClientSessionCapabilities::new()
4825 .notices(NoticeCapabilities::new())
4826 .notices(None)
4827 )
4828 .unwrap(),
4829 json!({})
4830 );
4831 }
4832
4833 #[cfg(feature = "unstable_prompt_suggestions")]
4834 #[test]
4835 fn prompt_suggestions_update_round_trips_prompt_content_and_meta() {
4836 use crate::v1::{ResourceLink, TextContent};
4837 use serde_json::json;
4838
4839 let mut meta = Meta::new();
4840 meta.insert("rank".into(), json!(1));
4841 let update = SessionUpdate::PromptSuggestionsUpdate(PromptSuggestionsUpdate::new(vec![
4842 PromptSuggestion::new(vec![ContentBlock::Text(TextContent::new(
4843 "Run the test suite and fix what breaks",
4844 ))])
4845 .meta(meta),
4846 PromptSuggestion::new(vec![
4847 ContentBlock::Text(TextContent::new("Add tests for ")),
4848 ContentBlock::ResourceLink(ResourceLink::new(
4849 "parser.rs",
4850 "file:///home/user/project/src/parser.rs",
4851 )),
4852 ]),
4853 ]));
4854 let wire = json!({
4855 "sessionUpdate": "prompt_suggestions_update",
4856 "suggestions": [
4857 {
4858 "prompt": [
4859 { "type": "text", "text": "Run the test suite and fix what breaks" }
4860 ],
4861 "_meta": { "rank": 1 }
4862 },
4863 {
4864 "prompt": [
4865 { "type": "text", "text": "Add tests for " },
4866 {
4867 "type": "resource_link",
4868 "name": "parser.rs",
4869 "uri": "file:///home/user/project/src/parser.rs"
4870 }
4871 ]
4872 }
4873 ]
4874 });
4875 assert_eq!(serde_json::to_value(&update).unwrap(), wire);
4876 assert_eq!(
4877 serde_json::from_value::<SessionUpdate>(wire).unwrap(),
4878 update
4879 );
4880 }
4881
4882 #[cfg(feature = "unstable_prompt_suggestions")]
4883 #[test]
4884 fn prompt_suggestions_update_with_an_empty_list_withdraws_suggestions() {
4885 use serde_json::json;
4886
4887 let update = SessionUpdate::PromptSuggestionsUpdate(PromptSuggestionsUpdate::new(vec![]));
4888 let wire = json!({
4889 "sessionUpdate": "prompt_suggestions_update",
4890 "suggestions": []
4891 });
4892 assert_eq!(serde_json::to_value(&update).unwrap(), wire);
4893 assert_eq!(
4894 serde_json::from_value::<SessionUpdate>(wire).unwrap(),
4895 update
4896 );
4897
4898 for malformed in [json!(null), json!("none"), json!({ "prompt": [] })] {
4900 assert!(
4901 serde_json::from_value::<SessionUpdate>(json!({
4902 "sessionUpdate": "prompt_suggestions_update",
4903 "suggestions": malformed
4904 }))
4905 .is_err()
4906 );
4907 }
4908 assert!(
4909 serde_json::from_value::<SessionUpdate>(json!({
4910 "sessionUpdate": "prompt_suggestions_update"
4911 }))
4912 .is_err()
4913 );
4914 }
4915
4916 #[cfg(feature = "unstable_prompt_suggestions")]
4917 #[test]
4918 fn prompt_suggestions_update_skips_whole_suggestions_it_cannot_parse() {
4919 use crate::v1::TextContent;
4920 use serde_json::json;
4921
4922 let text =
4923 |text: &str| PromptSuggestion::new(vec![ContentBlock::Text(TextContent::new(text))]);
4924
4925 let update: SessionUpdate = serde_json::from_value(json!({
4928 "sessionUpdate": "prompt_suggestions_update",
4929 "suggestions": [
4930 { "prompt": [{ "type": "text", "text": "Keep the first" }] },
4931 { "text": "A suggestion without a prompt" },
4932 { "prompt": "Not a list" },
4933 { "prompt": [{ "type": "text", "text": "Open " }, { "type": "text" }] },
4934 { "prompt": [{ "type": "hologram", "data": "AAAA" }] },
4935 "not an object",
4936 { "prompt": [{ "type": "text", "text": "Keep the last" }], "_meta": false }
4937 ]
4938 }))
4939 .unwrap();
4940
4941 assert_eq!(
4942 update,
4943 SessionUpdate::PromptSuggestionsUpdate(PromptSuggestionsUpdate::new(vec![
4944 text("Keep the first"),
4945 text("Keep the last"),
4946 ]))
4947 );
4948 }
4949
4950 #[cfg(feature = "unstable_prompt_suggestions")]
4951 #[test]
4952 fn prompt_suggestions_capability_advertises_support_and_content_types() {
4953 use serde_json::json;
4954
4955 let capabilities = ClientCapabilities::new().session(
4956 ClientSessionCapabilities::new()
4957 .prompt_suggestions(PromptSuggestionsCapabilities::new()),
4958 );
4959 let value = serde_json::to_value(&capabilities).unwrap();
4960 assert_eq!(value["session"], json!({ "promptSuggestions": {} }));
4961 assert_eq!(
4962 serde_json::from_value::<ClientCapabilities>(value).unwrap(),
4963 capabilities
4964 );
4965
4966 let content_types = PromptSuggestionsCapabilities::new()
4967 .image(PromptSuggestionsImageCapabilities::new())
4968 .audio(PromptSuggestionsAudioCapabilities::new())
4969 .embedded_context(PromptSuggestionsEmbeddedContextCapabilities::new());
4970 let wire = json!({ "image": {}, "audio": {}, "embeddedContext": {} });
4971 assert_eq!(serde_json::to_value(&content_types).unwrap(), wire);
4972 assert_eq!(
4973 serde_json::from_value::<PromptSuggestionsCapabilities>(wire).unwrap(),
4974 content_types
4975 );
4976
4977 for unsupported in [
4978 json!({}),
4979 json!({ "session": null }),
4980 json!({ "session": {} }),
4981 json!({ "session": { "promptSuggestions": null } }),
4982 json!({ "session": { "promptSuggestions": false } }),
4983 json!({ "session": { "promptSuggestions": true } }),
4984 json!({ "session": { "promptSuggestions": "supported" } }),
4985 ] {
4986 let capabilities: ClientCapabilities = serde_json::from_value(unsupported).unwrap();
4987 assert!(
4988 capabilities
4989 .session
4990 .and_then(|session| session.prompt_suggestions)
4991 .is_none()
4992 );
4993 }
4994
4995 assert_eq!(
4998 serde_json::from_value::<PromptSuggestionsCapabilities>(json!({
4999 "image": true,
5000 "audio": null,
5001 "embeddedContext": {}
5002 }))
5003 .unwrap(),
5004 PromptSuggestionsCapabilities::new()
5005 .embedded_context(PromptSuggestionsEmbeddedContextCapabilities::new())
5006 );
5007 }
5008
5009 #[cfg(all(feature = "schemars", feature = "unstable_prompt_suggestions"))]
5010 #[test]
5011 fn prompt_suggestions_schema_requires_the_list_and_a_non_empty_prompt() {
5012 use serde_json::json;
5013
5014 let update = serde_json::to_value(schemars::schema_for!(PromptSuggestionsUpdate)).unwrap();
5015 assert_eq!(update["required"], json!(["suggestions"]));
5016 assert_eq!(update["properties"]["suggestions"]["type"], "array");
5017
5018 let suggestion = serde_json::to_value(schemars::schema_for!(PromptSuggestion)).unwrap();
5019 assert_eq!(suggestion["required"], json!(["prompt"]));
5020 assert_eq!(suggestion["properties"]["prompt"]["type"], "array");
5021 assert_eq!(suggestion["properties"]["prompt"]["minItems"], 1);
5022
5023 let capabilities =
5024 serde_json::to_value(schemars::schema_for!(ClientSessionCapabilities)).unwrap();
5025 assert!(
5026 capabilities["properties"]["promptSuggestions"]["anyOf"]
5027 .as_array()
5028 .unwrap()
5029 .contains(&json!({"type": "null"}))
5030 );
5031 assert!(
5032 !capabilities["required"]
5033 .as_array()
5034 .is_some_and(|required| required.contains(&json!("promptSuggestions")))
5035 );
5036
5037 let content_types =
5038 serde_json::to_value(schemars::schema_for!(PromptSuggestionsCapabilities)).unwrap();
5039 assert!(content_types.get("required").is_none());
5040 for field in ["image", "audio", "embeddedContext"] {
5041 assert!(
5042 content_types["properties"][field]["anyOf"]
5043 .as_array()
5044 .unwrap()
5045 .contains(&json!({"type": "null"}))
5046 );
5047 }
5048 }
5049
5050 #[test]
5051 fn compaction_updates_preserve_patch_and_open_status_semantics() {
5052 use serde_json::json;
5053
5054 assert_eq!(
5055 serde_json::to_value(SessionUpdate::CompactionUpdate(CompactionUpdate::new(
5056 "cmp_001",
5057 CompactionStatus::InProgress,
5058 )))
5059 .unwrap(),
5060 json!({
5061 "sessionUpdate": "compaction_update",
5062 "compactionId": "cmp_001",
5063 "status": "in_progress"
5064 })
5065 );
5066
5067 let SessionUpdate::CompactionUpdate(update) = serde_json::from_value(json!({
5068 "sessionUpdate": "compaction_update",
5069 "compactionId": "cmp_001",
5070 "status": "paused",
5071 "summary": null,
5072 "error": null
5073 }))
5074 .unwrap() else {
5075 panic!("expected compaction update");
5076 };
5077 assert_eq!(update.status, CompactionStatus::Other("paused".into()));
5078 assert!(update.summary.is_null());
5079 assert!(update.error.is_null());
5080 assert!(update.meta.is_undefined());
5081 }
5082
5083 #[test]
5084 fn compaction_chunk_and_v1_capability_serialize() {
5085 use serde_json::json;
5086
5087 assert_eq!(
5088 serde_json::to_value(SessionUpdate::CompactionSummaryChunk(
5089 CompactionSummaryChunk::new(
5090 "cmp_001",
5091 ContentBlock::Text(crate::v1::TextContent::new("retained")),
5092 ),
5093 ))
5094 .unwrap(),
5095 json!({
5096 "sessionUpdate": "compaction_summary_chunk",
5097 "compactionId": "cmp_001",
5098 "content": { "type": "text", "text": "retained" }
5099 })
5100 );
5101 assert_eq!(
5102 serde_json::to_value(
5103 ClientSessionCapabilities::new().compaction(CompactionCapabilities::new())
5104 )
5105 .unwrap(),
5106 json!({ "compaction": {} })
5107 );
5108 let absent: ClientSessionCapabilities = serde_json::from_value(json!({})).unwrap();
5109 let null: ClientSessionCapabilities =
5110 serde_json::from_value(json!({ "compaction": null })).unwrap();
5111 assert!(absent.compaction.is_none());
5112 assert!(null.compaction.is_none());
5113 }
5114
5115 #[cfg(feature = "unstable_subagents")]
5116 #[test]
5117 fn test_subagent_updates_serialization() {
5118 use serde_json::json;
5119
5120 let announced = SessionUpdate::SubagentUpdate(SubagentUpdate::new("sess_child_1"));
5121 assert_eq!(
5122 serde_json::to_value(&announced).unwrap(),
5123 json!({
5124 "sessionUpdate": "subagent_update",
5125 "sessionId": "sess_child_1"
5126 })
5127 );
5128 assert_eq!(
5129 serde_json::from_value::<SessionUpdate>(serde_json::to_value(&announced).unwrap())
5130 .unwrap(),
5131 announced
5132 );
5133 let capable = SubagentUpdate::new("sess_child_1").capabilities(
5134 SubagentSessionCapabilities::new().cancel(SessionCancelCapabilities::new()),
5135 );
5136 assert_eq!(
5137 serde_json::to_value(capable).unwrap(),
5138 json!({
5139 "sessionId": "sess_child_1",
5140 "capabilities": {"cancel": {}}
5141 })
5142 );
5143 let minimal: SubagentUpdate =
5144 serde_json::from_value(json!({ "sessionId": "sess_child_3" })).unwrap();
5145 assert!(minimal.capabilities.is_undefined());
5146 assert!(minimal.state.is_undefined());
5147
5148 let nulls: SubagentUpdate = serde_json::from_value(json!({
5149 "sessionId": "sess_child_3",
5150 "capabilities": null,
5151 "state": null
5152 }))
5153 .unwrap();
5154 assert!(nulls.capabilities.is_null());
5155 assert!(nulls.state.is_null());
5156 assert_eq!(
5157 serde_json::to_value(nulls).unwrap(),
5158 json!({"sessionId": "sess_child_3", "capabilities": null, "state": null})
5159 );
5160 }
5161
5162 #[cfg(feature = "unstable_subagents")]
5163 #[test]
5164 fn test_subagent_display_metadata() {
5165 use serde_json::json;
5166
5167 let update = SubagentUpdate::new("child")
5168 .title("Test investigator".to_string())
5169 .description("Investigates platform-specific test failures.".to_string());
5170 let wire = json!({
5171 "sessionId": "child",
5172 "title": "Test investigator",
5173 "description": "Investigates platform-specific test failures."
5174 });
5175 assert_eq!(serde_json::to_value(&update).unwrap(), wire);
5176 assert_eq!(
5177 serde_json::from_value::<SubagentUpdate>(wire).unwrap(),
5178 update
5179 );
5180
5181 let minimal = SubagentUpdate::new("child");
5182 assert_eq!(
5183 serde_json::to_value(&minimal).unwrap(),
5184 json!({"sessionId": "child"})
5185 );
5186 let cleared: SubagentUpdate = serde_json::from_value(json!({
5187 "sessionId": "child", "title": null, "description": null
5188 }))
5189 .unwrap();
5190 assert!(cleared.title.is_null());
5191 assert!(cleared.description.is_null());
5192 assert_eq!(
5193 serde_json::to_value(cleared).unwrap(),
5194 json!({"sessionId": "child", "title": null, "description": null})
5195 );
5196 let invalid: SubagentUpdate = serde_json::from_value(json!({
5197 "sessionId": "child", "title": false, "description": false
5198 }))
5199 .unwrap();
5200 assert_eq!(invalid, minimal);
5201
5202 let title_only: SubagentUpdate = serde_json::from_value(json!({
5203 "sessionId": "child", "title": "Updated title"
5204 }))
5205 .unwrap();
5206 assert_eq!(
5207 title_only.title.value().map(String::as_str),
5208 Some("Updated title")
5209 );
5210 assert!(title_only.description.is_undefined());
5211 }
5212
5213 #[cfg(feature = "unstable_subagents")]
5214 #[test]
5215 fn subagent_directories_use_strict_patch_semantics() {
5216 use serde_json::json;
5217
5218 let update = SubagentUpdate::new("child")
5219 .cwd("/home/user/project/.worktrees/investigator")
5220 .additional_directories(vec![]);
5221 let wire = json!({
5222 "sessionId": "child",
5223 "cwd": "/home/user/project/.worktrees/investigator",
5224 "additionalDirectories": []
5225 });
5226 assert_eq!(serde_json::to_value(&update).unwrap(), wire);
5227 assert_eq!(
5228 serde_json::from_value::<SubagentUpdate>(wire).unwrap(),
5229 update
5230 );
5231
5232 let inherited: SubagentUpdate =
5233 serde_json::from_value(json!({"sessionId": "child"})).unwrap();
5234 assert!(inherited.cwd.is_undefined());
5235 assert!(inherited.additional_directories.is_undefined());
5236
5237 let cleared_wire = json!({
5238 "sessionId": "child", "cwd": null, "additionalDirectories": null
5239 });
5240 let cleared: SubagentUpdate = serde_json::from_value(cleared_wire.clone()).unwrap();
5241 assert!(cleared.cwd.is_null());
5242 assert!(cleared.additional_directories.is_null());
5243 assert_eq!(serde_json::to_value(cleared).unwrap(), cleared_wire);
5244
5245 for malformed in [
5246 json!({"sessionId": "child", "cwd": false}),
5247 json!({"sessionId": "child", "additionalDirectories": "/tmp/wt"}),
5248 json!({"sessionId": "child", "additionalDirectories": ["/tmp/wt", false]}),
5249 ] {
5250 assert!(
5251 serde_json::from_value::<SubagentUpdate>(malformed.clone()).is_err(),
5252 "{malformed}"
5253 );
5254 }
5255 }
5256
5257 #[cfg(feature = "unstable_subagents")]
5258 #[test]
5259 fn subagent_patch_fields_preserve_omitted_null_and_concrete() {
5260 use serde_json::json;
5261
5262 let omitted = SubagentUpdate::new("child");
5263 for field in ["title", "description", "capabilities", "state", "_meta"] {
5264 let wire = json!({"sessionId": "child", field: null});
5265 let decoded: SubagentUpdate = serde_json::from_value(wire.clone()).unwrap();
5266 assert_eq!(serde_json::to_value(decoded).unwrap(), wire, "{field}");
5267 let malformed = json!({"sessionId": "child", field: false});
5268 let decoded: SubagentUpdate = serde_json::from_value(malformed).unwrap();
5269 assert_eq!(decoded, omitted, "{field}");
5270 }
5271 let concrete = json!({
5272 "sessionId": "child", "title": "Investigator",
5273 "description": "Tests", "capabilities": {"cancel": {}},
5274 "state": {"state": "running"}, "_meta": {"source": "parent"}
5275 });
5276 let decoded: SubagentUpdate = serde_json::from_value(concrete.clone()).unwrap();
5277 assert!(decoded.title.value().is_some());
5278 assert!(decoded.description.value().is_some());
5279 assert!(decoded.capabilities.value().is_some());
5280 assert!(decoded.state.value().is_some());
5281 assert!(decoded.meta.value().is_some());
5282 assert_eq!(serde_json::to_value(decoded).unwrap(), concrete);
5283 let cleared = SubagentUpdate::new("child")
5284 .title(None)
5285 .description(None)
5286 .capabilities(None)
5287 .state(None)
5288 .meta(None);
5289 assert_eq!(
5290 serde_json::to_value(cleared).unwrap(),
5291 json!({
5292 "sessionId": "child", "title": null, "description": null,
5293 "capabilities": null, "state": null, "_meta": null
5294 })
5295 );
5296 }
5297
5298 #[cfg(feature = "unstable_subagents")]
5299 #[test]
5300 fn test_subagent_notification_keeps_parent_and_child_ids_nested() {
5301 use serde_json::json;
5302
5303 let notification = SessionNotification::new(
5304 "parent",
5305 SessionUpdate::SubagentUpdate(SubagentUpdate::new("child")),
5306 );
5307 let wire = json!({
5308 "sessionId": "parent",
5309 "update": {
5310 "sessionUpdate": "subagent_update",
5311 "sessionId": "child"
5312 }
5313 });
5314 assert_eq!(serde_json::to_value(¬ification).unwrap(), wire);
5315 assert_eq!(
5316 serde_json::from_value::<SessionNotification>(wire).unwrap(),
5317 notification
5318 );
5319 for malformed in [
5321 json!({"sessionId": "parent", "update": {"sessionUpdate": "subagent_update"}}),
5322 json!({"update": {"sessionUpdate": "subagent_update", "sessionId": "child"}}),
5323 ] {
5324 assert!(serde_json::from_value::<SessionNotification>(malformed).is_err());
5325 }
5326 }
5327
5328 #[cfg(feature = "unstable_subagents")]
5329 #[test]
5330 fn test_subagent_states_round_trip() {
5331 use serde_json::json;
5332
5333 for (wire_state, expected) in [
5334 (
5335 json!({"state": "running"}),
5336 StateUpdate::Running(RunningStateUpdate::new()),
5337 ),
5338 (
5339 json!({"state": "idle", "stopReason": "end_turn"}),
5340 StateUpdate::Idle(IdleStateUpdate::new().stop_reason(IdleStopReason::EndTurn)),
5341 ),
5342 (
5343 json!({"state": "requires_action"}),
5344 StateUpdate::RequiresAction(RequiresActionStateUpdate::new()),
5345 ),
5346 (
5347 json!({"state": "unknown"}),
5348 StateUpdate::Unknown(UnknownStateUpdate::new()),
5349 ),
5350 (
5351 json!({"state": "_waiting", "detail": {"ticket": 7}}),
5352 StateUpdate::Other(OtherStateUpdate::new(
5353 "_waiting",
5354 [("detail".into(), json!({"ticket": 7}))].into(),
5355 )),
5356 ),
5357 (
5358 json!({"state": "paused", "retryAt": 42}),
5359 StateUpdate::Other(OtherStateUpdate::new(
5360 "paused",
5361 [("retryAt".into(), json!(42))].into(),
5362 )),
5363 ),
5364 ] {
5365 let wire = json!({
5366 "sessionUpdate": "subagent_update",
5367 "sessionId": "sess_child",
5368 "state": wire_state
5369 });
5370 let parsed: SessionUpdate = serde_json::from_value(wire.clone()).unwrap();
5371 let SessionUpdate::SubagentUpdate(update) = &parsed else {
5372 panic!("expected subagent update");
5373 };
5374 assert_eq!(update.state.value(), Some(&expected));
5375 assert_eq!(serde_json::to_value(parsed).unwrap(), wire);
5376 }
5377
5378 for reason in [
5379 "end_turn",
5380 "max_tokens",
5381 "max_turn_requests",
5382 "refusal",
5383 "cancelled",
5384 ] {
5385 let state: StateUpdate = serde_json::from_value(json!({
5386 "state": "idle", "stopReason": reason
5387 }))
5388 .unwrap();
5389 assert_eq!(serde_json::to_value(state).unwrap()["stopReason"], reason);
5390 }
5391
5392 for state in [
5395 StateUpdate::Running(RunningStateUpdate::new()),
5396 StateUpdate::RequiresAction(RequiresActionStateUpdate::new()),
5397 StateUpdate::Unknown(UnknownStateUpdate::new()),
5398 StateUpdate::Running(RunningStateUpdate::new()),
5399 StateUpdate::Idle(IdleStateUpdate::new().stop_reason(IdleStopReason::EndTurn)),
5400 StateUpdate::Unknown(UnknownStateUpdate::new()),
5401 StateUpdate::Running(RunningStateUpdate::new()),
5402 ] {
5403 let update = SubagentUpdate::new("sess_child").state(state.clone());
5404 let wire = serde_json::to_value(&update).unwrap();
5405 assert_eq!(wire["sessionId"], "sess_child");
5406 assert_eq!(
5407 serde_json::from_value::<SubagentUpdate>(wire)
5408 .unwrap()
5409 .state,
5410 MaybeUndefined::Value(state)
5411 );
5412 }
5413 assert_eq!(
5414 serde_json::to_value(
5415 SubagentUpdate::new("sess_child").state(StateUpdate::Idle(IdleStateUpdate::new()))
5416 )
5417 .unwrap()["state"],
5418 json!({"state": "idle"})
5419 );
5420 }
5421
5422 #[cfg(feature = "unstable_subagents")]
5423 #[test]
5424 fn subagent_idle_snapshot_reports_child_failure() {
5425 use serde_json::json;
5426
5427 let update = SubagentUpdate::new("sess_child").state(StateUpdate::Idle(
5428 IdleStateUpdate::new().stop_reason(IdleStopReason::from(
5429 ErrorStopReason::new().error(Error::auth_required()),
5430 )),
5431 ));
5432 let wire = json!({
5433 "sessionId": "sess_child",
5434 "state": {
5435 "state": "idle",
5436 "stopReason": "error",
5437 "error": { "code": -32000, "message": "Authentication required" }
5438 }
5439 });
5440 assert_eq!(serde_json::to_value(&update).unwrap(), wire);
5441 assert_eq!(
5442 serde_json::from_value::<SubagentUpdate>(wire).unwrap(),
5443 update
5444 );
5445
5446 let without_details = StateUpdate::Idle(
5448 IdleStateUpdate::new().stop_reason(IdleStopReason::from(ErrorStopReason::new())),
5449 );
5450 for error in [None, Some(json!(null)), Some(json!("failed"))] {
5451 let mut wire = json!({ "state": "idle", "stopReason": "error" });
5452 if let Some(error) = error {
5453 wire["error"] = error;
5454 }
5455 assert_eq!(
5456 serde_json::from_value::<StateUpdate>(wire).unwrap(),
5457 without_details
5458 );
5459 }
5460
5461 let parsed: StateUpdate = serde_json::from_value(json!({
5464 "state": "idle",
5465 "stopReason": "end_turn",
5466 "error": { "code": -32603, "message": "Internal error" }
5467 }))
5468 .unwrap();
5469 assert_eq!(
5470 parsed,
5471 StateUpdate::Idle(IdleStateUpdate::new().stop_reason(IdleStopReason::EndTurn))
5472 );
5473
5474 let meta: Meta = [("source".into(), json!("worker"))].into_iter().collect();
5477 for stop_reason in [None, Some(json!(null)), Some(json!(true))] {
5478 let mut wire = json!({ "state": "idle", "_meta": { "source": "worker" } });
5479 if let Some(stop_reason) = stop_reason {
5480 wire["stopReason"] = stop_reason;
5481 }
5482 assert_eq!(
5483 serde_json::from_value::<StateUpdate>(wire).unwrap(),
5484 StateUpdate::Idle(IdleStateUpdate::new().meta(meta.clone()))
5485 );
5486 }
5487
5488 for stop_reason in ["_paused", "not_a_reason"] {
5491 let wire = json!({
5492 "state": "idle",
5493 "stopReason": stop_reason,
5494 "resumeAfter": 30,
5495 "_meta": { "source": "worker" }
5496 });
5497 let parsed: StateUpdate = serde_json::from_value(wire.clone()).unwrap();
5498 assert_eq!(
5499 parsed,
5500 StateUpdate::Idle(
5501 IdleStateUpdate::new()
5502 .stop_reason(IdleStopReason::Other(OtherStopReason::new(
5503 stop_reason,
5504 [("resumeAfter".into(), json!(30))].into_iter().collect(),
5505 )))
5506 .meta(meta.clone())
5507 )
5508 );
5509 assert_eq!(serde_json::to_value(&parsed).unwrap(), wire);
5510 }
5511 }
5512
5513 #[cfg(feature = "unstable_subagents")]
5514 #[test]
5515 fn subagent_known_stop_reasons_are_never_read_as_other() {
5516 use serde_json::json;
5517
5518 let known = [
5519 IdleStopReason::EndTurn,
5520 IdleStopReason::MaxTokens,
5521 IdleStopReason::MaxTurnRequests,
5522 IdleStopReason::Refusal,
5523 IdleStopReason::Cancelled,
5524 IdleStopReason::Error(ErrorStopReason::new()),
5525 ];
5526 for stop_reason in &known {
5528 match stop_reason {
5529 IdleStopReason::EndTurn
5530 | IdleStopReason::MaxTokens
5531 | IdleStopReason::MaxTurnRequests
5532 | IdleStopReason::Refusal
5533 | IdleStopReason::Cancelled
5534 | IdleStopReason::Error(_)
5535 | IdleStopReason::Other(_) => {}
5536 }
5537 }
5538
5539 for stop_reason in known {
5540 let state = StateUpdate::Idle(IdleStateUpdate::new().stop_reason(stop_reason));
5541 let wire = serde_json::to_value(&state).unwrap();
5542 assert_eq!(
5543 serde_json::from_value::<StateUpdate>(wire.clone()).unwrap(),
5544 state
5545 );
5546 assert!(
5547 serde_json::from_value::<OtherStopReason>(
5548 json!({ "stopReason": wire["stopReason"] })
5549 )
5550 .is_err(),
5551 "{} must not be accepted as a custom stop reason",
5552 wire["stopReason"]
5553 );
5554 }
5555 }
5556
5557 #[cfg(feature = "unstable_subagents")]
5558 #[test]
5559 fn subagent_unknown_stop_reason_leaves_usage_on_the_snapshot() {
5560 use serde_json::json;
5561
5562 let usage = json!({ "totalTokens": 10, "inputTokens": 6, "outputTokens": 4 });
5563 let wire = json!({ "state": "idle", "stopReason": "_paused", "usage": usage });
5564 let StateUpdate::Idle(idle) = serde_json::from_value(wire).unwrap() else {
5565 panic!("expected idle state snapshot");
5566 };
5567 let Some(IdleStopReason::Other(other)) = &idle.stop_reason else {
5568 panic!("expected a custom stop reason");
5569 };
5570 assert!(other.fields.is_empty());
5571
5572 #[cfg(feature = "unstable_end_turn_token_usage")]
5573 {
5574 assert!(idle.usage.is_some());
5575 assert_eq!(serde_json::to_value(&idle).unwrap()["usage"], usage);
5576 }
5577 #[cfg(not(feature = "unstable_end_turn_token_usage"))]
5580 assert!(serde_json::to_value(&idle).unwrap().get("usage").is_none());
5581 }
5582
5583 #[cfg(feature = "unstable_subagents")]
5584 #[test]
5585 fn test_subagent_unknown_activity_metadata_and_capabilities() {
5586 use serde_json::json;
5587
5588 let update = SubagentUpdate::new("child").state(StateUpdate::Unknown(
5589 UnknownStateUpdate::new().meta(
5590 [("source".into(), json!("worker"))]
5591 .into_iter()
5592 .collect::<Meta>(),
5593 ),
5594 ));
5595 let wire = json!({
5596 "sessionId": "child",
5597 "state": {
5598 "state": "unknown",
5599 "_meta": { "source": "worker" }
5600 }
5601 });
5602 assert_eq!(serde_json::to_value(&update).unwrap(), wire);
5603 assert_eq!(
5604 serde_json::from_value::<SubagentUpdate>(wire).unwrap(),
5605 update
5606 );
5607 assert!(update.capabilities.is_undefined());
5609
5610 for meta in [json!(null), json!(false)] {
5611 let state: StateUpdate = serde_json::from_value(json!({
5612 "state": "unknown",
5613 "_meta": meta
5614 }))
5615 .unwrap();
5616 assert_eq!(state, StateUpdate::Unknown(UnknownStateUpdate::new()));
5617 assert_eq!(
5618 serde_json::to_value(state).unwrap(),
5619 json!({"state": "unknown"})
5620 );
5621 }
5622 assert!(serde_json::from_value::<OtherStateUpdate>(json!({"state": "unknown"})).is_err());
5624 }
5625
5626 #[cfg(feature = "unstable_subagents")]
5627 #[test]
5628 fn test_subagent_malformed_optional_state() {
5629 use serde_json::json;
5630
5631 for malformed in [json!("running"), json!({}), json!({"state": 4})] {
5632 assert!(serde_json::from_value::<StateUpdate>(malformed.clone()).is_err());
5633 let update: SubagentUpdate = serde_json::from_value(json!({
5634 "sessionId": "child", "state": malformed
5635 }))
5636 .unwrap();
5637 assert!(update.state.is_undefined());
5638 }
5639 let bad_reason: StateUpdate =
5640 serde_json::from_value(json!({"state": "idle", "stopReason": false})).unwrap();
5641 assert_eq!(bad_reason, StateUpdate::Idle(IdleStateUpdate::new()));
5642 let null_reason: StateUpdate =
5643 serde_json::from_value(json!({"state": "idle", "stopReason": null})).unwrap();
5644 assert_eq!(null_reason, StateUpdate::Idle(IdleStateUpdate::new()));
5645 }
5646
5647 #[cfg(all(feature = "unstable_subagents", feature = "unstable_protocol_v2"))]
5648 #[test]
5649 fn test_subagent_state_v2_wire_parity() {
5650 use serde_json::json;
5651
5652 for wire in [
5653 json!({"state": "running"}),
5654 json!({"state": "idle", "stopReason": "cancelled"}),
5655 json!({"state": "requires_action"}),
5656 json!({"state": "unknown"}),
5657 json!({"state": "unknown", "_meta": {"source": "worker"}}),
5658 json!({"state": "_waiting", "detail": {"ticket": 7}}),
5659 ] {
5660 let v1: StateUpdate = serde_json::from_value(wire.clone()).unwrap();
5661 let v2: crate::v2::StateUpdate = serde_json::from_value(wire.clone()).unwrap();
5662 assert_eq!(serde_json::to_value(v1).unwrap(), wire);
5663 assert_eq!(serde_json::to_value(v2).unwrap(), wire);
5664 }
5665 }
5666
5667 #[cfg(feature = "unstable_subagents")]
5668 #[test]
5669 fn test_subagent_capability_semantics() {
5670 use serde_json::json;
5671
5672 let capabilities =
5673 serde_json::to_value(ClientCapabilities::new().subagents(SubagentCapabilities::new()))
5674 .unwrap();
5675 assert_eq!(capabilities["subagents"], json!({}));
5676
5677 let omitted: ClientCapabilities = serde_json::from_value(json!({})).unwrap();
5678 assert!(omitted.subagents.is_none());
5679
5680 let null: ClientCapabilities =
5681 serde_json::from_value(json!({ "subagents": null })).unwrap();
5682 assert!(null.subagents.is_none());
5683 assert_eq!(null, omitted);
5684 let serialized = serde_json::to_value(null).unwrap();
5685 assert_eq!(serialized, serde_json::to_value(omitted).unwrap());
5686 assert!(serialized.get("subagents").is_none());
5687
5688 for wire in [
5689 json!({}),
5690 json!({"cancel": null}),
5691 json!({"cancel": true}),
5692 json!({"cancel": false}),
5693 ] {
5694 let child: SubagentSessionCapabilities = serde_json::from_value(wire).unwrap();
5695 assert!(child.cancel.is_none());
5696 assert_eq!(serde_json::to_value(child).unwrap(), json!({}));
5697 }
5698 let enabled = SubagentSessionCapabilities::new().cancel(SessionCancelCapabilities::new());
5699 assert_eq!(
5700 serde_json::to_value(&enabled).unwrap(),
5701 json!({"cancel": {}})
5702 );
5703 assert_eq!(
5704 serde_json::from_value::<SubagentSessionCapabilities>(json!({"cancel": {}})).unwrap(),
5705 enabled
5706 );
5707 let meta: Meta = [("source".into(), json!("worker"))].into_iter().collect();
5708 let with_meta =
5709 SubagentSessionCapabilities::new().cancel(SessionCancelCapabilities::new().meta(meta));
5710 let wire = json!({"cancel": {"_meta": {"source": "worker"}}});
5711 assert_eq!(serde_json::to_value(&with_meta).unwrap(), wire);
5712 assert_eq!(
5713 serde_json::from_value::<SubagentSessionCapabilities>(wire).unwrap(),
5714 with_meta
5715 );
5716 let removed = SubagentSessionCapabilities::new();
5718 assert_eq!(serde_json::to_value(&removed).unwrap(), json!({}));
5719 assert!(removed.cancel.is_none());
5720 assert!(enabled.cancel.is_some());
5721 assert!(enabled.cancel(None).cancel.is_none());
5722 let replacement = SubagentUpdate::new("child").capabilities(removed);
5723 assert_eq!(
5724 serde_json::to_value(replacement).unwrap(),
5725 json!({"sessionId": "child", "capabilities": {}})
5726 );
5727 }
5728
5729 #[cfg(all(feature = "unstable_subagents", feature = "schemars"))]
5730 #[test]
5731 fn test_subagent_capability_schema_is_optional_and_nullable() {
5732 use serde_json::json;
5733
5734 let schema = serde_json::to_value(schemars::schema_for!(ClientCapabilities)).unwrap();
5735 let variants = schema["properties"]["subagents"]["anyOf"]
5736 .as_array()
5737 .expect("subagents must allow the capability object or null");
5738 assert!(variants.contains(&json!({"type": "null"})));
5739 assert!(
5740 !schema["required"]
5741 .as_array()
5742 .is_some_and(|required| required.contains(&json!("subagents")))
5743 );
5744 let child =
5745 serde_json::to_value(schemars::schema_for!(SubagentSessionCapabilities)).unwrap();
5746 let variants = child["properties"]["cancel"]["anyOf"]
5747 .as_array()
5748 .expect("cancel must allow the capability object or null");
5749 assert!(variants.contains(&json!({"type": "null"})));
5750 assert!(
5751 variants
5752 .iter()
5753 .any(|variant| variant["type"] == "object" || variant.get("$ref").is_some())
5754 );
5755 assert!(!variants.iter().any(|variant| variant["type"] == "boolean"));
5756 let cancel =
5757 serde_json::to_value(schemars::schema_for!(SessionCancelCapabilities)).unwrap();
5758 assert_eq!(cancel["type"], "object");
5759 assert!(
5760 !child["required"]
5761 .as_array()
5762 .is_some_and(|required| required.contains(&json!("cancel")))
5763 );
5764 }
5765
5766 #[test]
5767 fn test_elicitation_capability_semantics() {
5768 use serde_json::json;
5769
5770 let unsupported: ClientCapabilities = serde_json::from_value(json!({})).unwrap();
5771 assert!(unsupported.elicitation.is_none());
5772
5773 let null: ClientCapabilities =
5774 serde_json::from_value(json!({ "elicitation": null })).unwrap();
5775 assert!(null.elicitation.is_none());
5776
5777 let malformed: ClientCapabilities =
5778 serde_json::from_value(json!({ "elicitation": false })).unwrap();
5779 assert!(malformed.elicitation.is_none());
5780
5781 let empty: ClientCapabilities =
5782 serde_json::from_value(json!({ "elicitation": {} })).unwrap();
5783 let empty = empty.elicitation.expect("present capability");
5784 assert!(!empty.supports_form());
5785 assert!(!empty.supports_url());
5786
5787 let form_only: ClientCapabilities = serde_json::from_value(json!({
5788 "elicitation": { "form": {} }
5789 }))
5790 .unwrap();
5791 let form_only = form_only.elicitation.expect("advertised capability");
5792 assert!(form_only.supports_form());
5793 assert!(!form_only.supports_url());
5794
5795 let url_only: ClientCapabilities = serde_json::from_value(json!({
5796 "elicitation": { "url": {} }
5797 }))
5798 .unwrap();
5799 let url_only = url_only.elicitation.expect("advertised capability");
5800 assert!(!url_only.supports_form());
5801 assert!(url_only.supports_url());
5802
5803 let both: ClientCapabilities = serde_json::from_value(json!({
5804 "elicitation": { "form": {}, "url": {} }
5805 }))
5806 .unwrap();
5807 let both = both.elicitation.expect("advertised capability");
5808 assert!(both.supports_form());
5809 assert!(both.supports_url());
5810 }
5811
5812 #[test]
5813 fn test_elicitation_method_routing_and_envelopes() {
5814 use serde_json::json;
5815
5816 assert_eq!(CLIENT_METHOD_NAMES.elicitation_create, "elicitation/create");
5817 assert_eq!(
5818 CLIENT_METHOD_NAMES.elicitation_complete,
5819 "elicitation/complete"
5820 );
5821
5822 let request = AgentRequest::CreateElicitationRequest(CreateElicitationRequest::new(
5823 crate::v1::ElicitationFormMode::new(
5824 crate::v1::ElicitationSessionScope::new("sess_1"),
5825 crate::v1::ElicitationSchema::new(),
5826 ),
5827 "Choose a value",
5828 ));
5829 assert_eq!(request.method(), "elicitation/create");
5830 let method = Arc::from(request.method());
5831 let request = crate::v1::JsonRpcMessage::wrap(crate::v1::Request {
5832 id: crate::v1::RequestId::Number(7),
5833 method,
5834 params: Some(request),
5835 });
5836 assert_eq!(
5837 serde_json::to_value(request).unwrap(),
5838 json!({
5839 "jsonrpc": "2.0",
5840 "id": 7,
5841 "method": "elicitation/create",
5842 "params": {
5843 "mode": "form",
5844 "sessionId": "sess_1",
5845 "message": "Choose a value",
5846 "requestedSchema": { "type": "object", "properties": {} }
5847 }
5848 })
5849 );
5850
5851 let notification = AgentNotification::CompleteElicitationNotification(
5852 CompleteElicitationNotification::new("elic_1"),
5853 );
5854 assert_eq!(notification.method(), "elicitation/complete");
5855 let method = Arc::from(notification.method());
5856 let notification = crate::v1::JsonRpcMessage::wrap(crate::v1::Notification {
5857 method,
5858 params: Some(notification),
5859 });
5860 assert_eq!(
5861 serde_json::to_value(notification).unwrap(),
5862 json!({
5863 "jsonrpc": "2.0",
5864 "method": "elicitation/complete",
5865 "params": { "elicitationId": "elic_1" }
5866 })
5867 );
5868 }
5869
5870 #[test]
5871 fn test_client_capabilities_default_on_malformed_values() {
5872 use serde_json::json;
5873
5874 let capabilities: ClientCapabilities = serde_json::from_value(json!({
5875 "fs": {
5876 "readTextFile": "yes",
5877 "writeTextFile": true
5878 },
5879 "terminal": {}
5880 }))
5881 .unwrap();
5882
5883 assert!(!capabilities.fs.read_text_file);
5884 assert!(capabilities.fs.write_text_file);
5885 assert!(!capabilities.terminal);
5886
5887 let capabilities: ClientCapabilities = serde_json::from_value(json!({
5888 "fs": false
5889 }))
5890 .unwrap();
5891 assert_eq!(capabilities.fs, FileSystemCapabilities::default());
5892
5893 {
5894 let capabilities: ClientCapabilities = serde_json::from_value(json!({
5895 "auth": false
5896 }))
5897 .unwrap();
5898 assert_eq!(capabilities.auth, AuthCapabilities::default());
5899
5900 let capabilities: AuthCapabilities = serde_json::from_value(json!({
5901 "terminal": {}
5902 }))
5903 .unwrap();
5904 assert!(!capabilities.terminal);
5905 }
5906 }
5907
5908 #[test]
5909 fn test_serialization_behavior() {
5910 use serde_json::json;
5911
5912 assert_eq!(
5913 serde_json::from_value::<SessionInfoUpdate>(json!({})).unwrap(),
5914 SessionInfoUpdate {
5915 title: MaybeUndefined::Undefined,
5916 updated_at: MaybeUndefined::Undefined,
5917 meta: None
5918 }
5919 );
5920 assert_eq!(
5921 serde_json::from_value::<SessionInfoUpdate>(json!({"title": null, "updatedAt": null}))
5922 .unwrap(),
5923 SessionInfoUpdate {
5924 title: MaybeUndefined::Null,
5925 updated_at: MaybeUndefined::Null,
5926 meta: None
5927 }
5928 );
5929 assert_eq!(
5930 serde_json::from_value::<SessionInfoUpdate>(
5931 json!({"title": "title", "updatedAt": "timestamp"})
5932 )
5933 .unwrap(),
5934 SessionInfoUpdate {
5935 title: MaybeUndefined::Value("title".to_string()),
5936 updated_at: MaybeUndefined::Value("timestamp".to_string()),
5937 meta: None
5938 }
5939 );
5940
5941 assert_eq!(
5942 serde_json::to_value(SessionInfoUpdate::new()).unwrap(),
5943 json!({})
5944 );
5945 assert_eq!(
5946 serde_json::to_value(SessionInfoUpdate::new().title("title")).unwrap(),
5947 json!({"title": "title"})
5948 );
5949 assert_eq!(
5950 serde_json::to_value(SessionInfoUpdate::new().title(None)).unwrap(),
5951 json!({"title": null})
5952 );
5953 assert_eq!(
5954 serde_json::to_value(
5955 SessionInfoUpdate::new()
5956 .title("title")
5957 .title(MaybeUndefined::Undefined)
5958 )
5959 .unwrap(),
5960 json!({})
5961 );
5962 }
5963
5964 #[test]
5965 fn test_content_chunk_message_id_serialization() {
5966 use serde_json::json;
5967
5968 assert_eq!(
5969 serde_json::to_value(SessionUpdate::AgentMessageChunk(ContentChunk::new(
5970 ContentBlock::Text(crate::v1::TextContent::new("Hello"))
5971 )))
5972 .unwrap(),
5973 json!({
5974 "sessionUpdate": "agent_message_chunk",
5975 "content": {
5976 "type": "text",
5977 "text": "Hello"
5978 }
5979 })
5980 );
5981
5982 assert_eq!(
5983 serde_json::to_value(SessionUpdate::AgentMessageChunk(
5984 ContentChunk::new(ContentBlock::Text(crate::v1::TextContent::new("Hello")))
5985 .message_id("msg_agent_c42b9")
5986 ))
5987 .unwrap(),
5988 json!({
5989 "sessionUpdate": "agent_message_chunk",
5990 "messageId": "msg_agent_c42b9",
5991 "content": {
5992 "type": "text",
5993 "text": "Hello"
5994 }
5995 })
5996 );
5997
5998 let SessionUpdate::AgentMessageChunk(chunk) = serde_json::from_value(json!({
5999 "sessionUpdate": "agent_message_chunk",
6000 "messageId": null,
6001 "content": {
6002 "type": "text",
6003 "text": "Hello"
6004 }
6005 }))
6006 .unwrap() else {
6007 panic!("expected agent message chunk");
6008 };
6009
6010 assert_eq!(chunk.message_id, None);
6011 }
6012
6013 #[test]
6014 fn test_usage_update_serialization() {
6015 use serde_json::json;
6016
6017 assert_eq!(
6018 serde_json::to_value(SessionUpdate::UsageUpdate(UsageUpdate::new(
6019 53_000, 200_000
6020 )))
6021 .unwrap(),
6022 json!({
6023 "sessionUpdate": "usage_update",
6024 "used": 53000,
6025 "size": 200_000
6026 })
6027 );
6028
6029 assert_eq!(
6030 serde_json::to_value(SessionUpdate::UsageUpdate(
6031 UsageUpdate::new(53_000, 200_000).cost(Cost::new(0.045, "USD"))
6032 ))
6033 .unwrap(),
6034 json!({
6035 "sessionUpdate": "usage_update",
6036 "used": 53000,
6037 "size": 200_000,
6038 "cost": {
6039 "amount": 0.045,
6040 "currency": "USD"
6041 }
6042 })
6043 );
6044
6045 let SessionUpdate::UsageUpdate(update) = serde_json::from_value(json!({
6046 "sessionUpdate": "usage_update",
6047 "used": 53000,
6048 "size": 200_000,
6049 "cost": null
6050 }))
6051 .unwrap() else {
6052 panic!("expected usage update");
6053 };
6054
6055 assert_eq!(update.cost, None);
6056 }
6057
6058 #[test]
6059 fn test_client_capabilities_boolean_config_options_serialization() {
6060 use serde_json::json;
6061
6062 let capabilities = ClientCapabilities::new().session(
6063 ClientSessionCapabilities::new().config_options(
6064 SessionConfigOptionsCapabilities::new()
6065 .boolean(BooleanConfigOptionCapabilities::new()),
6066 ),
6067 );
6068 let json = serde_json::to_value(&capabilities).unwrap();
6069
6070 assert_eq!(json["session"]["configOptions"]["boolean"], json!({}));
6071
6072 let omitted: ClientCapabilities = serde_json::from_value(json!({})).unwrap();
6073 assert!(omitted.session.is_none());
6074
6075 let null_session: ClientCapabilities = serde_json::from_value(json!({
6076 "session": null
6077 }))
6078 .unwrap();
6079 assert!(null_session.session.is_none());
6080
6081 let null_config_options: ClientCapabilities = serde_json::from_value(json!({
6082 "session": {
6083 "configOptions": null
6084 }
6085 }))
6086 .unwrap();
6087 assert!(
6088 null_config_options
6089 .session
6090 .and_then(|session| session.config_options)
6091 .is_none()
6092 );
6093
6094 let null_boolean: ClientCapabilities = serde_json::from_value(json!({
6095 "session": {
6096 "configOptions": {
6097 "boolean": null
6098 }
6099 }
6100 }))
6101 .unwrap();
6102 assert!(
6103 null_boolean
6104 .session
6105 .and_then(|session| session.config_options)
6106 .and_then(|config_options| config_options.boolean)
6107 .is_none()
6108 );
6109 }
6110
6111 #[cfg(feature = "unstable_plan_operations")]
6112 #[test]
6113 fn test_plan_operations_serialization() {
6114 use serde_json::json;
6115
6116 use crate::v1::{PlanEntry, PlanEntryPriority, PlanEntryStatus, PlanUpdateContent};
6117
6118 let plan_update = SessionUpdate::PlanUpdate(PlanUpdate::new(PlanUpdateContent::items(
6119 "plan-1",
6120 vec![PlanEntry::new(
6121 "Step 1",
6122 PlanEntryPriority::High,
6123 PlanEntryStatus::Pending,
6124 )],
6125 )));
6126
6127 assert_eq!(
6128 serde_json::to_value(plan_update).unwrap(),
6129 json!({
6130 "sessionUpdate": "plan_update",
6131 "plan": {
6132 "type": "items",
6133 "planId": "plan-1",
6134 "entries": [
6135 {
6136 "content": "Step 1",
6137 "priority": "high",
6138 "status": "pending"
6139 }
6140 ]
6141 }
6142 })
6143 );
6144
6145 assert_eq!(
6146 serde_json::to_value(SessionUpdate::PlanRemoved(PlanRemoved::new("plan-1"))).unwrap(),
6147 json!({
6148 "sessionUpdate": "plan_removed",
6149 "planId": "plan-1"
6150 })
6151 );
6152
6153 let capabilities = ClientCapabilities::new().plan(PlanCapabilities::new());
6154 let json = serde_json::to_value(&capabilities).unwrap();
6155 assert_eq!(json["plan"], json!({}));
6156
6157 assert_eq!(
6158 serde_json::from_value::<ClientCapabilities>(json!({ "plan": null }))
6159 .unwrap()
6160 .plan,
6161 None
6162 );
6163 }
6164
6165 #[cfg(feature = "unstable_mcp_over_acp")]
6166 #[test]
6167 fn test_agent_mcp_request_method_names() {
6168 use serde_json::json;
6169
6170 let params: serde_json::Map<String, serde_json::Value> =
6171 [("cursor".to_string(), json!("abc"))].into_iter().collect();
6172
6173 assert_eq!(CLIENT_METHOD_NAMES.mcp_message, "mcp/message");
6174 assert_eq!(
6175 AgentRequest::MessageMcpRequest(MessageMcpRequest::new(
6176 "server-1",
6177 "req-1",
6178 "tools/list"
6179 ))
6180 .method(),
6181 "mcp/message"
6182 );
6183 assert_eq!(
6184 serde_json::to_value(
6185 MessageMcpRequest::new("server-1", "req-1", "tools/list").params(params)
6186 )
6187 .unwrap(),
6188 json!({
6189 "serverId": "server-1",
6190 "requestId": "req-1",
6191 "method": "tools/list",
6192 "params": { "cursor": "abc" }
6193 })
6194 );
6195
6196 let request_with_null_params: MessageMcpRequest = serde_json::from_value(json!({
6197 "serverId": "server-1",
6198 "requestId": "req-1",
6199 "method": "tools/list",
6200 "params": null,
6201 "_meta": null
6202 }))
6203 .unwrap();
6204 assert_eq!(request_with_null_params.params, None);
6205 assert_eq!(request_with_null_params.meta, None);
6206 for key in ["serverId", "requestId", "method"] {
6207 let mut value =
6208 json!({"serverId":"server-1", "requestId":"req-1", "method":"tools/list"});
6209 value.as_object_mut().unwrap().remove(key);
6210 assert!(serde_json::from_value::<MessageMcpRequest>(value).is_err());
6211 }
6212 for key in ["serverId", "requestId", "method"] {
6213 let mut value =
6214 json!({"serverId":"server-1", "requestId":"req-1", "method":"tools/list"});
6215 value[key] = serde_json::Value::Null;
6216 assert!(serde_json::from_value::<MessageMcpRequest>(value).is_err());
6217 }
6218 }
6219
6220 #[test]
6221 fn request_permission_request_rejects_malformed_options() {
6222 use serde_json::json;
6223
6224 assert!(
6225 serde_json::from_value::<RequestPermissionRequest>(json!({
6226 "sessionId": "sess-1",
6227 "toolCall": {"toolCallId": "tc-1"},
6228 "options": "not-an-array"
6229 }))
6230 .is_err()
6231 );
6232 assert!(
6233 serde_json::from_value::<RequestPermissionRequest>(json!({
6234 "sessionId": "sess-1",
6235 "toolCall": {"toolCallId": "tc-1"},
6236 "options": [{"optionId": "allow"}]
6237 }))
6238 .is_err()
6239 );
6240 }
6241
6242 #[test]
6243 fn create_terminal_request_rejects_malformed_fields() {
6244 use serde_json::json;
6245
6246 let request = |field: &str, value: serde_json::Value| {
6247 let mut request = json!({"sessionId": "sess-1", "command": "npx"});
6248 request[field] = value;
6249 serde_json::from_value::<CreateTerminalRequest>(request)
6250 };
6251
6252 for (field, value) in [
6254 ("args", json!(["serve", "--port", 3000])),
6255 ("args", json!("serve --port 3000")),
6256 ("env", json!([{"name": "PORT", "value": 3000}])),
6257 ("env", json!({"PORT": "3000"})),
6258 ("cwd", json!({"path": "/repo"})),
6259 ("outputByteLimit", json!("1048576")),
6260 ] {
6261 assert!(request(field, value.clone()).is_err(), "{field}: {value}");
6262 }
6263
6264 for field in ["args", "env", "cwd", "outputByteLimit"] {
6265 assert_eq!(
6266 request(field, serde_json::Value::Null).unwrap(),
6267 CreateTerminalRequest::new("sess-1", "npx"),
6268 "{field}"
6269 );
6270 }
6271 }
6272
6273 #[test]
6274 fn read_text_file_request_rejects_malformed_range() {
6275 use serde_json::json;
6276
6277 let request = |field: &str, value: serde_json::Value| {
6278 let mut request = json!({"sessionId": "sess-1", "path": "/repo/src/main.rs"});
6279 request[field] = value;
6280 serde_json::from_value::<ReadTextFileRequest>(request)
6281 };
6282
6283 for field in ["line", "limit"] {
6285 assert!(request(field, json!("120")).is_err(), "{field}");
6286 assert!(request(field, json!(-1)).is_err(), "{field}");
6287 assert_eq!(
6288 request(field, serde_json::Value::Null).unwrap(),
6289 ReadTextFileRequest::new("sess-1", "/repo/src/main.rs"),
6290 "{field}"
6291 );
6292 }
6293 }
6294}