1use std::sync::Arc;
7
8use derive_more::{Display, From};
9use indexmap::IndexMap;
10#[cfg(feature = "schemars")]
11use schemars::Schema;
12use serde::{Deserialize, Serialize};
13use serde_with::{DefaultOnError, VecSkipError, serde_as, skip_serializing_none};
14
15#[cfg(feature = "unstable_auth_status")]
16use super::AuthStatusUpdateNotification;
17#[cfg(feature = "unstable_end_turn_token_usage")]
18use super::Usage;
19use super::{
20 AbsolutePath, ContentBlock, ExtNotification, ExtRequest, ExtResponse, Meta, PlanRemoved,
21 PlanUpdate, SessionConfigOption, SessionId, StopReason, TerminalId, TerminalOutputChunk,
22 TerminalUpdate, ToolCallContentChunk, ToolCallId, ToolCallUpdate,
23};
24use super::{
25 CompleteElicitationNotification, CreateElicitationRequest, CreateElicitationResponse,
26 ElicitationCapabilities,
27};
28use crate::{IntoMaybeUndefined, IntoOption, MaybeUndefined};
29
30#[cfg(feature = "unstable_mcp_over_acp")]
31use super::mcp::{MCP_MESSAGE_METHOD_NAME, MessageMcpRequest, MessageMcpResponse};
32
33#[serde_as]
41#[skip_serializing_none]
42#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
43#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
44#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = SESSION_UPDATE_NOTIFICATION)))]
45#[cfg_attr(feature = "schemars", schemars(extend("x-scope" = {"session": ["sessionId"]})))]
46#[serde(rename_all = "camelCase")]
47#[non_exhaustive]
48pub struct UpdateSessionNotification {
49 pub session_id: SessionId,
51 pub update: SessionUpdate,
53 #[serde_as(deserialize_as = "DefaultOnError")]
59 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
60 #[serde(default)]
61 #[serde(rename = "_meta")]
62 pub meta: Option<Meta>,
63}
64
65impl UpdateSessionNotification {
66 #[must_use]
68 pub fn new(session_id: impl Into<SessionId>, update: SessionUpdate) -> Self {
69 Self {
70 session_id: session_id.into(),
71 update,
72 meta: None,
73 }
74 }
75
76 #[must_use]
82 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
83 self.meta = meta.into_option();
84 self
85 }
86}
87
88#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
94#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
95#[serde(tag = "sessionUpdate", rename_all = "snake_case")]
96#[non_exhaustive]
97pub enum SessionUpdate {
98 #[cfg_attr(feature = "schemars", schemars(extend("x-state" = {"session": [{"action": "append", "target": "userMessage", "id": "messageId", "field": "content", "value": "content"}]})))]
100 UserMessageChunk(ContentChunk),
101 #[cfg_attr(feature = "schemars", schemars(extend("x-state" = {"session": [{"action": "upsert", "target": "userMessage", "id": "messageId"}]})))]
107 UserMessage(UserMessage),
108 #[cfg_attr(feature = "schemars", schemars(extend("x-state" = {"session": [{"action": "append", "target": "agentMessage", "id": "messageId", "field": "content", "value": "content"}]})))]
110 AgentMessageChunk(ContentChunk),
111 #[cfg_attr(feature = "schemars", schemars(extend("x-state" = {"session": [{"action": "upsert", "target": "agentMessage", "id": "messageId"}]})))]
117 AgentMessage(AgentMessage),
118 #[cfg_attr(feature = "schemars", schemars(extend("x-state" = {"session": [{"action": "append", "target": "agentThought", "id": "messageId", "field": "content", "value": "content"}]})))]
120 AgentThoughtChunk(ContentChunk),
121 #[cfg_attr(feature = "schemars", schemars(extend("x-state" = {"session": [{"action": "upsert", "target": "agentThought", "id": "messageId"}]})))]
127 AgentThought(AgentThought),
128 #[cfg_attr(feature = "schemars", schemars(extend("x-state" = {"session": [{"action": "replace", "target": "state"}]})))]
130 StateUpdate(StateUpdate),
131 #[cfg_attr(feature = "schemars", schemars(extend("x-state" = {"session": [{"action": "append", "target": "toolCall", "id": "toolCallId", "field": "content", "value": "content"}]})))]
133 ToolCallContentChunk(ToolCallContentChunk),
134 #[cfg_attr(feature = "schemars", schemars(extend("x-state" = {"session": [{"action": "upsert", "target": "toolCall", "id": "toolCallId"}]})))]
136 ToolCallUpdate(ToolCallUpdate),
137 #[cfg_attr(feature = "schemars", schemars(extend("x-state" = {"session": [{"action": "upsert", "target": "terminal", "id": "terminalId"}]})))]
139 TerminalUpdate(TerminalUpdate),
140 #[cfg_attr(feature = "schemars", schemars(extend("x-state" = {"session": [{"action": "append", "target": "terminal", "id": "terminalId", "field": "output.data", "value": "data"}]})))]
142 TerminalOutputChunk(TerminalOutputChunk),
143 #[cfg_attr(feature = "schemars", schemars(extend("x-state" = {"session": [{"action": "replace", "target": "plan", "id": "plan.planId", "value": "plan"}]})))]
146 PlanUpdate(PlanUpdate),
147 #[cfg_attr(feature = "schemars", schemars(extend("x-state" = {"session": [{"action": "remove", "target": "plan", "id": "planId"}]})))]
149 PlanRemoved(PlanRemoved),
150 #[cfg_attr(feature = "schemars", schemars(extend("x-state" = {"session": [{"action": "replace", "target": "availableCommands", "value": "availableCommands"}]})))]
152 AvailableCommandsUpdate(AvailableCommandsUpdate),
153 #[cfg_attr(feature = "schemars", schemars(extend("x-state" = {"session": [{"action": "replace", "target": "configOptions", "value": "configOptions"}]})))]
155 ConfigOptionUpdate(ConfigOptionUpdate),
156 #[cfg_attr(feature = "schemars", schemars(extend("x-state" = {"session": [{"action": "upsert", "target": "sessionInfo"}]})))]
158 SessionInfoUpdate(SessionInfoUpdate),
159 #[cfg_attr(feature = "schemars", schemars(extend("x-state" = {"session": [{"action": "upsert", "target": "usage"}]})))]
161 UsageUpdate(UsageUpdate),
162 #[cfg_attr(feature = "schemars", schemars(extend("x-state" = {})))]
167 Notice(Notice),
168 #[cfg_attr(feature = "schemars", schemars(extend("x-state" = {"session": [{"action": "upsert", "target": "compaction", "id": "compactionId"}]})))]
170 CompactionUpdate(CompactionUpdate),
171 #[cfg_attr(feature = "schemars", schemars(extend("x-state" = {"session": [{"action": "append", "target": "compaction", "id": "compactionId", "field": "summary", "value": "content"}]})))]
173 CompactionSummaryChunk(CompactionSummaryChunk),
174 #[cfg_attr(feature = "schemars", schemars(extend("x-state" = {})))]
179 ReplayComplete(ReplayComplete),
180 #[cfg(feature = "unstable_prompt_suggestions")]
189 #[cfg_attr(feature = "schemars", schemars(extend("x-state" = {"session": [{"action": "replace", "target": "promptSuggestions", "value": "suggestions"}]})))]
190 PromptSuggestionsUpdate(PromptSuggestionsUpdate),
191 #[cfg(feature = "unstable_session_cursors")]
200 #[cfg_attr(feature = "schemars", schemars(extend("x-state" = {"session": [{"action": "upsert", "target": "cursor", "id": "cursorId"}]})))]
201 CursorUpdate(CursorUpdate),
202 #[cfg_attr(feature = "schemars", schemars(extend("x-state" = {"session": [{"action": "upsert", "target": "subagent", "id": "sessionId"}]})))]
205 SubagentUpdate(SubagentUpdate),
206 #[cfg_attr(feature = "schemars", schemars(extend("x-state" = {"session": [{"action": "upsert", "target": "sessionMessage", "id": "messageId"}]})))]
209 SessionMessage(SessionMessage),
210 #[cfg_attr(feature = "schemars", schemars(extend("x-state" = {"session": [{"action": "append", "target": "sessionMessage", "id": "messageId", "field": "content", "value": "content"}]})))]
212 SessionMessageChunk(SessionMessageChunk),
213 #[serde(untagged)]
223 Other(OtherSessionUpdate),
224}
225
226#[serde_as]
231#[skip_serializing_none]
232#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
233#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
234#[serde(rename_all = "camelCase")]
235#[non_exhaustive]
236pub struct SessionMessageChunk {
237 pub message_id: MessageId,
239 pub content: ContentBlock,
241 #[serde_as(deserialize_as = "DefaultOnError")]
248 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
249 #[serde(default, rename = "_meta")]
250 pub meta: Option<Meta>,
251}
252
253impl SessionMessageChunk {
254 #[must_use]
256 pub fn new(message_id: impl Into<MessageId>, content: ContentBlock) -> Self {
257 Self {
258 message_id: message_id.into(),
259 content,
260 meta: None,
261 }
262 }
263
264 #[must_use]
266 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
267 self.meta = meta.into_option();
268 self
269 }
270}
271
272#[serde_as]
274#[skip_serializing_none]
275#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
276#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
277#[serde(rename_all = "camelCase")]
278#[non_exhaustive]
279pub struct SessionMessage {
280 pub message_id: MessageId,
282 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
286 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
287 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
288 pub sender_session_id: MaybeUndefined<SessionId>,
289 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
293 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
294 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
295 pub recipient_session_id: MaybeUndefined<SessionId>,
296 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
302 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
303 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
304 pub sender_message_id: MaybeUndefined<MessageId>,
305 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
311 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
312 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
313 pub recipient_message_id: MaybeUndefined<MessageId>,
314 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<VecSkipError<_>>>")]
317 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
318 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
319 pub content: MaybeUndefined<Vec<ContentBlock>>,
320 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
329 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
330 #[serde(
331 default,
332 rename = "_meta",
333 skip_serializing_if = "MaybeUndefined::is_undefined"
334 )]
335 pub meta: MaybeUndefined<Meta>,
336}
337
338impl SessionMessage {
339 #[must_use]
341 pub fn new(message_id: impl Into<MessageId>) -> Self {
342 Self {
343 message_id: message_id.into(),
344 sender_session_id: MaybeUndefined::Undefined,
345 recipient_session_id: MaybeUndefined::Undefined,
346 sender_message_id: MaybeUndefined::Undefined,
347 recipient_message_id: MaybeUndefined::Undefined,
348 content: MaybeUndefined::Undefined,
349 meta: MaybeUndefined::Undefined,
350 }
351 }
352
353 #[must_use]
355 pub fn sender_session_id(
356 mut self,
357 sender_session_id: impl IntoMaybeUndefined<SessionId>,
358 ) -> Self {
359 self.sender_session_id = sender_session_id.into_maybe_undefined();
360 self
361 }
362
363 #[must_use]
365 pub fn recipient_session_id(
366 mut self,
367 recipient_session_id: impl IntoMaybeUndefined<SessionId>,
368 ) -> Self {
369 self.recipient_session_id = recipient_session_id.into_maybe_undefined();
370 self
371 }
372
373 #[must_use]
375 pub fn sender_message_id(
376 mut self,
377 sender_message_id: impl IntoMaybeUndefined<MessageId>,
378 ) -> Self {
379 self.sender_message_id = sender_message_id.into_maybe_undefined();
380 self
381 }
382
383 #[must_use]
385 pub fn recipient_message_id(
386 mut self,
387 recipient_message_id: impl IntoMaybeUndefined<MessageId>,
388 ) -> Self {
389 self.recipient_message_id = recipient_message_id.into_maybe_undefined();
390 self
391 }
392
393 #[must_use]
395 pub fn content(mut self, content: impl IntoMaybeUndefined<Vec<ContentBlock>>) -> Self {
396 self.content = content.into_maybe_undefined();
397 self
398 }
399
400 #[must_use]
405 pub fn meta(mut self, meta: impl IntoMaybeUndefined<Meta>) -> Self {
406 self.meta = meta.into_maybe_undefined();
407 self
408 }
409}
410
411#[cfg(test)]
412mod session_message_tests {
413 use super::*;
414 use serde_json::{Value, json};
415
416 #[test]
417 fn transcript_envelopes_and_multimodal_content() {
418 for (transcript, sender, recipient, id) in [
419 ("parent", "parent", "child", "sent-1"),
420 ("child", "parent", "child", "received-9"),
421 ("child", "child", "parent", "sent-2"),
422 ] {
423 let wire = json!({"sessionId": transcript, "update": {
424 "sessionUpdate": "session_message", "messageId": id,
425 "senderSessionId": sender, "recipientSessionId": recipient, "content": [
426 {"type": "text", "text": "hello"},
427 {"type": "image", "data": "aGVsbG8=", "mimeType": "image/png"}
428 ]
429 }});
430 let decoded: UpdateSessionNotification = serde_json::from_value(wire.clone()).unwrap();
431 assert_eq!(serde_json::to_value(decoded).unwrap(), wire);
432 }
433 }
434
435 #[test]
436 fn chunks_and_upserts_share_transcript_local_identity() {
437 for (transcript, id) in [("parent", "sent-1"), ("child", "received-9")] {
438 let wire = json!({"sessionId": transcript, "update": {
439 "sessionUpdate": "session_message_chunk", "messageId": id,
440 "content": {"type": "text", "text": "hello"}
441 }});
442 let decoded: UpdateSessionNotification = serde_json::from_value(wire.clone()).unwrap();
443 assert_eq!(serde_json::to_value(decoded).unwrap(), wire);
444 let upsert = SessionMessage::new(id)
445 .sender_session_id(SessionId::new("parent"))
446 .recipient_session_id(SessionId::new("child"))
447 .content(vec![]);
448 let chunk = SessionMessageChunk::new(
449 id,
450 ContentBlock::Text(crate::v2::TextContent::new("hello")),
451 );
452 assert_eq!(chunk.message_id, upsert.message_id);
453 assert_eq!(
454 serde_json::to_value(SessionUpdate::SessionMessageChunk(chunk)).unwrap(),
455 wire["update"]
456 );
457 assert_eq!(serde_json::to_value(upsert).unwrap()["content"], json!([]));
458 }
459 let with_identity = json!({"sessionUpdate": "session_message_chunk", "messageId": "m1",
461 "senderSessionId": "parent", "recipientSessionId": "child",
462 "senderMessageId": "sent-1", "recipientMessageId": "received-1",
463 "content": {"type": "text", "text": "hello"}});
464 let decoded: SessionUpdate = serde_json::from_value(with_identity).unwrap();
465 assert_eq!(
466 serde_json::to_value(decoded).unwrap(),
467 json!({"sessionUpdate": "session_message_chunk", "messageId": "m1",
468 "content": {"type": "text", "text": "hello"}})
469 );
470 }
471
472 #[test]
473 fn required_ids_and_chunk_content_with_upsert_patch_semantics() {
474 for (kind, content) in [
475 ("session_message", json!([])),
476 (
477 "session_message_chunk",
478 json!({"type": "text", "text": "hello"}),
479 ),
480 ] {
481 let mut base = json!({"sessionUpdate": kind, "messageId": "m1", "content": content});
482 if kind == "session_message" {
483 base["senderSessionId"] = json!("parent");
484 base["recipientSessionId"] = json!("child");
485 }
486 {
487 let key = "messageId";
488 let mut missing = base.clone();
489 missing.as_object_mut().unwrap().remove(key);
490 assert!(
491 serde_json::from_value::<SessionUpdate>(missing).is_err(),
492 "{kind} {key}"
493 );
494 let mut null = base.clone();
495 null[key] = Value::Null;
496 assert!(
497 serde_json::from_value::<SessionUpdate>(null).is_err(),
498 "{kind} {key}"
499 );
500 let mut non_string = base.clone();
501 non_string[key] = json!(42);
502 assert!(
503 serde_json::from_value::<SessionUpdate>(non_string).is_err(),
504 "{kind} {key}"
505 );
506 }
507 if kind == "session_message_chunk" {
508 for content in [None, Some(Value::Null), Some(json!([]))] {
509 let mut invalid = base.clone();
510 invalid.as_object_mut().unwrap().remove("content");
511 if let Some(content) = content {
512 invalid["content"] = content;
513 }
514 assert!(serde_json::from_value::<SessionUpdate>(invalid).is_err());
515 }
516 } else {
517 for content in [None, Some(Value::Null), Some(json!([])), Some(json!({}))] {
518 let mut wire = base.clone();
519 wire.as_object_mut().unwrap().remove("content");
520 if let Some(content) = content {
521 wire["content"] = content;
522 }
523 let decoded: SessionUpdate = serde_json::from_value(wire.clone()).unwrap();
524 let encoded = serde_json::to_value(decoded).unwrap();
525 if wire["content"].is_object() {
526 wire.as_object_mut().unwrap().remove("content");
527 }
528 assert_eq!(encoded, wire);
529 }
530 }
531 for meta in [None, Some(Value::Null), Some(json!({"tag": "value"}))] {
532 let mut wire = base.clone();
533 if let Some(meta) = meta {
534 wire["_meta"] = meta;
535 }
536 let decoded: SessionUpdate = serde_json::from_value(wire.clone()).unwrap();
537 let encoded = serde_json::to_value(decoded).unwrap();
538 if kind == "session_message" {
539 assert_eq!(encoded, wire);
540 } else if wire["_meta"].is_null() {
541 assert_eq!(encoded, base);
542 } else {
543 assert_eq!(encoded, wire);
544 }
545 }
546 }
547 let metadata_only = json!({"sessionUpdate": "session_message",
548 "messageId": "m1", "senderSessionId": "parent",
549 "recipientSessionId": "child", "_meta": {"tag": "value"}});
550 let decoded: SessionUpdate = serde_json::from_value(metadata_only.clone()).unwrap();
551 assert_eq!(serde_json::to_value(decoded).unwrap(), metadata_only);
552 let cleared = SessionMessage::new("m1")
553 .sender_session_id(SessionId::new("parent"))
554 .recipient_session_id(SessionId::new("child"))
555 .content(None)
556 .meta(None);
557 assert_eq!(
558 serde_json::to_value(cleared).unwrap(),
559 json!({"messageId": "m1", "senderSessionId": "parent",
560 "recipientSessionId": "child", "content": null, "_meta": null})
561 );
562 }
563
564 #[cfg(feature = "schemars")]
565 #[test]
566 fn schemas_require_ids_and_chunk_content_but_not_upsert_content() {
567 let upsert = serde_json::to_value(schemars::schema_for!(SessionMessage)).unwrap();
568 let required = upsert["required"].as_array().unwrap();
569 assert_eq!(required, &vec![json!("messageId")]);
570 let chunk = serde_json::to_value(schemars::schema_for!(SessionMessageChunk)).unwrap();
571 let required = chunk["required"].as_array().unwrap();
572 assert_eq!(required.len(), 2);
573 assert!(required.contains(&json!("messageId")));
574 assert!(required.contains(&json!("content")));
575 }
576
577 #[test]
578 fn endpoints_can_arrive_late_or_be_omitted_from_later_events() {
579 let block = ContentBlock::Text(crate::v2::TextContent::new("hello"));
580 let minimal = SessionMessage::new("m1");
581 let first = SessionMessageChunk::new("m1", block.clone());
582 assert_eq!(
583 serde_json::to_value(&minimal).unwrap(),
584 json!({"messageId": "m1"})
585 );
586 assert_eq!(
587 serde_json::to_value(&first).unwrap(),
588 json!({"messageId": "m1", "content": {"type": "text", "text": "hello"}})
589 );
590 let enriched = SessionMessage::new("m1")
591 .sender_session_id(SessionId::new("parent"))
592 .recipient_session_id(SessionId::new("child"));
593 assert_eq!(
594 enriched.sender_session_id,
595 MaybeUndefined::Value(SessionId::new("parent"))
596 );
597 assert_eq!(
598 enriched.recipient_session_id,
599 MaybeUndefined::Value(SessionId::new("child"))
600 );
601 let later = SessionMessage::new("m1").sender_session_id(SessionId::new("parent"));
602 assert_eq!(
603 later.sender_session_id,
604 MaybeUndefined::Value(SessionId::new("parent"))
605 );
606 assert_eq!(later.recipient_session_id, MaybeUndefined::Undefined);
607 let more = SessionMessageChunk::new("m1", block);
608 for update in [
609 SessionUpdate::SessionMessage(minimal),
610 SessionUpdate::SessionMessageChunk(first),
611 SessionUpdate::SessionMessage(enriched),
612 SessionUpdate::SessionMessage(later),
613 SessionUpdate::SessionMessageChunk(more),
614 ] {
615 let wire = serde_json::to_value(&update).unwrap();
616 let decoded: SessionUpdate = serde_json::from_value(wire.clone()).unwrap();
617 assert_eq!(serde_json::to_value(decoded).unwrap(), wire);
618 }
619 }
620
621 #[test]
622 fn null_endpoints_clear_invalid_are_absent_but_message_id_is_required() {
623 let mut base = json!({"sessionUpdate": "session_message", "messageId": "m1",
624 "senderSessionId": null, "recipientSessionId": 42});
625 let decoded: SessionUpdate = serde_json::from_value(base.clone()).unwrap();
626 let encoded = serde_json::to_value(decoded).unwrap();
627 base.as_object_mut().unwrap().remove("recipientSessionId");
628 assert_eq!(encoded, base);
629 for bad in [Value::Null, json!(42)] {
630 let mut invalid = base.clone();
631 invalid["messageId"] = bad;
632 assert!(serde_json::from_value::<SessionUpdate>(invalid).is_err());
633 }
634 }
635
636 #[test]
637 fn message_references_link_views_and_can_arrive_late() {
638 let block = ContentBlock::Text(crate::v2::TextContent::new("hello"));
639 let incoming = SessionMessage::new("received-1")
640 .sender_session_id(SessionId::new("parent"))
641 .recipient_session_id(SessionId::new("child"))
642 .sender_message_id(MessageId::new("sent-1"))
643 .content(vec![block]);
644 let outgoing =
646 SessionMessage::new("sent-1").recipient_message_id(MessageId::new("received-1"));
647 for (update, wire) in [
648 (
649 SessionUpdate::SessionMessage(incoming),
650 json!({"sessionUpdate": "session_message", "messageId": "received-1",
651 "senderSessionId": "parent", "recipientSessionId": "child",
652 "senderMessageId": "sent-1", "content": [{"type": "text", "text": "hello"}]}),
653 ),
654 (
655 SessionUpdate::SessionMessage(outgoing),
656 json!({"sessionUpdate": "session_message", "messageId": "sent-1",
657 "recipientMessageId": "received-1"}),
658 ),
659 ] {
660 assert_eq!(serde_json::to_value(&update).unwrap(), wire);
661 let decoded: SessionUpdate = serde_json::from_value(wire.clone()).unwrap();
662 assert_eq!(decoded, update);
663 }
664
665 let mut wire = json!({"sessionUpdate": "session_message", "messageId": "m1",
666 "senderMessageId": null, "recipientMessageId": 42});
667 let decoded: SessionUpdate = serde_json::from_value(wire.clone()).unwrap();
668 wire.as_object_mut().unwrap().remove("recipientMessageId");
669 assert_eq!(
670 serde_json::to_value(decoded).unwrap(),
671 wire,
672 "null clears a reference and a malformed one is not supplied"
673 );
674 }
675}
676
677#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
679#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
680#[serde(rename_all = "snake_case")]
681#[non_exhaustive]
682pub enum NoticeSeverity {
683 Info,
685 Warning,
687 Error,
689 #[serde(untagged)]
694 Other(String),
695}
696
697#[serde_as]
705#[skip_serializing_none]
706#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
707#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
708#[serde(rename_all = "camelCase")]
709#[non_exhaustive]
710pub struct Notice {
711 pub severity: NoticeSeverity,
713 #[cfg_attr(feature = "schemars", schemars(length(min = 1)))]
715 pub title: String,
716 #[serde_as(deserialize_as = "DefaultOnError")]
720 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
721 #[serde(default)]
722 pub description: Option<String>,
723 #[serde_as(deserialize_as = "DefaultOnError")]
729 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
730 #[serde(default, rename = "_meta")]
731 pub meta: Option<Meta>,
732}
733
734impl Notice {
735 #[must_use]
737 pub fn new(severity: NoticeSeverity, title: impl Into<String>) -> Self {
738 Self {
739 severity,
740 title: title.into(),
741 description: None,
742 meta: None,
743 }
744 }
745
746 #[must_use]
748 pub fn description(mut self, description: impl IntoOption<String>) -> Self {
749 self.description = description.into_option();
750 self
751 }
752
753 #[must_use]
755 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
756 self.meta = meta.into_option();
757 self
758 }
759}
760
761#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
763#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
764#[serde(transparent)]
765#[from(forward)]
766#[non_exhaustive]
767pub struct CompactionId(pub Arc<str>);
768
769impl CompactionId {
770 #[must_use]
772 pub fn new(id: impl Into<Self>) -> Self {
773 id.into()
774 }
775}
776
777#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
779#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
780#[serde(rename_all = "snake_case")]
781#[non_exhaustive]
782pub enum CompactionStatus {
783 #[default]
785 InProgress,
786 Completed,
788 Failed,
790 Cancelled,
792 #[serde(untagged)]
797 Other(String),
798}
799
800#[serde_as]
809#[skip_serializing_none]
810#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
811#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
812#[serde(rename_all = "camelCase")]
813#[non_exhaustive]
814pub struct CompactionUpdate {
815 pub compaction_id: CompactionId,
817 #[serde_as(deserialize_as = "DefaultOnError")]
822 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
823 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
824 pub status: MaybeUndefined<CompactionStatus>,
825 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<VecSkipError<_>>>")]
827 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
828 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
829 pub summary: MaybeUndefined<Vec<ContentBlock>>,
830 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
832 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
833 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
834 pub error: MaybeUndefined<String>,
835 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
844 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
845 #[serde(
846 rename = "_meta",
847 default,
848 skip_serializing_if = "MaybeUndefined::is_undefined"
849 )]
850 pub meta: MaybeUndefined<Meta>,
851}
852
853impl CompactionUpdate {
854 #[must_use]
856 pub fn new(compaction_id: impl Into<CompactionId>) -> Self {
857 Self {
858 compaction_id: compaction_id.into(),
859 status: MaybeUndefined::Undefined,
860 summary: MaybeUndefined::Undefined,
861 error: MaybeUndefined::Undefined,
862 meta: MaybeUndefined::Undefined,
863 }
864 }
865
866 #[must_use]
868 pub fn status(mut self, status: impl IntoMaybeUndefined<CompactionStatus>) -> Self {
869 self.status = status.into_maybe_undefined();
870 self
871 }
872
873 #[must_use]
875 pub fn summary(mut self, summary: impl IntoMaybeUndefined<Vec<ContentBlock>>) -> Self {
876 self.summary = summary.into_maybe_undefined();
877 self
878 }
879
880 #[must_use]
882 pub fn error(mut self, error: impl IntoMaybeUndefined<String>) -> Self {
883 self.error = error.into_maybe_undefined();
884 self
885 }
886
887 #[must_use]
892 pub fn meta(mut self, meta: impl IntoMaybeUndefined<Meta>) -> Self {
893 self.meta = meta.into_maybe_undefined();
894 self
895 }
896}
897
898#[serde_as]
901#[skip_serializing_none]
902#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
903#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
904#[serde(rename_all = "camelCase")]
905#[non_exhaustive]
906pub struct CompactionSummaryChunk {
907 pub compaction_id: CompactionId,
909 pub content: ContentBlock,
911 #[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_session_cursors")]
955#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
956#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
957#[serde(transparent)]
958#[from(forward)]
959#[non_exhaustive]
960pub struct CursorId(pub Arc<str>);
961
962#[cfg(feature = "unstable_session_cursors")]
963impl CursorId {
964 #[must_use]
966 pub fn new(id: impl Into<Self>) -> Self {
967 id.into()
968 }
969}
970
971#[cfg(feature = "unstable_session_cursors")]
987#[serde_as]
988#[skip_serializing_none]
989#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
990#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
991#[serde(rename_all = "camelCase")]
992#[non_exhaustive]
993pub struct CursorUpdate {
994 pub cursor_id: CursorId,
996 #[serde_as(deserialize_as = "DefaultOnError")]
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<CursorCapabilities>,
1004 #[serde(default)]
1010 pub anchor: Option<CursorAnchor>,
1011 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
1020 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1021 #[serde(
1022 rename = "_meta",
1023 default,
1024 skip_serializing_if = "MaybeUndefined::is_undefined"
1025 )]
1026 pub meta: MaybeUndefined<Meta>,
1027}
1028
1029#[cfg(feature = "unstable_session_cursors")]
1030impl CursorUpdate {
1031 #[must_use]
1033 pub fn new(cursor_id: impl Into<CursorId>) -> Self {
1034 Self {
1035 cursor_id: cursor_id.into(),
1036 capabilities: MaybeUndefined::Undefined,
1037 anchor: None,
1038 meta: MaybeUndefined::Undefined,
1039 }
1040 }
1041
1042 #[must_use]
1044 pub fn capabilities(
1045 mut self,
1046 capabilities: impl IntoMaybeUndefined<CursorCapabilities>,
1047 ) -> Self {
1048 self.capabilities = capabilities.into_maybe_undefined();
1049 self
1050 }
1051
1052 #[must_use]
1054 pub fn anchor(mut self, anchor: impl IntoOption<CursorAnchor>) -> Self {
1055 self.anchor = anchor.into_option();
1056 self
1057 }
1058
1059 #[must_use]
1064 pub fn meta(mut self, meta: impl IntoMaybeUndefined<Meta>) -> Self {
1065 self.meta = meta.into_maybe_undefined();
1066 self
1067 }
1068}
1069
1070#[cfg(feature = "unstable_session_cursors")]
1078#[serde_as]
1079#[skip_serializing_none]
1080#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1081#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1082#[serde(rename_all = "camelCase")]
1083#[non_exhaustive]
1084pub struct CursorCapabilities {
1085 #[cfg(feature = "unstable_session_fork")]
1090 #[serde_as(deserialize_as = "DefaultOnError")]
1091 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1092 #[serde(default)]
1093 pub fork: Option<CursorForkCapabilities>,
1094 #[serde_as(deserialize_as = "DefaultOnError")]
1100 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1101 #[serde(default)]
1102 #[serde(rename = "_meta")]
1103 pub meta: Option<Meta>,
1104}
1105
1106#[cfg(feature = "unstable_session_cursors")]
1107impl CursorCapabilities {
1108 #[must_use]
1110 pub fn new() -> Self {
1111 Self::default()
1112 }
1113
1114 #[cfg(feature = "unstable_session_fork")]
1116 #[must_use]
1117 pub fn fork(mut self, fork: impl IntoOption<CursorForkCapabilities>) -> Self {
1118 self.fork = fork.into_option();
1119 self
1120 }
1121
1122 #[must_use]
1128 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1129 self.meta = meta.into_option();
1130 self
1131 }
1132}
1133
1134#[cfg(all(
1142 feature = "unstable_session_cursors",
1143 feature = "unstable_session_fork"
1144))]
1145#[serde_as]
1146#[skip_serializing_none]
1147#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1148#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1149#[non_exhaustive]
1150pub struct CursorForkCapabilities {
1151 #[serde_as(deserialize_as = "DefaultOnError")]
1157 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1158 #[serde(default)]
1159 #[serde(rename = "_meta")]
1160 pub meta: Option<Meta>,
1161}
1162
1163#[cfg(all(
1164 feature = "unstable_session_cursors",
1165 feature = "unstable_session_fork"
1166))]
1167impl CursorForkCapabilities {
1168 #[must_use]
1170 pub fn new() -> Self {
1171 Self::default()
1172 }
1173
1174 #[must_use]
1180 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1181 self.meta = meta.into_option();
1182 self
1183 }
1184}
1185
1186#[cfg(feature = "unstable_session_cursors")]
1198#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1199#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1200#[serde(tag = "type", rename_all = "snake_case")]
1201#[non_exhaustive]
1202pub enum CursorAnchor {
1203 UserMessage(CursorMessageAnchor),
1205 AgentMessage(CursorMessageAnchor),
1207 AgentThought(CursorMessageAnchor),
1209 SessionMessage(CursorMessageAnchor),
1211 ToolCall(CursorToolCallAnchor),
1213 Compaction(CursorCompactionAnchor),
1215 #[serde(untagged)]
1224 Other(OtherCursorAnchor),
1225}
1226
1227#[cfg(feature = "unstable_session_cursors")]
1233#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1234#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1235#[serde(rename_all = "snake_case")]
1236#[non_exhaustive]
1237pub enum CursorAnchorPosition {
1238 Before,
1241 After,
1244 #[serde(untagged)]
1250 Other(String),
1251}
1252
1253#[cfg(feature = "unstable_session_cursors")]
1259#[serde_as]
1260#[skip_serializing_none]
1261#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1262#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1263#[serde(rename_all = "camelCase")]
1264#[non_exhaustive]
1265pub struct CursorMessageAnchor {
1266 pub message_id: MessageId,
1268 pub position: CursorAnchorPosition,
1270 #[serde_as(deserialize_as = "DefaultOnError")]
1276 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1277 #[serde(default)]
1278 #[serde(rename = "_meta")]
1279 pub meta: Option<Meta>,
1280}
1281
1282#[cfg(feature = "unstable_session_cursors")]
1283impl CursorMessageAnchor {
1284 #[must_use]
1286 pub fn new(message_id: impl Into<MessageId>, position: CursorAnchorPosition) -> Self {
1287 Self {
1288 message_id: message_id.into(),
1289 position,
1290 meta: None,
1291 }
1292 }
1293
1294 #[must_use]
1300 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1301 self.meta = meta.into_option();
1302 self
1303 }
1304}
1305
1306#[cfg(feature = "unstable_session_cursors")]
1312#[serde_as]
1313#[skip_serializing_none]
1314#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1315#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1316#[serde(rename_all = "camelCase")]
1317#[non_exhaustive]
1318pub struct CursorToolCallAnchor {
1319 pub tool_call_id: ToolCallId,
1321 pub position: CursorAnchorPosition,
1323 #[serde_as(deserialize_as = "DefaultOnError")]
1329 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1330 #[serde(default)]
1331 #[serde(rename = "_meta")]
1332 pub meta: Option<Meta>,
1333}
1334
1335#[cfg(feature = "unstable_session_cursors")]
1336impl CursorToolCallAnchor {
1337 #[must_use]
1339 pub fn new(tool_call_id: impl Into<ToolCallId>, position: CursorAnchorPosition) -> Self {
1340 Self {
1341 tool_call_id: tool_call_id.into(),
1342 position,
1343 meta: None,
1344 }
1345 }
1346
1347 #[must_use]
1353 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1354 self.meta = meta.into_option();
1355 self
1356 }
1357}
1358
1359#[cfg(feature = "unstable_session_cursors")]
1365#[serde_as]
1366#[skip_serializing_none]
1367#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1368#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1369#[serde(rename_all = "camelCase")]
1370#[non_exhaustive]
1371pub struct CursorCompactionAnchor {
1372 pub compaction_id: CompactionId,
1374 pub position: CursorAnchorPosition,
1376 #[serde_as(deserialize_as = "DefaultOnError")]
1382 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1383 #[serde(default)]
1384 #[serde(rename = "_meta")]
1385 pub meta: Option<Meta>,
1386}
1387
1388#[cfg(feature = "unstable_session_cursors")]
1389impl CursorCompactionAnchor {
1390 #[must_use]
1392 pub fn new(compaction_id: impl Into<CompactionId>, position: CursorAnchorPosition) -> Self {
1393 Self {
1394 compaction_id: compaction_id.into(),
1395 position,
1396 meta: None,
1397 }
1398 }
1399
1400 #[must_use]
1406 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1407 self.meta = meta.into_option();
1408 self
1409 }
1410}
1411
1412#[cfg(feature = "unstable_session_cursors")]
1421#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1422#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
1423#[cfg_attr(feature = "schemars", schemars(inline))]
1424#[cfg_attr(feature = "schemars", schemars(transform = other_cursor_anchor_schema))]
1425#[serde(rename_all = "camelCase")]
1426#[non_exhaustive]
1427pub struct OtherCursorAnchor {
1428 #[serde(rename = "type")]
1434 pub type_: String,
1435 #[serde(flatten)]
1438 pub fields: IndexMap<String, serde_json::Value>,
1439}
1440
1441#[cfg(feature = "unstable_session_cursors")]
1442impl OtherCursorAnchor {
1443 #[must_use]
1445 pub fn new(type_: impl Into<String>, mut fields: IndexMap<String, serde_json::Value>) -> Self {
1446 fields.shift_remove("type");
1447 Self {
1448 type_: type_.into(),
1449 fields,
1450 }
1451 }
1452}
1453
1454#[cfg(feature = "unstable_session_cursors")]
1455impl<'de> Deserialize<'de> for OtherCursorAnchor {
1456 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1457 where
1458 D: serde::Deserializer<'de>,
1459 {
1460 let mut fields = IndexMap::<String, serde_json::Value>::deserialize(deserializer)?;
1461 let type_ = fields
1462 .shift_remove("type")
1463 .ok_or_else(|| serde::de::Error::missing_field("type"))?;
1464 let serde_json::Value::String(type_) = type_ else {
1465 return Err(serde::de::Error::custom("`type` must be a string"));
1466 };
1467
1468 if KNOWN_CURSOR_ANCHOR_TYPES.contains(&type_.as_str()) {
1469 return Err(serde::de::Error::custom(format!(
1470 "known cursor anchor `{type_}` did not match its schema"
1471 )));
1472 }
1473
1474 Ok(Self { type_, fields })
1475 }
1476}
1477
1478#[cfg(feature = "unstable_session_cursors")]
1479const KNOWN_CURSOR_ANCHOR_TYPES: &[&str] = &[
1480 "user_message",
1481 "agent_message",
1482 "agent_thought",
1483 "session_message",
1484 "tool_call",
1485 "compaction",
1486];
1487
1488#[cfg(all(feature = "unstable_session_cursors", feature = "schemars"))]
1489fn other_cursor_anchor_schema(schema: &mut Schema) {
1490 super::schema_util::reject_known_string_discriminators(
1491 schema,
1492 "type",
1493 KNOWN_CURSOR_ANCHOR_TYPES,
1494 );
1495}
1496
1497#[serde_as]
1514#[skip_serializing_none]
1515#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1516#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq, Eq)]
1517#[serde(rename_all = "camelCase")]
1518#[non_exhaustive]
1519pub struct ReplayComplete {
1520 #[serde_as(deserialize_as = "DefaultOnError")]
1526 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1527 #[serde(default, rename = "_meta")]
1528 pub meta: Option<Meta>,
1529}
1530
1531impl ReplayComplete {
1532 #[must_use]
1534 pub fn new() -> Self {
1535 Self::default()
1536 }
1537
1538 #[must_use]
1540 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1541 self.meta = meta.into_option();
1542 self
1543 }
1544}
1545
1546#[serde_as]
1581#[skip_serializing_none]
1582#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1583#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1584#[serde(rename_all = "camelCase")]
1585#[non_exhaustive]
1586pub struct SubagentUpdate {
1587 pub session_id: SessionId,
1589 #[serde_as(deserialize_as = "DefaultOnError")]
1594 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1595 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
1596 pub title: MaybeUndefined<String>,
1597 #[serde_as(deserialize_as = "DefaultOnError")]
1603 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1604 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
1605 pub description: MaybeUndefined<String>,
1606 #[serde_as(deserialize_as = "DefaultOnError")]
1611 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1612 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
1613 pub capabilities: MaybeUndefined<SubagentSessionCapabilities>,
1614 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
1620 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1621 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
1622 pub state: MaybeUndefined<StateUpdate>,
1623 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
1629 pub cwd: MaybeUndefined<AbsolutePath>,
1630 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
1637 pub additional_directories: MaybeUndefined<Vec<AbsolutePath>>,
1638 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
1647 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1648 #[serde(
1649 rename = "_meta",
1650 default,
1651 skip_serializing_if = "MaybeUndefined::is_undefined"
1652 )]
1653 pub meta: MaybeUndefined<Meta>,
1654}
1655
1656impl SubagentUpdate {
1657 #[must_use]
1659 pub fn new(session_id: impl Into<SessionId>) -> Self {
1660 Self {
1661 session_id: session_id.into(),
1662 title: MaybeUndefined::Undefined,
1663 description: MaybeUndefined::Undefined,
1664 capabilities: MaybeUndefined::Undefined,
1665 state: MaybeUndefined::Undefined,
1666 cwd: MaybeUndefined::Undefined,
1667 additional_directories: MaybeUndefined::Undefined,
1668 meta: MaybeUndefined::Undefined,
1669 }
1670 }
1671
1672 #[must_use]
1674 pub fn title(mut self, title: impl IntoMaybeUndefined<String>) -> Self {
1675 self.title = title.into_maybe_undefined();
1676 self
1677 }
1678
1679 #[must_use]
1681 pub fn description(mut self, description: impl IntoMaybeUndefined<String>) -> Self {
1682 self.description = description.into_maybe_undefined();
1683 self
1684 }
1685
1686 #[must_use]
1688 pub fn capabilities(
1689 mut self,
1690 capabilities: impl IntoMaybeUndefined<SubagentSessionCapabilities>,
1691 ) -> Self {
1692 self.capabilities = capabilities.into_maybe_undefined();
1693 self
1694 }
1695
1696 #[must_use]
1698 pub fn state(mut self, state: impl IntoMaybeUndefined<StateUpdate>) -> Self {
1699 self.state = state.into_maybe_undefined();
1700 self
1701 }
1702
1703 #[must_use]
1707 pub fn cwd(mut self, cwd: impl IntoMaybeUndefined<AbsolutePath>) -> Self {
1708 self.cwd = cwd.into_maybe_undefined();
1709 self
1710 }
1711
1712 #[must_use]
1716 pub fn additional_directories(
1717 mut self,
1718 additional_directories: impl IntoMaybeUndefined<Vec<AbsolutePath>>,
1719 ) -> Self {
1720 self.additional_directories = additional_directories.into_maybe_undefined();
1721 self
1722 }
1723
1724 #[must_use]
1729 pub fn meta(mut self, meta: impl IntoMaybeUndefined<Meta>) -> Self {
1730 self.meta = meta.into_maybe_undefined();
1731 self
1732 }
1733}
1734
1735#[serde_as]
1742#[skip_serializing_none]
1743#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1744#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1745#[serde(rename_all = "camelCase")]
1746#[non_exhaustive]
1747pub struct SubagentSessionCapabilities {
1748 #[serde_as(deserialize_as = "DefaultOnError")]
1752 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1753 #[serde(default)]
1754 pub cancel: Option<SessionCancelCapabilities>,
1755 #[serde_as(deserialize_as = "DefaultOnError")]
1761 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1762 #[serde(default)]
1763 #[serde(rename = "_meta")]
1764 pub meta: Option<Meta>,
1765}
1766
1767impl SubagentSessionCapabilities {
1768 #[must_use]
1770 pub fn new() -> Self {
1771 Self::default()
1772 }
1773
1774 #[must_use]
1776 pub fn cancel(mut self, cancel: impl IntoOption<SessionCancelCapabilities>) -> Self {
1777 self.cancel = cancel.into_option();
1778 self
1779 }
1780
1781 #[must_use]
1785 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1786 self.meta = meta.into_option();
1787 self
1788 }
1789}
1790
1791#[serde_as]
1795#[skip_serializing_none]
1796#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1797#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1798#[non_exhaustive]
1799pub struct SessionCancelCapabilities {
1800 #[serde_as(deserialize_as = "DefaultOnError")]
1806 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1807 #[serde(default)]
1808 #[serde(rename = "_meta")]
1809 pub meta: Option<Meta>,
1810}
1811
1812impl SessionCancelCapabilities {
1813 #[must_use]
1815 pub fn new() -> Self {
1816 Self::default()
1817 }
1818
1819 #[must_use]
1825 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1826 self.meta = meta.into_option();
1827 self
1828 }
1829}
1830
1831#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1837#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
1838#[cfg_attr(feature = "schemars", schemars(inline))]
1839#[cfg_attr(feature = "schemars", schemars(transform = other_session_update_schema))]
1840#[serde(rename_all = "camelCase")]
1841#[non_exhaustive]
1842pub struct OtherSessionUpdate {
1843 #[serde(rename = "sessionUpdate")]
1849 pub session_update: String,
1850 #[serde(flatten)]
1852 pub fields: IndexMap<String, serde_json::Value>,
1853}
1854
1855impl OtherSessionUpdate {
1856 #[must_use]
1858 pub fn new(
1859 session_update: impl Into<String>,
1860 mut fields: IndexMap<String, serde_json::Value>,
1861 ) -> Self {
1862 fields.shift_remove("sessionUpdate");
1863 Self {
1864 session_update: session_update.into(),
1865 fields,
1866 }
1867 }
1868}
1869
1870impl<'de> Deserialize<'de> for OtherSessionUpdate {
1871 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1872 where
1873 D: serde::Deserializer<'de>,
1874 {
1875 let mut fields = IndexMap::<String, serde_json::Value>::deserialize(deserializer)?;
1876 let session_update = fields
1877 .shift_remove("sessionUpdate")
1878 .ok_or_else(|| serde::de::Error::missing_field("sessionUpdate"))?;
1879 let serde_json::Value::String(session_update) = session_update else {
1880 return Err(serde::de::Error::custom("`sessionUpdate` must be a string"));
1881 };
1882
1883 if is_known_session_update(&session_update) {
1884 return Err(serde::de::Error::custom(format!(
1885 "known session update `{session_update}` did not match its schema"
1886 )));
1887 }
1888
1889 Ok(Self {
1890 session_update,
1891 fields,
1892 })
1893 }
1894}
1895
1896fn is_known_session_update(session_update: &str) -> bool {
1897 if session_update == "notice" {
1898 return true;
1899 }
1900 if matches!(
1901 session_update,
1902 "compaction_update" | "compaction_summary_chunk" | "replay_complete"
1903 ) {
1904 return true;
1905 }
1906 #[cfg(feature = "unstable_prompt_suggestions")]
1907 if session_update == "prompt_suggestions_update" {
1908 return true;
1909 }
1910 #[cfg(feature = "unstable_session_cursors")]
1911 if session_update == "cursor_update" {
1912 return true;
1913 }
1914 if matches!(
1915 session_update,
1916 "subagent_update" | "session_message" | "session_message_chunk"
1917 ) {
1918 return true;
1919 }
1920 matches!(
1921 session_update,
1922 "user_message_chunk"
1923 | "user_message"
1924 | "agent_message_chunk"
1925 | "agent_message"
1926 | "agent_thought_chunk"
1927 | "agent_thought"
1928 | "state_update"
1929 | "tool_call_content_chunk"
1930 | "tool_call_update"
1931 | "terminal_update"
1932 | "terminal_output_chunk"
1933 | "plan_update"
1934 | "plan_removed"
1935 | "available_commands_update"
1936 | "config_option_update"
1937 | "session_info_update"
1938 | "usage_update"
1939 )
1940}
1941
1942#[cfg(feature = "schemars")]
1943fn other_session_update_schema(schema: &mut Schema) {
1944 super::schema_util::reject_known_string_discriminators(
1945 schema,
1946 "sessionUpdate",
1947 &[
1948 "user_message_chunk",
1949 "user_message",
1950 "agent_message_chunk",
1951 "agent_message",
1952 "agent_thought_chunk",
1953 "agent_thought",
1954 "state_update",
1955 "tool_call_content_chunk",
1956 "tool_call_update",
1957 "terminal_update",
1958 "terminal_output_chunk",
1959 "plan_update",
1960 "plan_removed",
1961 "available_commands_update",
1962 "config_option_update",
1963 "session_info_update",
1964 "usage_update",
1965 "notice",
1966 "compaction_update",
1967 "compaction_summary_chunk",
1968 "replay_complete",
1969 #[cfg(feature = "unstable_prompt_suggestions")]
1970 "prompt_suggestions_update",
1971 #[cfg(feature = "unstable_session_cursors")]
1972 "cursor_update",
1973 "subagent_update",
1974 "session_message",
1975 "session_message_chunk",
1976 ],
1977 );
1978}
1979
1980#[serde_as]
1982#[skip_serializing_none]
1983#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1984#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1985#[serde(rename_all = "camelCase")]
1986#[non_exhaustive]
1987pub struct ConfigOptionUpdate {
1988 #[serde_as(deserialize_as = "VecSkipError<_>")]
1990 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-skip-invalid-items" = true)))]
1991 pub config_options: Vec<SessionConfigOption>,
1992 #[serde_as(deserialize_as = "DefaultOnError")]
1998 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1999 #[serde(default)]
2000 #[serde(rename = "_meta")]
2001 pub meta: Option<Meta>,
2002}
2003
2004impl ConfigOptionUpdate {
2005 #[must_use]
2007 pub fn new(config_options: Vec<SessionConfigOption>) -> Self {
2008 Self {
2009 config_options,
2010 meta: None,
2011 }
2012 }
2013
2014 #[must_use]
2020 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2021 self.meta = meta.into_option();
2022 self
2023 }
2024}
2025
2026#[serde_as]
2035#[skip_serializing_none]
2036#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2037#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2038#[serde(rename_all = "camelCase")]
2039#[non_exhaustive]
2040pub struct SessionInfoUpdate {
2041 #[serde_as(deserialize_as = "DefaultOnError")]
2043 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2044 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
2045 pub title: MaybeUndefined<String>,
2046 #[serde_as(deserialize_as = "DefaultOnError")]
2048 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "format" = "date-time")))]
2049 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
2050 pub updated_at: MaybeUndefined<String>,
2051 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
2060 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2061 #[serde(
2062 rename = "_meta",
2063 default,
2064 skip_serializing_if = "MaybeUndefined::is_undefined"
2065 )]
2066 pub meta: MaybeUndefined<Meta>,
2067}
2068
2069impl SessionInfoUpdate {
2070 #[must_use]
2072 pub fn new() -> Self {
2073 Self::default()
2074 }
2075
2076 #[must_use]
2078 pub fn title(mut self, title: impl IntoMaybeUndefined<String>) -> Self {
2079 self.title = title.into_maybe_undefined();
2080 self
2081 }
2082
2083 #[must_use]
2085 pub fn updated_at(mut self, updated_at: impl IntoMaybeUndefined<String>) -> Self {
2086 self.updated_at = updated_at.into_maybe_undefined();
2087 self
2088 }
2089
2090 #[must_use]
2095 pub fn meta(mut self, meta: impl IntoMaybeUndefined<Meta>) -> Self {
2096 self.meta = meta.into_maybe_undefined();
2097 self
2098 }
2099}
2100
2101#[serde_as]
2103#[skip_serializing_none]
2104#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2105#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
2106#[serde(rename_all = "camelCase")]
2107#[non_exhaustive]
2108pub struct UsageUpdate {
2109 pub used: u64,
2111 pub size: u64,
2113 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
2117 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2118 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
2119 pub cost: MaybeUndefined<Cost>,
2120 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
2129 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2130 #[serde(
2131 rename = "_meta",
2132 default,
2133 skip_serializing_if = "MaybeUndefined::is_undefined"
2134 )]
2135 pub meta: MaybeUndefined<Meta>,
2136}
2137
2138impl UsageUpdate {
2139 #[must_use]
2141 pub fn new(used: u64, size: u64) -> Self {
2142 Self {
2143 used,
2144 size,
2145 cost: MaybeUndefined::Undefined,
2146 meta: MaybeUndefined::Undefined,
2147 }
2148 }
2149
2150 #[must_use]
2152 pub fn cost(mut self, cost: impl IntoMaybeUndefined<Cost>) -> Self {
2153 self.cost = cost.into_maybe_undefined();
2154 self
2155 }
2156
2157 #[must_use]
2162 pub fn meta(mut self, meta: impl IntoMaybeUndefined<Meta>) -> Self {
2163 self.meta = meta.into_maybe_undefined();
2164 self
2165 }
2166}
2167
2168#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2209#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2210#[serde(tag = "state", rename_all = "snake_case")]
2211#[non_exhaustive]
2212pub enum StateUpdate {
2213 Running(RunningStateUpdate),
2215 Idle(IdleStateUpdate),
2217 RequiresAction(RequiresActionStateUpdate),
2219 Unknown(UnknownStateUpdate),
2222 #[serde(untagged)]
2234 Other(OtherStateUpdate),
2235}
2236
2237impl StateUpdate {
2238 #[must_use]
2246 pub fn background(&self) -> Option<&[BackgroundWork]> {
2247 match self {
2248 Self::Running(state) => state.background.as_deref(),
2249 Self::Idle(state) => state.background.as_deref(),
2250 Self::RequiresAction(state) => state.background.as_deref(),
2251 Self::Unknown(state) => state.background.as_deref(),
2252 Self::Other(_) => None,
2253 }
2254 }
2255}
2256
2257#[serde_as]
2259#[skip_serializing_none]
2260#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2261#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2262#[serde(rename_all = "camelCase")]
2263#[non_exhaustive]
2264pub struct RunningStateUpdate {
2265 #[serde_as(deserialize_as = "DefaultOnError")]
2274 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2275 #[serde(default)]
2276 pub background: Option<Vec<BackgroundWork>>,
2277 #[serde_as(deserialize_as = "DefaultOnError")]
2283 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2284 #[serde(default)]
2285 #[serde(rename = "_meta")]
2286 pub meta: Option<Meta>,
2287}
2288
2289impl RunningStateUpdate {
2290 #[must_use]
2292 pub fn new() -> Self {
2293 Self::default()
2294 }
2295
2296 #[must_use]
2298 pub fn background(mut self, background: impl IntoOption<Vec<BackgroundWork>>) -> Self {
2299 self.background = background.into_option();
2300 self
2301 }
2302
2303 #[must_use]
2309 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2310 self.meta = meta.into_option();
2311 self
2312 }
2313}
2314
2315#[serde_as]
2323#[skip_serializing_none]
2324#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2325#[cfg_attr(feature = "schemars", schemars(transform = idle_state_update_schema))]
2326#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2327#[serde(rename_all = "camelCase")]
2328#[non_exhaustive]
2329pub struct IdleStateUpdate {
2330 #[serde(flatten)]
2332 pub stop_reason: Option<StopReason>,
2333 #[cfg(feature = "unstable_end_turn_token_usage")]
2343 #[serde_as(deserialize_as = "DefaultOnError")]
2344 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2345 #[serde(default)]
2346 pub usage: Option<Box<Usage>>,
2347 #[serde_as(deserialize_as = "DefaultOnError")]
2356 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2357 #[serde(default)]
2358 pub background: Option<Vec<BackgroundWork>>,
2359 #[serde_as(deserialize_as = "DefaultOnError")]
2365 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2366 #[serde(default)]
2367 #[serde(rename = "_meta")]
2368 pub meta: Option<Meta>,
2369}
2370
2371impl IdleStateUpdate {
2372 #[must_use]
2374 pub fn new() -> Self {
2375 Self::default()
2376 }
2377
2378 #[must_use]
2380 pub fn stop_reason(mut self, stop_reason: impl IntoOption<StopReason>) -> Self {
2381 self.stop_reason = stop_reason.into_option();
2382 self
2383 }
2384
2385 #[cfg(feature = "unstable_end_turn_token_usage")]
2391 #[must_use]
2392 pub fn usage(mut self, usage: impl IntoOption<Usage>) -> Self {
2393 self.usage = usage.into_option().map(Box::new);
2394 self
2395 }
2396
2397 #[must_use]
2399 pub fn background(mut self, background: impl IntoOption<Vec<BackgroundWork>>) -> Self {
2400 self.background = background.into_option();
2401 self
2402 }
2403
2404 #[must_use]
2410 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2411 self.meta = meta.into_option();
2412 self
2413 }
2414}
2415
2416#[cfg(feature = "schemars")]
2425fn idle_state_update_schema(schema: &mut Schema) {
2426 if let Some(properties) = schema
2427 .get_mut("properties")
2428 .and_then(serde_json::Value::as_object_mut)
2429 {
2430 properties.insert(
2431 "stopReason".into(),
2432 serde_json::json!({
2433 "description": "Why foreground work stopped. The value selects one of this type's variants, which may add fields of their own.\n\nOptional. Omitted and `null` are equivalent and mean the Agent is not reporting a stop reason.\n\nSee protocol docs: [Stop Reasons](https://agentclientprotocol.com/protocol/v2/prompt-lifecycle#stop-reasons)",
2434 "type": ["string", "null"],
2435 "x-deserialize-default-on-error": true
2436 }),
2437 );
2438 }
2439 let Some(variants) = schema
2440 .get_mut("anyOf")
2441 .and_then(serde_json::Value::as_array_mut)
2442 else {
2443 return;
2444 };
2445 for variant in variants {
2446 if variant.as_object().is_some_and(serde_json::Map::is_empty) {
2447 *variant = serde_json::json!({
2448 "title": "none",
2449 "description": "No stop reason: `stopReason` is omitted or `null`.",
2450 "type": "object",
2451 "properties": {
2452 "stopReason": { "type": "null" }
2453 }
2454 });
2455 }
2456 }
2457}
2458
2459#[serde_as]
2468#[skip_serializing_none]
2469#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2470#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2471#[serde(rename_all = "camelCase")]
2472#[non_exhaustive]
2473pub struct RequiresActionStateUpdate {
2474 #[serde_as(deserialize_as = "DefaultOnError")]
2483 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2484 #[serde(default)]
2485 pub background: Option<Vec<BackgroundWork>>,
2486 #[serde_as(deserialize_as = "DefaultOnError")]
2492 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2493 #[serde(default)]
2494 #[serde(rename = "_meta")]
2495 pub meta: Option<Meta>,
2496}
2497
2498impl RequiresActionStateUpdate {
2499 #[must_use]
2501 pub fn new() -> Self {
2502 Self::default()
2503 }
2504
2505 #[must_use]
2507 pub fn background(mut self, background: impl IntoOption<Vec<BackgroundWork>>) -> Self {
2508 self.background = background.into_option();
2509 self
2510 }
2511
2512 #[must_use]
2518 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2519 self.meta = meta.into_option();
2520 self
2521 }
2522}
2523
2524#[serde_as]
2537#[skip_serializing_none]
2538#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2539#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2540#[serde(rename_all = "camelCase")]
2541#[non_exhaustive]
2542pub struct UnknownStateUpdate {
2543 #[serde_as(deserialize_as = "DefaultOnError")]
2552 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2553 #[serde(default)]
2554 pub background: Option<Vec<BackgroundWork>>,
2555 #[serde_as(deserialize_as = "DefaultOnError")]
2561 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2562 #[serde(default, rename = "_meta")]
2563 pub meta: Option<Meta>,
2564}
2565
2566impl UnknownStateUpdate {
2567 #[must_use]
2569 pub fn new() -> Self {
2570 Self::default()
2571 }
2572
2573 #[must_use]
2575 pub fn background(mut self, background: impl IntoOption<Vec<BackgroundWork>>) -> Self {
2576 self.background = background.into_option();
2577 self
2578 }
2579
2580 #[must_use]
2582 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2583 self.meta = meta.into_option();
2584 self
2585 }
2586}
2587
2588#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2593#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
2594#[cfg_attr(feature = "schemars", schemars(inline))]
2595#[cfg_attr(feature = "schemars", schemars(transform = other_state_update_schema))]
2596#[serde(rename_all = "camelCase")]
2597#[non_exhaustive]
2598pub struct OtherStateUpdate {
2599 #[serde(rename = "state")]
2605 pub state: String,
2606 #[serde(flatten)]
2608 pub fields: IndexMap<String, serde_json::Value>,
2609}
2610
2611impl OtherStateUpdate {
2612 #[must_use]
2614 pub fn new(state: impl Into<String>, mut fields: IndexMap<String, serde_json::Value>) -> Self {
2615 fields.shift_remove("state");
2616 Self {
2617 state: state.into(),
2618 fields,
2619 }
2620 }
2621}
2622
2623impl<'de> Deserialize<'de> for OtherStateUpdate {
2624 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2625 where
2626 D: serde::Deserializer<'de>,
2627 {
2628 let mut fields = IndexMap::<String, serde_json::Value>::deserialize(deserializer)?;
2629 let state = fields
2630 .shift_remove("state")
2631 .ok_or_else(|| serde::de::Error::missing_field("state"))?;
2632 let serde_json::Value::String(state) = state else {
2633 return Err(serde::de::Error::custom("`state` must be a string"));
2634 };
2635
2636 if is_known_state_update(&state) {
2637 return Err(serde::de::Error::custom(format!(
2638 "known state update `{state}` did not match its schema"
2639 )));
2640 }
2641
2642 Ok(Self { state, fields })
2643 }
2644}
2645
2646const KNOWN_STATE_UPDATE_STATES: &[&str] = &["running", "idle", "requires_action", "unknown"];
2647
2648fn is_known_state_update(state: &str) -> bool {
2649 KNOWN_STATE_UPDATE_STATES.contains(&state)
2650}
2651
2652#[cfg(feature = "schemars")]
2653fn other_state_update_schema(schema: &mut Schema) {
2654 super::schema_util::reject_known_string_discriminators(
2655 schema,
2656 "state",
2657 KNOWN_STATE_UPDATE_STATES,
2658 );
2659}
2660
2661#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2671#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2672#[serde(tag = "type", rename_all = "snake_case")]
2673#[non_exhaustive]
2674pub enum BackgroundWork {
2675 Terminal(BackgroundTerminal),
2678 ToolCall(BackgroundToolCall),
2682 Subagent(BackgroundSubagent),
2685 #[serde(untagged)]
2694 Other(OtherBackgroundWork),
2695}
2696
2697#[serde_as]
2699#[skip_serializing_none]
2700#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2701#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2702#[serde(rename_all = "camelCase")]
2703#[non_exhaustive]
2704pub struct BackgroundTerminal {
2705 pub terminal_id: TerminalId,
2707 #[serde_as(deserialize_as = "DefaultOnError")]
2713 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2714 #[serde(default)]
2715 #[serde(rename = "_meta")]
2716 pub meta: Option<Meta>,
2717}
2718
2719impl BackgroundTerminal {
2720 #[must_use]
2722 pub fn new(terminal_id: impl Into<TerminalId>) -> Self {
2723 Self {
2724 terminal_id: terminal_id.into(),
2725 meta: None,
2726 }
2727 }
2728
2729 #[must_use]
2735 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2736 self.meta = meta.into_option();
2737 self
2738 }
2739}
2740
2741#[serde_as]
2743#[skip_serializing_none]
2744#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2745#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2746#[serde(rename_all = "camelCase")]
2747#[non_exhaustive]
2748pub struct BackgroundToolCall {
2749 pub tool_call_id: ToolCallId,
2751 #[serde_as(deserialize_as = "DefaultOnError")]
2757 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2758 #[serde(default)]
2759 #[serde(rename = "_meta")]
2760 pub meta: Option<Meta>,
2761}
2762
2763impl BackgroundToolCall {
2764 #[must_use]
2766 pub fn new(tool_call_id: impl Into<ToolCallId>) -> Self {
2767 Self {
2768 tool_call_id: tool_call_id.into(),
2769 meta: None,
2770 }
2771 }
2772
2773 #[must_use]
2779 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2780 self.meta = meta.into_option();
2781 self
2782 }
2783}
2784
2785#[serde_as]
2787#[skip_serializing_none]
2788#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2789#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2790#[serde(rename_all = "camelCase")]
2791#[non_exhaustive]
2792pub struct BackgroundSubagent {
2793 pub session_id: SessionId,
2795 #[serde_as(deserialize_as = "DefaultOnError")]
2801 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2802 #[serde(default)]
2803 #[serde(rename = "_meta")]
2804 pub meta: Option<Meta>,
2805}
2806
2807impl BackgroundSubagent {
2808 #[must_use]
2810 pub fn new(session_id: impl Into<SessionId>) -> Self {
2811 Self {
2812 session_id: session_id.into(),
2813 meta: None,
2814 }
2815 }
2816
2817 #[must_use]
2823 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2824 self.meta = meta.into_option();
2825 self
2826 }
2827}
2828
2829#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2834#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
2835#[cfg_attr(feature = "schemars", schemars(inline))]
2836#[cfg_attr(feature = "schemars", schemars(transform = other_background_work_schema))]
2837#[serde(rename_all = "camelCase")]
2838#[non_exhaustive]
2839pub struct OtherBackgroundWork {
2840 #[serde(rename = "type")]
2846 pub kind: String,
2847 #[serde(flatten)]
2849 pub fields: IndexMap<String, serde_json::Value>,
2850}
2851
2852impl OtherBackgroundWork {
2853 #[must_use]
2855 pub fn new(kind: impl Into<String>, mut fields: IndexMap<String, serde_json::Value>) -> Self {
2856 fields.shift_remove("type");
2857 Self {
2858 kind: kind.into(),
2859 fields,
2860 }
2861 }
2862}
2863
2864impl<'de> Deserialize<'de> for OtherBackgroundWork {
2865 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2866 where
2867 D: serde::Deserializer<'de>,
2868 {
2869 let mut fields = IndexMap::<String, serde_json::Value>::deserialize(deserializer)?;
2870 let kind = fields
2871 .shift_remove("type")
2872 .ok_or_else(|| serde::de::Error::missing_field("type"))?;
2873 let serde_json::Value::String(kind) = kind else {
2874 return Err(serde::de::Error::custom("`type` must be a string"));
2875 };
2876
2877 if KNOWN_BACKGROUND_WORK_TYPES.contains(&kind.as_str()) {
2878 return Err(serde::de::Error::custom(format!(
2879 "known background work `{kind}` did not match its schema"
2880 )));
2881 }
2882
2883 Ok(Self { kind, fields })
2884 }
2885}
2886
2887const KNOWN_BACKGROUND_WORK_TYPES: &[&str] = &["terminal", "tool_call", "subagent"];
2888
2889#[cfg(feature = "schemars")]
2890fn other_background_work_schema(schema: &mut Schema) {
2891 super::schema_util::reject_known_string_discriminators(
2892 schema,
2893 "type",
2894 KNOWN_BACKGROUND_WORK_TYPES,
2895 );
2896}
2897
2898#[serde_as]
2900#[skip_serializing_none]
2901#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2902#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
2903#[serde(rename_all = "camelCase")]
2904#[non_exhaustive]
2905pub struct Cost {
2906 pub amount: f64,
2908 pub currency: String,
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 Cost {
2924 #[must_use]
2926 pub fn new(amount: f64, currency: impl Into<String>) -> Self {
2927 Self {
2928 amount,
2929 currency: currency.into(),
2930 meta: None,
2931 }
2932 }
2933
2934 #[must_use]
2940 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2941 self.meta = meta.into_option();
2942 self
2943 }
2944}
2945
2946#[serde_as]
2948#[skip_serializing_none]
2949#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2950#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2951#[serde(rename_all = "camelCase")]
2952#[non_exhaustive]
2953pub struct ContentChunk {
2954 pub message_id: MessageId,
2959 pub content: ContentBlock,
2961 #[serde_as(deserialize_as = "DefaultOnError")]
2968 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2969 #[serde(default)]
2970 #[serde(rename = "_meta")]
2971 pub meta: Option<Meta>,
2972}
2973
2974impl ContentChunk {
2975 #[must_use]
2977 pub fn new(content: ContentBlock, message_id: impl Into<MessageId>) -> Self {
2978 Self {
2979 content,
2980 message_id: message_id.into(),
2981 meta: None,
2982 }
2983 }
2984
2985 #[must_use]
2991 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2992 self.meta = meta.into_option();
2993 self
2994 }
2995}
2996
2997#[serde_as]
3011#[skip_serializing_none]
3012#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3013#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3014#[serde(rename_all = "camelCase")]
3015#[non_exhaustive]
3016pub struct UserMessage {
3017 pub message_id: MessageId,
3019 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<VecSkipError<_>>>")]
3021 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
3022 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
3023 pub content: MaybeUndefined<Vec<ContentBlock>>,
3024 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
3033 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3034 #[serde(
3035 rename = "_meta",
3036 default,
3037 skip_serializing_if = "MaybeUndefined::is_undefined"
3038 )]
3039 pub meta: MaybeUndefined<Meta>,
3040}
3041
3042impl UserMessage {
3043 #[must_use]
3045 pub fn new(message_id: impl Into<MessageId>) -> Self {
3046 Self {
3047 message_id: message_id.into(),
3048 content: MaybeUndefined::Undefined,
3049 meta: MaybeUndefined::Undefined,
3050 }
3051 }
3052
3053 #[must_use]
3055 pub fn content(mut self, content: impl IntoMaybeUndefined<Vec<ContentBlock>>) -> Self {
3056 self.content = content.into_maybe_undefined();
3057 self
3058 }
3059
3060 #[must_use]
3065 pub fn meta(mut self, meta: impl IntoMaybeUndefined<Meta>) -> Self {
3066 self.meta = meta.into_maybe_undefined();
3067 self
3068 }
3069}
3070
3071#[serde_as]
3085#[skip_serializing_none]
3086#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3087#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3088#[serde(rename_all = "camelCase")]
3089#[non_exhaustive]
3090pub struct AgentMessage {
3091 pub message_id: MessageId,
3093 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<VecSkipError<_>>>")]
3095 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
3096 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
3097 pub content: MaybeUndefined<Vec<ContentBlock>>,
3098 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
3107 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3108 #[serde(
3109 rename = "_meta",
3110 default,
3111 skip_serializing_if = "MaybeUndefined::is_undefined"
3112 )]
3113 pub meta: MaybeUndefined<Meta>,
3114}
3115
3116impl AgentMessage {
3117 #[must_use]
3119 pub fn new(message_id: impl Into<MessageId>) -> Self {
3120 Self {
3121 message_id: message_id.into(),
3122 content: MaybeUndefined::Undefined,
3123 meta: MaybeUndefined::Undefined,
3124 }
3125 }
3126
3127 #[must_use]
3129 pub fn content(mut self, content: impl IntoMaybeUndefined<Vec<ContentBlock>>) -> Self {
3130 self.content = content.into_maybe_undefined();
3131 self
3132 }
3133
3134 #[must_use]
3139 pub fn meta(mut self, meta: impl IntoMaybeUndefined<Meta>) -> Self {
3140 self.meta = meta.into_maybe_undefined();
3141 self
3142 }
3143}
3144
3145#[serde_as]
3159#[skip_serializing_none]
3160#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3161#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3162#[serde(rename_all = "camelCase")]
3163#[non_exhaustive]
3164pub struct AgentThought {
3165 pub message_id: MessageId,
3167 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<VecSkipError<_>>>")]
3169 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
3170 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
3171 pub content: MaybeUndefined<Vec<ContentBlock>>,
3172 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
3181 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3182 #[serde(
3183 rename = "_meta",
3184 default,
3185 skip_serializing_if = "MaybeUndefined::is_undefined"
3186 )]
3187 pub meta: MaybeUndefined<Meta>,
3188}
3189
3190impl AgentThought {
3191 #[must_use]
3193 pub fn new(message_id: impl Into<MessageId>) -> Self {
3194 Self {
3195 message_id: message_id.into(),
3196 content: MaybeUndefined::Undefined,
3197 meta: MaybeUndefined::Undefined,
3198 }
3199 }
3200
3201 #[must_use]
3203 pub fn content(mut self, content: impl IntoMaybeUndefined<Vec<ContentBlock>>) -> Self {
3204 self.content = content.into_maybe_undefined();
3205 self
3206 }
3207
3208 #[must_use]
3213 pub fn meta(mut self, meta: impl IntoMaybeUndefined<Meta>) -> Self {
3214 self.meta = meta.into_maybe_undefined();
3215 self
3216 }
3217}
3218
3219#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3225#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
3226#[serde(transparent)]
3227#[from(forward)]
3228#[non_exhaustive]
3229pub struct MessageId(pub Arc<str>);
3230
3231impl MessageId {
3232 #[must_use]
3234 pub fn new(id: impl Into<Self>) -> Self {
3235 id.into()
3236 }
3237}
3238
3239#[cfg(feature = "unstable_prompt_suggestions")]
3256#[serde_as]
3257#[skip_serializing_none]
3258#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3259#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3260#[serde(rename_all = "camelCase")]
3261#[non_exhaustive]
3262pub struct PromptSuggestionsUpdate {
3263 #[serde_as(deserialize_as = "VecSkipError<_>")]
3268 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-skip-invalid-items" = true)))]
3269 pub suggestions: Vec<PromptSuggestion>,
3270 #[serde_as(deserialize_as = "DefaultOnError")]
3276 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3277 #[serde(default)]
3278 #[serde(rename = "_meta")]
3279 pub meta: Option<Meta>,
3280}
3281
3282#[cfg(feature = "unstable_prompt_suggestions")]
3283impl PromptSuggestionsUpdate {
3284 #[must_use]
3288 pub fn new(suggestions: Vec<PromptSuggestion>) -> Self {
3289 Self {
3290 suggestions,
3291 meta: None,
3292 }
3293 }
3294
3295 #[must_use]
3301 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3302 self.meta = meta.into_option();
3303 self
3304 }
3305}
3306
3307#[cfg(feature = "unstable_prompt_suggestions")]
3313#[serde_as]
3314#[skip_serializing_none]
3315#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3316#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3317#[serde(rename_all = "camelCase")]
3318#[non_exhaustive]
3319pub struct PromptSuggestion {
3320 #[cfg_attr(feature = "schemars", schemars(length(min = 1)))]
3332 pub prompt: Vec<ContentBlock>,
3333 #[serde_as(deserialize_as = "DefaultOnError")]
3339 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3340 #[serde(default)]
3341 #[serde(rename = "_meta")]
3342 pub meta: Option<Meta>,
3343}
3344
3345#[cfg(feature = "unstable_prompt_suggestions")]
3346impl PromptSuggestion {
3347 #[must_use]
3349 pub fn new(prompt: Vec<ContentBlock>) -> Self {
3350 Self { prompt, meta: None }
3351 }
3352
3353 #[must_use]
3359 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3360 self.meta = meta.into_option();
3361 self
3362 }
3363}
3364
3365#[serde_as]
3367#[skip_serializing_none]
3368#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3369#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3370#[serde(rename_all = "camelCase")]
3371#[non_exhaustive]
3372pub struct AvailableCommandsUpdate {
3373 #[serde_as(deserialize_as = "VecSkipError<_>")]
3375 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-skip-invalid-items" = true)))]
3376 pub available_commands: Vec<AvailableCommand>,
3377 #[serde_as(deserialize_as = "DefaultOnError")]
3383 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3384 #[serde(default)]
3385 #[serde(rename = "_meta")]
3386 pub meta: Option<Meta>,
3387}
3388
3389impl AvailableCommandsUpdate {
3390 #[must_use]
3392 pub fn new(available_commands: Vec<AvailableCommand>) -> Self {
3393 Self {
3394 available_commands,
3395 meta: None,
3396 }
3397 }
3398
3399 #[must_use]
3405 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3406 self.meta = meta.into_option();
3407 self
3408 }
3409}
3410
3411#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3415#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3416#[serde(tag = "type", rename_all = "snake_case")]
3417#[non_exhaustive]
3418pub enum AvailableCommand {
3419 Command(Command),
3421 #[cfg(feature = "unstable_agent_skills")]
3430 Skill(Skill),
3431 #[serde(untagged)]
3442 Other(OtherAvailableCommand),
3443}
3444
3445impl AvailableCommand {
3446 #[must_use]
3448 pub fn name(&self) -> &str {
3449 match self {
3450 Self::Command(c) => &c.name,
3451 #[cfg(feature = "unstable_agent_skills")]
3452 Self::Skill(c) => &c.name,
3453 Self::Other(c) => &c.name,
3454 }
3455 }
3456
3457 #[must_use]
3460 pub fn description(&self) -> &str {
3461 match self {
3462 Self::Command(c) => &c.description,
3463 #[cfg(feature = "unstable_agent_skills")]
3464 Self::Skill(c) => &c.description,
3465 Self::Other(c) => &c.description,
3466 }
3467 }
3468
3469 #[must_use]
3475 pub fn meta(&self) -> Option<&Meta> {
3476 match self {
3477 Self::Command(c) => c.meta.as_ref(),
3478 #[cfg(feature = "unstable_agent_skills")]
3479 Self::Skill(c) => c.meta.as_ref(),
3480 Self::Other(c) => c.fields.get("_meta").and_then(serde_json::Value::as_object),
3481 }
3482 }
3483}
3484
3485#[serde_as]
3487#[skip_serializing_none]
3488#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3489#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
3490#[cfg_attr(feature = "schemars", schemars(inline))]
3491#[cfg_attr(feature = "schemars", schemars(transform = other_available_command_schema))]
3492#[serde(rename_all = "camelCase")]
3493#[non_exhaustive]
3494pub struct OtherAvailableCommand {
3495 #[serde(rename = "type")]
3501 pub type_: String,
3502 pub name: String,
3504 pub description: String,
3507 #[serde(flatten)]
3510 pub fields: IndexMap<String, serde_json::Value>,
3511}
3512
3513impl OtherAvailableCommand {
3514 #[must_use]
3516 pub fn new(
3517 type_: impl Into<String>,
3518 name: impl Into<String>,
3519 description: impl Into<String>,
3520 mut fields: IndexMap<String, serde_json::Value>,
3521 ) -> Self {
3522 fields.shift_remove("type");
3523 fields.shift_remove("name");
3524 fields.shift_remove("description");
3525 Self {
3526 type_: type_.into(),
3527 name: name.into(),
3528 description: description.into(),
3529 fields,
3530 }
3531 }
3532}
3533
3534impl<'de> Deserialize<'de> for OtherAvailableCommand {
3535 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
3536 where
3537 D: serde::Deserializer<'de>,
3538 {
3539 #[derive(Deserialize)]
3540 struct RawOtherAvailableCommand {
3541 #[serde(rename = "type")]
3542 type_: String,
3543 name: String,
3544 description: String,
3545 #[serde(flatten)]
3546 fields: IndexMap<String, serde_json::Value>,
3547 }
3548
3549 let raw = RawOtherAvailableCommand::deserialize(deserializer)?;
3550 if is_known_available_command_type(&raw.type_) {
3551 return Err(serde::de::Error::custom(format!(
3552 "known available command type `{}` did not match its schema",
3553 raw.type_
3554 )));
3555 }
3556
3557 Ok(Self {
3558 type_: raw.type_,
3559 name: raw.name,
3560 description: raw.description,
3561 fields: raw.fields,
3562 })
3563 }
3564}
3565
3566const KNOWN_AVAILABLE_COMMAND_TYPES: &[&str] = &[
3567 "command",
3568 #[cfg(feature = "unstable_agent_skills")]
3569 "skill",
3570];
3571
3572fn is_known_available_command_type(type_: &str) -> bool {
3573 KNOWN_AVAILABLE_COMMAND_TYPES.contains(&type_)
3574}
3575
3576#[cfg(feature = "schemars")]
3577fn other_available_command_schema(schema: &mut Schema) {
3578 super::schema_util::reject_known_string_discriminators(
3579 schema,
3580 "type",
3581 KNOWN_AVAILABLE_COMMAND_TYPES,
3582 );
3583}
3584
3585#[serde_as]
3589#[skip_serializing_none]
3590#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3591#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3592#[serde(rename_all = "camelCase")]
3593#[non_exhaustive]
3594pub struct Command {
3595 pub name: String,
3599 pub description: String,
3602 #[serde_as(deserialize_as = "DefaultOnError")]
3606 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3607 #[serde(default)]
3608 pub input: Option<AvailableCommandInput>,
3609 #[serde_as(deserialize_as = "DefaultOnError")]
3615 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3616 #[serde(default)]
3617 #[serde(rename = "_meta")]
3618 pub meta: Option<Meta>,
3619}
3620
3621impl Command {
3622 #[must_use]
3624 pub fn new(name: impl Into<String>, description: impl Into<String>) -> Self {
3625 Self {
3626 name: name.into(),
3627 description: description.into(),
3628 input: None,
3629 meta: None,
3630 }
3631 }
3632
3633 #[must_use]
3635 pub fn input(mut self, input: impl IntoOption<AvailableCommandInput>) -> Self {
3636 self.input = input.into_option();
3637 self
3638 }
3639
3640 #[must_use]
3646 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3647 self.meta = meta.into_option();
3648 self
3649 }
3650}
3651
3652#[cfg(feature = "unstable_agent_skills")]
3668#[serde_as]
3669#[skip_serializing_none]
3670#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3671#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3672#[serde(rename_all = "camelCase")]
3673#[non_exhaustive]
3674pub struct Skill {
3675 pub name: String,
3681 pub description: String,
3684 #[serde_as(deserialize_as = "DefaultOnError")]
3690 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3691 #[serde(default)]
3692 pub path: Option<AbsolutePath>,
3693 #[serde_as(deserialize_as = "DefaultOnError")]
3699 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3700 #[serde(default)]
3701 #[serde(rename = "_meta")]
3702 pub meta: Option<Meta>,
3703}
3704
3705#[cfg(feature = "unstable_agent_skills")]
3706impl Skill {
3707 #[must_use]
3709 pub fn new(name: impl Into<String>, description: impl Into<String>) -> Self {
3710 Self {
3711 name: name.into(),
3712 description: description.into(),
3713 path: None,
3714 meta: None,
3715 }
3716 }
3717
3718 #[must_use]
3721 pub fn path(mut self, path: impl IntoOption<AbsolutePath>) -> Self {
3722 self.path = path.into_option();
3723 self
3724 }
3725
3726 #[must_use]
3732 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3733 self.meta = meta.into_option();
3734 self
3735 }
3736}
3737
3738#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3740#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3741#[serde(tag = "type", rename_all = "snake_case")]
3742#[non_exhaustive]
3743pub enum AvailableCommandInput {
3744 #[serde(rename = "text")]
3746 Text(TextCommandInput),
3747 #[serde(untagged)]
3758 Other(OtherAvailableCommandInput),
3759}
3760
3761#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3763#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
3764#[cfg_attr(feature = "schemars", schemars(inline))]
3765#[cfg_attr(feature = "schemars", schemars(transform = other_available_command_input_schema))]
3766#[serde(rename_all = "camelCase")]
3767#[non_exhaustive]
3768pub struct OtherAvailableCommandInput {
3769 #[serde(rename = "type")]
3775 pub type_: String,
3776 #[serde(flatten)]
3778 pub fields: IndexMap<String, serde_json::Value>,
3779}
3780
3781impl OtherAvailableCommandInput {
3782 #[must_use]
3784 pub fn new(type_: impl Into<String>, mut fields: IndexMap<String, serde_json::Value>) -> Self {
3785 fields.shift_remove("type");
3786 Self {
3787 type_: type_.into(),
3788 fields,
3789 }
3790 }
3791}
3792
3793impl<'de> Deserialize<'de> for OtherAvailableCommandInput {
3794 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
3795 where
3796 D: serde::Deserializer<'de>,
3797 {
3798 let mut fields = IndexMap::<String, serde_json::Value>::deserialize(deserializer)?;
3799 let type_ = fields
3800 .shift_remove("type")
3801 .ok_or_else(|| serde::de::Error::missing_field("type"))?;
3802 let serde_json::Value::String(type_) = type_ else {
3803 return Err(serde::de::Error::custom("`type` must be a string"));
3804 };
3805
3806 if is_known_available_command_input_type(&type_) {
3807 return Err(serde::de::Error::custom(format!(
3808 "known available command input type `{type_}` did not match its schema"
3809 )));
3810 }
3811
3812 Ok(Self { type_, fields })
3813 }
3814}
3815
3816const KNOWN_AVAILABLE_COMMAND_INPUT_TYPES: &[&str] = &["text"];
3817
3818fn is_known_available_command_input_type(type_: &str) -> bool {
3819 KNOWN_AVAILABLE_COMMAND_INPUT_TYPES.contains(&type_)
3820}
3821
3822#[cfg(feature = "schemars")]
3823fn other_available_command_input_schema(schema: &mut Schema) {
3824 super::schema_util::reject_known_string_discriminators(
3825 schema,
3826 "type",
3827 KNOWN_AVAILABLE_COMMAND_INPUT_TYPES,
3828 );
3829}
3830
3831#[serde_as]
3833#[skip_serializing_none]
3834#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3835#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3836#[serde(rename_all = "camelCase")]
3837#[non_exhaustive]
3838pub struct TextCommandInput {
3839 pub hint: String,
3841 #[serde_as(deserialize_as = "DefaultOnError")]
3847 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3848 #[serde(default)]
3849 #[serde(rename = "_meta")]
3850 pub meta: Option<Meta>,
3851}
3852
3853impl TextCommandInput {
3854 #[must_use]
3856 pub fn new(hint: impl Into<String>) -> Self {
3857 Self {
3858 hint: hint.into(),
3859 meta: None,
3860 }
3861 }
3862
3863 #[must_use]
3869 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3870 self.meta = meta.into_option();
3871 self
3872 }
3873}
3874
3875#[serde_as]
3883#[skip_serializing_none]
3884#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3885#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3886#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = SESSION_REQUEST_PERMISSION_METHOD_NAME)))]
3887#[cfg_attr(feature = "schemars", schemars(extend("x-scope" = {"session": ["sessionId"], "toolCall": ["subject.toolCall.toolCallId", "subject.toolCallId"]})))]
3888#[cfg_attr(feature = "schemars", schemars(extend("x-state" = {"session": [{"action": "upsert", "target": "toolCall", "id": "subject.toolCall.toolCallId", "value": "subject.toolCall"}]})))]
3889#[serde(rename_all = "camelCase")]
3890#[non_exhaustive]
3891pub struct RequestPermissionRequest {
3892 pub session_id: SessionId,
3894 pub title: String,
3899 #[serde_as(deserialize_as = "DefaultOnError")]
3906 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3907 #[serde(default)]
3908 pub description: Option<String>,
3909 #[serde(default)]
3913 pub subject: Option<RequestPermissionSubject>,
3914 #[cfg_attr(feature = "schemars", schemars(length(min = 1)))]
3917 #[serde(deserialize_with = "deserialize_permission_options")]
3918 pub options: Vec<PermissionOption>,
3919 #[serde_as(deserialize_as = "DefaultOnError")]
3925 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3926 #[serde(default)]
3927 #[serde(rename = "_meta")]
3928 pub meta: Option<Meta>,
3929}
3930
3931fn deserialize_permission_options<'de, D>(
3934 deserializer: D,
3935) -> Result<Vec<PermissionOption>, D::Error>
3936where
3937 D: serde::Deserializer<'de>,
3938{
3939 let options = Vec::<PermissionOption>::deserialize(deserializer)?;
3940 if options.is_empty() {
3941 return Err(serde::de::Error::invalid_length(
3942 0,
3943 &"at least one permission option",
3944 ));
3945 }
3946 Ok(options)
3947}
3948
3949impl RequestPermissionRequest {
3950 #[must_use]
3952 pub fn new(
3953 session_id: impl Into<SessionId>,
3954 title: impl Into<String>,
3955 options: Vec<PermissionOption>,
3956 ) -> Self {
3957 Self {
3958 session_id: session_id.into(),
3959 title: title.into(),
3960 description: None,
3961 subject: None,
3962 options,
3963 meta: None,
3964 }
3965 }
3966
3967 #[must_use]
3969 pub fn description(mut self, description: impl IntoOption<String>) -> Self {
3970 self.description = description.into_option();
3971 self
3972 }
3973
3974 #[must_use]
3976 pub fn subject(mut self, subject: impl IntoOption<RequestPermissionSubject>) -> Self {
3977 self.subject = subject.into_option();
3978 self
3979 }
3980
3981 #[must_use]
3987 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3988 self.meta = meta.into_option();
3989 self
3990 }
3991}
3992
3993#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3995#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3996#[serde(tag = "type", rename_all = "snake_case")]
3997#[non_exhaustive]
3998pub enum RequestPermissionSubject {
3999 ToolCall(Box<ToolCallPermissionSubject>),
4001 Command(CommandPermissionSubject),
4003 #[serde(untagged)]
4014 Other(OtherRequestPermissionSubject),
4015}
4016
4017impl From<ToolCallPermissionSubject> for RequestPermissionSubject {
4018 fn from(subject: ToolCallPermissionSubject) -> Self {
4019 Self::ToolCall(Box::new(subject))
4020 }
4021}
4022
4023impl From<ToolCallUpdate> for RequestPermissionSubject {
4024 fn from(tool_call: ToolCallUpdate) -> Self {
4025 ToolCallPermissionSubject::new(tool_call).into()
4026 }
4027}
4028
4029impl From<CommandPermissionSubject> for RequestPermissionSubject {
4030 fn from(subject: CommandPermissionSubject) -> Self {
4031 Self::Command(subject)
4032 }
4033}
4034
4035#[serde_as]
4037#[skip_serializing_none]
4038#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4039#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4040#[serde(rename_all = "camelCase")]
4041#[non_exhaustive]
4042pub struct ToolCallPermissionSubject {
4043 pub tool_call: ToolCallUpdate,
4049 #[serde_as(deserialize_as = "DefaultOnError")]
4055 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4056 #[serde(default)]
4057 #[serde(rename = "_meta")]
4058 pub meta: Option<Meta>,
4059}
4060
4061impl ToolCallPermissionSubject {
4062 #[must_use]
4064 pub fn new(tool_call: ToolCallUpdate) -> Self {
4065 Self {
4066 tool_call,
4067 meta: None,
4068 }
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(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4088#[serde(rename_all = "camelCase")]
4089#[non_exhaustive]
4090pub struct CommandPermissionSubject {
4091 pub command: String,
4093 pub cwd: AbsolutePath,
4095 #[serde_as(deserialize_as = "DefaultOnError")]
4097 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4098 #[serde(default)]
4099 pub tool_call_id: Option<ToolCallId>,
4100 #[serde_as(deserialize_as = "DefaultOnError")]
4102 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4103 #[serde(default)]
4104 pub terminal_id: Option<TerminalId>,
4105 #[serde_as(deserialize_as = "DefaultOnError")]
4111 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4112 #[serde(default)]
4113 #[serde(rename = "_meta")]
4114 pub meta: Option<Meta>,
4115}
4116
4117impl CommandPermissionSubject {
4118 #[must_use]
4120 pub fn new(command: impl Into<String>, cwd: impl Into<AbsolutePath>) -> Self {
4121 Self {
4122 command: command.into(),
4123 cwd: cwd.into(),
4124 tool_call_id: None,
4125 terminal_id: None,
4126 meta: None,
4127 }
4128 }
4129
4130 #[must_use]
4132 pub fn tool_call_id(mut self, tool_call_id: impl IntoOption<ToolCallId>) -> Self {
4133 self.tool_call_id = tool_call_id.into_option();
4134 self
4135 }
4136
4137 #[must_use]
4139 pub fn terminal_id(mut self, terminal_id: impl IntoOption<TerminalId>) -> Self {
4140 self.terminal_id = terminal_id.into_option();
4141 self
4142 }
4143
4144 #[must_use]
4146 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4147 self.meta = meta.into_option();
4148 self
4149 }
4150}
4151
4152#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4154#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
4155#[cfg_attr(feature = "schemars", schemars(inline))]
4156#[cfg_attr(feature = "schemars", schemars(transform = other_request_permission_subject_schema))]
4157#[serde(rename_all = "camelCase")]
4158#[non_exhaustive]
4159pub struct OtherRequestPermissionSubject {
4160 #[serde(rename = "type")]
4166 pub type_: String,
4167 #[serde(flatten)]
4169 pub fields: IndexMap<String, serde_json::Value>,
4170}
4171
4172impl OtherRequestPermissionSubject {
4173 #[must_use]
4175 pub fn new(type_: impl Into<String>, mut fields: IndexMap<String, serde_json::Value>) -> Self {
4176 fields.shift_remove("type");
4177 Self {
4178 type_: type_.into(),
4179 fields,
4180 }
4181 }
4182}
4183
4184impl<'de> Deserialize<'de> for OtherRequestPermissionSubject {
4185 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
4186 where
4187 D: serde::Deserializer<'de>,
4188 {
4189 let mut fields = IndexMap::<String, serde_json::Value>::deserialize(deserializer)?;
4190 let type_ = fields
4191 .shift_remove("type")
4192 .ok_or_else(|| serde::de::Error::missing_field("type"))?;
4193 let serde_json::Value::String(type_) = type_ else {
4194 return Err(serde::de::Error::custom("`type` must be a string"));
4195 };
4196
4197 if is_known_request_permission_subject_type(&type_) {
4198 return Err(serde::de::Error::custom(format!(
4199 "known request permission subject `{type_}` did not match its schema"
4200 )));
4201 }
4202
4203 Ok(Self { type_, fields })
4204 }
4205}
4206
4207fn is_known_request_permission_subject_type(type_: &str) -> bool {
4208 matches!(type_, "tool_call" | "command")
4209}
4210
4211#[cfg(feature = "schemars")]
4212fn other_request_permission_subject_schema(schema: &mut Schema) {
4213 super::schema_util::reject_known_string_discriminators(
4214 schema,
4215 "type",
4216 &["tool_call", "command"],
4217 );
4218}
4219
4220#[serde_as]
4222#[skip_serializing_none]
4223#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4224#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4225#[serde(rename_all = "camelCase")]
4226#[non_exhaustive]
4227pub struct PermissionOption {
4228 pub option_id: PermissionOptionId,
4230 pub name: String,
4232 pub kind: PermissionOptionKind,
4234 #[serde_as(deserialize_as = "DefaultOnError")]
4240 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4241 #[serde(default)]
4242 #[serde(rename = "_meta")]
4243 pub meta: Option<Meta>,
4244}
4245
4246impl PermissionOption {
4247 #[must_use]
4249 pub fn new(
4250 option_id: impl Into<PermissionOptionId>,
4251 name: impl Into<String>,
4252 kind: PermissionOptionKind,
4253 ) -> Self {
4254 Self {
4255 option_id: option_id.into(),
4256 name: name.into(),
4257 kind,
4258 meta: None,
4259 }
4260 }
4261
4262 #[must_use]
4268 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4269 self.meta = meta.into_option();
4270 self
4271 }
4272}
4273
4274#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4276#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
4277#[serde(transparent)]
4278#[from(forward)]
4279#[non_exhaustive]
4280pub struct PermissionOptionId(pub Arc<str>);
4281
4282impl PermissionOptionId {
4283 #[must_use]
4285 pub fn new(id: impl Into<Self>) -> Self {
4286 id.into()
4287 }
4288}
4289
4290#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4296#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4297#[serde(rename_all = "snake_case")]
4298#[non_exhaustive]
4299pub enum PermissionOptionKind {
4300 AllowOnce,
4302 AllowAlways,
4304 RejectOnce,
4306 RejectAlways,
4308 #[serde(untagged)]
4314 Other(String),
4315}
4316
4317#[serde_as]
4319#[skip_serializing_none]
4320#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4321#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4322#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = SESSION_REQUEST_PERMISSION_METHOD_NAME)))]
4323#[serde(rename_all = "camelCase")]
4324#[non_exhaustive]
4325pub struct RequestPermissionResponse {
4326 pub outcome: RequestPermissionOutcome,
4328 #[serde_as(deserialize_as = "DefaultOnError")]
4334 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4335 #[serde(default)]
4336 #[serde(rename = "_meta")]
4337 pub meta: Option<Meta>,
4338}
4339
4340impl RequestPermissionResponse {
4341 #[must_use]
4343 pub fn new(outcome: RequestPermissionOutcome) -> Self {
4344 Self {
4345 outcome,
4346 meta: None,
4347 }
4348 }
4349
4350 #[must_use]
4356 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4357 self.meta = meta.into_option();
4358 self
4359 }
4360}
4361
4362#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4364#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4365#[serde(tag = "outcome", rename_all = "snake_case")]
4366#[non_exhaustive]
4367pub enum RequestPermissionOutcome {
4368 Cancelled(CancelledPermissionOutcome),
4379 #[serde(rename_all = "camelCase")]
4386 Selected(SelectedPermissionOutcome),
4387 #[serde(untagged)]
4398 Other(OtherRequestPermissionOutcome),
4399}
4400
4401#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4407#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
4408#[cfg_attr(feature = "schemars", schemars(inline))]
4409#[cfg_attr(feature = "schemars", schemars(transform = other_request_permission_outcome_schema))]
4410#[serde(rename_all = "camelCase")]
4411#[non_exhaustive]
4412pub struct OtherRequestPermissionOutcome {
4413 pub outcome: String,
4419 #[serde(flatten)]
4421 pub fields: IndexMap<String, serde_json::Value>,
4422}
4423
4424impl OtherRequestPermissionOutcome {
4425 #[must_use]
4427 pub fn new(
4428 outcome: impl Into<String>,
4429 mut fields: IndexMap<String, serde_json::Value>,
4430 ) -> Self {
4431 fields.shift_remove("outcome");
4432 Self {
4433 outcome: outcome.into(),
4434 fields,
4435 }
4436 }
4437}
4438
4439impl<'de> Deserialize<'de> for OtherRequestPermissionOutcome {
4440 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
4441 where
4442 D: serde::Deserializer<'de>,
4443 {
4444 let mut fields = IndexMap::<String, serde_json::Value>::deserialize(deserializer)?;
4445 let outcome = fields
4446 .shift_remove("outcome")
4447 .ok_or_else(|| serde::de::Error::missing_field("outcome"))?;
4448 let serde_json::Value::String(outcome) = outcome else {
4449 return Err(serde::de::Error::custom("`outcome` must be a string"));
4450 };
4451
4452 if is_known_request_permission_outcome(&outcome) {
4453 return Err(serde::de::Error::custom(format!(
4454 "known request permission outcome `{outcome}` did not match its schema"
4455 )));
4456 }
4457
4458 Ok(Self { outcome, fields })
4459 }
4460}
4461
4462fn is_known_request_permission_outcome(outcome: &str) -> bool {
4463 matches!(outcome, "cancelled" | "selected")
4464}
4465
4466#[cfg(feature = "schemars")]
4467fn other_request_permission_outcome_schema(schema: &mut Schema) {
4468 super::schema_util::reject_known_string_discriminators(
4469 schema,
4470 "outcome",
4471 &["cancelled", "selected"],
4472 );
4473}
4474
4475#[serde_as]
4477#[skip_serializing_none]
4478#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4479#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4480#[serde(rename_all = "camelCase")]
4481#[non_exhaustive]
4482pub struct CancelledPermissionOutcome {
4483 #[serde_as(deserialize_as = "DefaultOnError")]
4489 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4490 #[serde(default)]
4491 #[serde(rename = "_meta")]
4492 pub meta: Option<Meta>,
4493}
4494
4495impl CancelledPermissionOutcome {
4496 #[must_use]
4498 pub fn new() -> Self {
4499 Self::default()
4500 }
4501
4502 #[must_use]
4508 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4509 self.meta = meta.into_option();
4510 self
4511 }
4512}
4513
4514impl From<CancelledPermissionOutcome> for RequestPermissionOutcome {
4515 fn from(outcome: CancelledPermissionOutcome) -> Self {
4516 Self::Cancelled(outcome)
4517 }
4518}
4519
4520#[serde_as]
4522#[skip_serializing_none]
4523#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4524#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4525#[serde(rename_all = "camelCase")]
4526#[non_exhaustive]
4527pub struct SelectedPermissionOutcome {
4528 pub option_id: PermissionOptionId,
4530 #[serde_as(deserialize_as = "DefaultOnError")]
4536 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4537 #[serde(default)]
4538 #[serde(rename = "_meta")]
4539 pub meta: Option<Meta>,
4540}
4541
4542impl SelectedPermissionOutcome {
4543 #[must_use]
4545 pub fn new(option_id: impl Into<PermissionOptionId>) -> Self {
4546 Self {
4547 option_id: option_id.into(),
4548 meta: None,
4549 }
4550 }
4551
4552 #[must_use]
4558 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4559 self.meta = meta.into_option();
4560 self
4561 }
4562}
4563
4564#[serde_as]
4573#[skip_serializing_none]
4574#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4575#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4576#[serde(rename_all = "camelCase")]
4577#[non_exhaustive]
4578pub struct ClientCapabilities {
4579 #[serde_as(deserialize_as = "DefaultOnError")]
4586 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4587 #[serde(default)]
4588 pub auth: Option<ClientAuthCapabilities>,
4589 #[serde_as(deserialize_as = "DefaultOnError")]
4595 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4596 #[serde(default)]
4597 pub elicitation: Option<ElicitationCapabilities>,
4598 #[cfg(any(
4608 feature = "unstable_prompt_suggestions",
4609 feature = "unstable_agent_skills"
4610 ))]
4611 #[serde_as(deserialize_as = "DefaultOnError")]
4612 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4613 #[serde(default)]
4614 pub session: Option<ClientSessionCapabilities>,
4615
4616 #[serde_as(deserialize_as = "DefaultOnError")]
4622 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4623 #[serde(default)]
4624 #[serde(rename = "_meta")]
4625 pub meta: Option<Meta>,
4626}
4627
4628impl ClientCapabilities {
4629 #[must_use]
4631 pub fn new() -> Self {
4632 Self::default()
4633 }
4634
4635 #[must_use]
4639 pub fn auth(mut self, auth: impl IntoOption<ClientAuthCapabilities>) -> Self {
4640 self.auth = auth.into_option();
4641 self
4642 }
4643
4644 #[must_use]
4647 pub fn elicitation(mut self, elicitation: impl IntoOption<ElicitationCapabilities>) -> Self {
4648 self.elicitation = elicitation.into_option();
4649 self
4650 }
4651
4652 #[cfg(any(
4658 feature = "unstable_prompt_suggestions",
4659 feature = "unstable_agent_skills"
4660 ))]
4661 #[must_use]
4662 pub fn session(mut self, session: impl IntoOption<ClientSessionCapabilities>) -> Self {
4663 self.session = session.into_option();
4664 self
4665 }
4666
4667 #[must_use]
4673 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4674 self.meta = meta.into_option();
4675 self
4676 }
4677}
4678
4679#[cfg(any(
4689 feature = "unstable_prompt_suggestions",
4690 feature = "unstable_agent_skills"
4691))]
4692#[serde_as]
4693#[skip_serializing_none]
4694#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4695#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4696#[serde(rename_all = "camelCase")]
4697#[non_exhaustive]
4698pub struct ClientSessionCapabilities {
4699 #[cfg(feature = "unstable_prompt_suggestions")]
4705 #[serde_as(deserialize_as = "DefaultOnError")]
4706 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4707 #[serde(default)]
4708 pub prompt_suggestions: Option<PromptSuggestionsCapabilities>,
4709 #[cfg(feature = "unstable_agent_skills")]
4714 #[serde_as(deserialize_as = "DefaultOnError")]
4715 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4716 #[serde(default)]
4717 pub commands: Option<CommandsCapabilities>,
4718 #[serde_as(deserialize_as = "DefaultOnError")]
4724 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4725 #[serde(default)]
4726 #[serde(rename = "_meta")]
4727 pub meta: Option<Meta>,
4728}
4729
4730#[cfg(any(
4731 feature = "unstable_prompt_suggestions",
4732 feature = "unstable_agent_skills"
4733))]
4734impl ClientSessionCapabilities {
4735 #[must_use]
4737 pub fn new() -> Self {
4738 Self::default()
4739 }
4740
4741 #[cfg(feature = "unstable_prompt_suggestions")]
4743 #[must_use]
4744 pub fn prompt_suggestions(
4745 mut self,
4746 prompt_suggestions: impl IntoOption<PromptSuggestionsCapabilities>,
4747 ) -> Self {
4748 self.prompt_suggestions = prompt_suggestions.into_option();
4749 self
4750 }
4751
4752 #[cfg(feature = "unstable_agent_skills")]
4754 #[must_use]
4755 pub fn commands(mut self, commands: impl IntoOption<CommandsCapabilities>) -> Self {
4756 self.commands = commands.into_option();
4757 self
4758 }
4759
4760 #[must_use]
4766 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4767 self.meta = meta.into_option();
4768 self
4769 }
4770}
4771
4772#[cfg(feature = "unstable_agent_skills")]
4782#[serde_as]
4783#[skip_serializing_none]
4784#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4785#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4786#[serde(rename_all = "camelCase")]
4787#[non_exhaustive]
4788pub struct CommandsCapabilities {
4789 #[serde_as(deserialize_as = "DefaultOnError")]
4795 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4796 #[serde(default)]
4797 pub skill: Option<CommandsSkillCapabilities>,
4798 #[serde_as(deserialize_as = "DefaultOnError")]
4804 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4805 #[serde(default)]
4806 #[serde(rename = "_meta")]
4807 pub meta: Option<Meta>,
4808}
4809
4810#[cfg(feature = "unstable_agent_skills")]
4811impl CommandsCapabilities {
4812 #[must_use]
4814 pub fn new() -> Self {
4815 Self::default()
4816 }
4817
4818 #[must_use]
4820 pub fn skill(mut self, skill: impl IntoOption<CommandsSkillCapabilities>) -> Self {
4821 self.skill = skill.into_option();
4822 self
4823 }
4824
4825 #[must_use]
4831 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4832 self.meta = meta.into_option();
4833 self
4834 }
4835}
4836
4837#[cfg(feature = "unstable_agent_skills")]
4846#[serde_as]
4847#[skip_serializing_none]
4848#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4849#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4850#[non_exhaustive]
4851pub struct CommandsSkillCapabilities {
4852 #[serde_as(deserialize_as = "DefaultOnError")]
4858 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4859 #[serde(default)]
4860 #[serde(rename = "_meta")]
4861 pub meta: Option<Meta>,
4862}
4863
4864#[cfg(feature = "unstable_agent_skills")]
4865impl CommandsSkillCapabilities {
4866 #[must_use]
4868 pub fn new() -> Self {
4869 Self::default()
4870 }
4871
4872 #[must_use]
4878 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4879 self.meta = meta.into_option();
4880 self
4881 }
4882}
4883
4884#[cfg(feature = "unstable_prompt_suggestions")]
4895#[serde_as]
4896#[skip_serializing_none]
4897#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4898#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4899#[serde(rename_all = "camelCase")]
4900#[non_exhaustive]
4901pub struct PromptSuggestionsCapabilities {
4902 #[serde_as(deserialize_as = "DefaultOnError")]
4907 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4908 #[serde(default)]
4909 pub image: Option<PromptSuggestionsImageCapabilities>,
4910 #[serde_as(deserialize_as = "DefaultOnError")]
4915 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4916 #[serde(default)]
4917 pub audio: Option<PromptSuggestionsAudioCapabilities>,
4918 #[serde_as(deserialize_as = "DefaultOnError")]
4924 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4925 #[serde(default)]
4926 pub embedded_context: Option<PromptSuggestionsEmbeddedContextCapabilities>,
4927 #[serde_as(deserialize_as = "DefaultOnError")]
4933 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4934 #[serde(default)]
4935 #[serde(rename = "_meta")]
4936 pub meta: Option<Meta>,
4937}
4938
4939#[cfg(feature = "unstable_prompt_suggestions")]
4940impl PromptSuggestionsCapabilities {
4941 #[must_use]
4943 pub fn new() -> Self {
4944 Self::default()
4945 }
4946
4947 #[must_use]
4949 pub fn image(mut self, image: impl IntoOption<PromptSuggestionsImageCapabilities>) -> Self {
4950 self.image = image.into_option();
4951 self
4952 }
4953
4954 #[must_use]
4956 pub fn audio(mut self, audio: impl IntoOption<PromptSuggestionsAudioCapabilities>) -> Self {
4957 self.audio = audio.into_option();
4958 self
4959 }
4960
4961 #[must_use]
4963 pub fn embedded_context(
4964 mut self,
4965 embedded_context: impl IntoOption<PromptSuggestionsEmbeddedContextCapabilities>,
4966 ) -> Self {
4967 self.embedded_context = embedded_context.into_option();
4968 self
4969 }
4970
4971 #[must_use]
4977 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4978 self.meta = meta.into_option();
4979 self
4980 }
4981}
4982
4983#[cfg(feature = "unstable_prompt_suggestions")]
4991#[serde_as]
4992#[skip_serializing_none]
4993#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4994#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4995#[non_exhaustive]
4996pub struct PromptSuggestionsImageCapabilities {
4997 #[serde_as(deserialize_as = "DefaultOnError")]
5003 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5004 #[serde(default)]
5005 #[serde(rename = "_meta")]
5006 pub meta: Option<Meta>,
5007}
5008
5009#[cfg(feature = "unstable_prompt_suggestions")]
5010impl PromptSuggestionsImageCapabilities {
5011 #[must_use]
5013 pub fn new() -> Self {
5014 Self::default()
5015 }
5016
5017 #[must_use]
5023 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5024 self.meta = meta.into_option();
5025 self
5026 }
5027}
5028
5029#[cfg(feature = "unstable_prompt_suggestions")]
5037#[serde_as]
5038#[skip_serializing_none]
5039#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5040#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5041#[non_exhaustive]
5042pub struct PromptSuggestionsAudioCapabilities {
5043 #[serde_as(deserialize_as = "DefaultOnError")]
5049 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5050 #[serde(default)]
5051 #[serde(rename = "_meta")]
5052 pub meta: Option<Meta>,
5053}
5054
5055#[cfg(feature = "unstable_prompt_suggestions")]
5056impl PromptSuggestionsAudioCapabilities {
5057 #[must_use]
5059 pub fn new() -> Self {
5060 Self::default()
5061 }
5062
5063 #[must_use]
5069 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5070 self.meta = meta.into_option();
5071 self
5072 }
5073}
5074
5075#[cfg(feature = "unstable_prompt_suggestions")]
5084#[serde_as]
5085#[skip_serializing_none]
5086#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5087#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5088#[non_exhaustive]
5089pub struct PromptSuggestionsEmbeddedContextCapabilities {
5090 #[serde_as(deserialize_as = "DefaultOnError")]
5096 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5097 #[serde(default)]
5098 #[serde(rename = "_meta")]
5099 pub meta: Option<Meta>,
5100}
5101
5102#[cfg(feature = "unstable_prompt_suggestions")]
5103impl PromptSuggestionsEmbeddedContextCapabilities {
5104 #[must_use]
5106 pub fn new() -> Self {
5107 Self::default()
5108 }
5109
5110 #[must_use]
5116 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5117 self.meta = meta.into_option();
5118 self
5119 }
5120}
5121
5122#[serde_as]
5128#[skip_serializing_none]
5129#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5130#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5131#[serde(rename_all = "camelCase")]
5132#[non_exhaustive]
5133pub struct ClientAuthCapabilities {
5134 #[serde_as(deserialize_as = "DefaultOnError")]
5141 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5142 #[serde(default)]
5143 pub terminal: Option<TerminalAuthCapabilities>,
5144 #[serde_as(deserialize_as = "DefaultOnError")]
5150 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5151 #[serde(default)]
5152 #[serde(rename = "_meta")]
5153 pub meta: Option<Meta>,
5154}
5155
5156impl ClientAuthCapabilities {
5157 #[must_use]
5159 pub fn new() -> Self {
5160 Self::default()
5161 }
5162
5163 #[must_use]
5170 pub fn terminal(mut self, terminal: impl IntoOption<TerminalAuthCapabilities>) -> Self {
5171 self.terminal = terminal.into_option();
5172 self
5173 }
5174
5175 #[must_use]
5181 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5182 self.meta = meta.into_option();
5183 self
5184 }
5185}
5186
5187#[serde_as]
5193#[skip_serializing_none]
5194#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5195#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5196#[non_exhaustive]
5197pub struct TerminalAuthCapabilities {
5198 #[serde_as(deserialize_as = "DefaultOnError")]
5204 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5205 #[serde(default)]
5206 #[serde(rename = "_meta")]
5207 pub meta: Option<Meta>,
5208}
5209
5210impl TerminalAuthCapabilities {
5211 #[must_use]
5213 pub fn new() -> Self {
5214 Self::default()
5215 }
5216
5217 #[must_use]
5223 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5224 self.meta = meta.into_option();
5225 self
5226 }
5227}
5228
5229#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5235#[non_exhaustive]
5236pub struct ClientMethodNames {
5237 pub session_request_permission: &'static str,
5239 pub session_update: &'static str,
5241 #[cfg(feature = "unstable_mcp_over_acp")]
5243 pub mcp_message: &'static str,
5244 pub elicitation_create: &'static str,
5246 pub elicitation_complete: &'static str,
5248 #[cfg(feature = "unstable_auth_status")]
5250 pub auth_status_update: &'static str,
5251}
5252
5253pub const CLIENT_METHOD_NAMES: ClientMethodNames = ClientMethodNames {
5255 session_update: SESSION_UPDATE_NOTIFICATION,
5256 session_request_permission: SESSION_REQUEST_PERMISSION_METHOD_NAME,
5257 #[cfg(feature = "unstable_mcp_over_acp")]
5258 mcp_message: MCP_MESSAGE_METHOD_NAME,
5259 elicitation_create: ELICITATION_CREATE_METHOD_NAME,
5260 elicitation_complete: ELICITATION_COMPLETE_NOTIFICATION,
5261 #[cfg(feature = "unstable_auth_status")]
5262 auth_status_update: AUTH_STATUS_UPDATE_NOTIFICATION,
5263};
5264
5265pub(crate) const SESSION_UPDATE_NOTIFICATION: &str = "session/update";
5267pub(crate) const SESSION_REQUEST_PERMISSION_METHOD_NAME: &str = "session/request_permission";
5269pub(crate) const ELICITATION_CREATE_METHOD_NAME: &str = "elicitation/create";
5271pub(crate) const ELICITATION_COMPLETE_NOTIFICATION: &str = "elicitation/complete";
5273#[cfg(feature = "unstable_auth_status")]
5275pub(crate) const AUTH_STATUS_UPDATE_NOTIFICATION: &str = "auth/status_update";
5276
5277#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5284#[derive(Clone, Debug, Serialize, Deserialize)]
5285#[serde(untagged)]
5286#[cfg_attr(feature = "schemars", schemars(inline))]
5287#[non_exhaustive]
5288pub enum AgentRequest {
5289 RequestPermissionRequest(Box<RequestPermissionRequest>),
5307 CreateElicitationRequest(Box<CreateElicitationRequest>),
5311 #[cfg(feature = "unstable_mcp_over_acp")]
5317 MessageMcpRequest(Box<MessageMcpRequest>),
5318 ExtMethodRequest(Box<ExtRequest>),
5325}
5326
5327impl_request_dispatch! {
5328 AgentRequest => ClientResponse {
5329 RequestPermissionRequest => RequestPermissionResponse: CLIENT_METHOD_NAMES.session_request_permission,
5330 CreateElicitationRequest => CreateElicitationResponse: CLIENT_METHOD_NAMES.elicitation_create,
5331 #[cfg(feature = "unstable_mcp_over_acp")]
5332 MessageMcpRequest => MessageMcpResponse: CLIENT_METHOD_NAMES.mcp_message,
5333 }
5334 extension ExtMethodRequest(Box<ExtRequest>) => ExtMethodResponse;
5335}
5336
5337#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5344#[derive(Clone, Debug, Serialize, Deserialize)]
5345#[serde(untagged)]
5346#[cfg_attr(feature = "schemars", schemars(inline))]
5347#[non_exhaustive]
5348pub enum ClientResponse {
5349 RequestPermissionResponse(Box<RequestPermissionResponse>),
5351 CreateElicitationResponse(Box<CreateElicitationResponse>),
5353 #[cfg(feature = "unstable_mcp_over_acp")]
5355 MessageMcpResponse(Box<MessageMcpResponse>),
5356 ExtMethodResponse(Box<ExtResponse>),
5358}
5359
5360#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5367#[derive(Clone, Debug, Serialize, Deserialize)]
5368#[serde(untagged)]
5369#[cfg_attr(feature = "schemars", schemars(inline))]
5370#[non_exhaustive]
5371pub enum AgentNotification {
5372 UpdateSessionNotification(Box<UpdateSessionNotification>),
5384 CompleteElicitationNotification(Box<CompleteElicitationNotification>),
5388 #[cfg(feature = "unstable_auth_status")]
5396 AuthStatusUpdateNotification(Box<AuthStatusUpdateNotification>),
5397 ExtNotification(Box<ExtNotification>),
5404}
5405
5406impl_message_dispatch! {
5407 AgentNotification {
5408 UpdateSessionNotification => CLIENT_METHOD_NAMES.session_update,
5409 CompleteElicitationNotification => CLIENT_METHOD_NAMES.elicitation_complete,
5410 #[cfg(feature = "unstable_auth_status")]
5411 AuthStatusUpdateNotification => CLIENT_METHOD_NAMES.auth_status_update,
5412 }
5413 extension ExtNotification(Box<ExtNotification>);
5414}
5415
5416#[cfg(test)]
5417mod tests {
5418
5419 #[test]
5420 fn background_list_round_trips_on_state_updates() {
5421 use serde_json::json;
5422 let idle = super::StateUpdate::Idle(super::IdleStateUpdate::new().background(vec![
5423 super::BackgroundWork::Terminal(super::BackgroundTerminal::new("term_003")),
5424 super::BackgroundWork::ToolCall(super::BackgroundToolCall::new("call_012")),
5425 ]));
5426 let wire = json!({
5427 "state": "idle",
5428 "background": [
5429 { "type": "terminal", "terminalId": "term_003" },
5430 { "type": "tool_call", "toolCallId": "call_012" }
5431 ]
5432 });
5433 assert_eq!(serde_json::to_value(&idle).unwrap(), wire);
5434 assert_eq!(
5435 serde_json::from_value::<super::StateUpdate>(wire).unwrap(),
5436 idle
5437 );
5438
5439 assert_eq!(idle.background().map(<[_]>::len), Some(2));
5440
5441 let empty = super::RunningStateUpdate::new().background(vec![]);
5442 assert_eq!(
5443 serde_json::to_value(&empty).unwrap(),
5444 json!({ "background": [] })
5445 );
5446 assert_eq!(
5447 super::StateUpdate::Running(empty).background(),
5448 Some(&[][..])
5449 );
5450 assert_eq!(
5451 super::StateUpdate::RequiresAction(super::RequiresActionStateUpdate::new())
5452 .background(),
5453 None
5454 );
5455 let custom: super::StateUpdate = serde_json::from_value(json!({
5456 "state": "_waiting",
5457 "background": [{ "type": "terminal", "terminalId": "term_003" }]
5458 }))
5459 .unwrap();
5460 assert_eq!(custom.background(), None);
5461 }
5462
5463 #[test]
5464 fn background_list_keeps_unknown_items_and_drops_malformed_lists() {
5465 use serde_json::json;
5466 let parsed: super::RunningStateUpdate = serde_json::from_value(json!({
5467 "background": [{ "type": "_cron", "schedule": "* * * * *" }]
5468 }))
5469 .unwrap();
5470 let Some([super::BackgroundWork::Other(other)]) = parsed.background.as_deref() else {
5471 panic!("expected one unknown item: {parsed:?}");
5472 };
5473 assert_eq!(other.kind, "_cron");
5474 assert_eq!(other.fields["schedule"], json!("* * * * *"));
5475
5476 for background in [
5477 json!(null),
5478 json!("oops"),
5479 json!([{ "type": "terminal" }]),
5480 json!([{ "type": "tool_call", "toolCallId": "call_1" }, { "type": "terminal", "terminalId": 7 }]),
5481 ] {
5482 let parsed: super::IdleStateUpdate =
5483 serde_json::from_value(json!({ "background": background })).unwrap();
5484 assert_eq!(parsed.background, None, "{background}");
5485 }
5486 }
5487
5488 #[test]
5489 fn replacement_lists_reject_non_arrays_instead_of_clearing() {
5490 use serde_json::json;
5491 for (update, key) in [
5492 ("config_option_update", "configOptions"),
5493 ("available_commands_update", "availableCommands"),
5494 ] {
5495 let empty = json!({ "sessionUpdate": update, key: [] });
5496 serde_json::from_value::<super::SessionUpdate>(empty).unwrap();
5497 for bad in [json!("oops"), json!(null), json!({})] {
5498 let wire = json!({ "sessionUpdate": update, key: bad });
5499 assert!(
5500 serde_json::from_value::<super::SessionUpdate>(wire).is_err(),
5501 "{update} {bad}"
5502 );
5503 }
5504 }
5505 let plan = |entries: serde_json::Value| {
5506 json!({ "sessionUpdate": "plan_update",
5507 "plan": { "type": "items", "planId": "p", "entries": entries } })
5508 };
5509 serde_json::from_value::<super::SessionUpdate>(plan(json!([]))).unwrap();
5510 assert!(serde_json::from_value::<super::SessionUpdate>(plan(json!("oops"))).is_err());
5511 let skipped =
5513 plan(json!([42, { "content": "a", "priority": "high", "status": "pending" }]));
5514 let super::SessionUpdate::PlanUpdate(update) =
5515 serde_json::from_value::<super::SessionUpdate>(skipped).unwrap()
5516 else {
5517 panic!("expected plan_update");
5518 };
5519 let crate::v2::PlanUpdateContent::Items(items) = update.plan else {
5520 panic!("expected items");
5521 };
5522 assert_eq!(items.entries.len(), 1);
5523 }
5524
5525 #[test]
5526 fn other_available_command_preserves_meta_verbatim() {
5527 for meta in [serde_json::json!({ "k": 1 }), serde_json::json!("bad")] {
5528 let wire = serde_json::json!({ "type": "_custom", "name": "c",
5529 "description": "d", "_meta": meta, "extra": true });
5530 let command: super::AvailableCommand = serde_json::from_value(wire.clone()).unwrap();
5531 assert_eq!(command.meta(), meta.as_object());
5532 assert_eq!(serde_json::to_value(&command).unwrap(), wire);
5533 }
5534 }
5535
5536 #[test]
5537 fn cancelled_permission_outcome_wire_format() {
5538 let outcome: RequestPermissionOutcome =
5539 serde_json::from_value(serde_json::json!({ "outcome": "cancelled" })).unwrap();
5540 assert_eq!(outcome, CancelledPermissionOutcome::new().into());
5541 assert_eq!(
5542 serde_json::to_value(&outcome).unwrap(),
5543 serde_json::json!({ "outcome": "cancelled" })
5544 );
5545
5546 let with_meta: RequestPermissionOutcome = CancelledPermissionOutcome::new()
5547 .meta(serde_json::Map::from_iter([(
5548 "k".to_string(),
5549 serde_json::json!(1),
5550 )]))
5551 .into();
5552 let json = serde_json::to_value(&with_meta).unwrap();
5553 assert_eq!(
5554 json,
5555 serde_json::json!({ "outcome": "cancelled", "_meta": { "k": 1 } })
5556 );
5557 assert_eq!(
5558 serde_json::from_value::<RequestPermissionOutcome>(json).unwrap(),
5559 with_meta
5560 );
5561 }
5562
5563 use super::*;
5564
5565 #[test]
5566 fn subagent_update_serializes_as_upsert() {
5567 use serde_json::json;
5568
5569 let announced =
5570 SessionUpdate::SubagentUpdate(SubagentUpdate::new("sess_child_1").capabilities(
5571 SubagentSessionCapabilities::new().cancel(SessionCancelCapabilities::new()),
5572 ));
5573 let wire = json!({
5574 "sessionUpdate": "subagent_update",
5575 "sessionId": "sess_child_1",
5576 "capabilities": { "cancel": {} }
5577 });
5578 assert_eq!(serde_json::to_value(&announced).unwrap(), wire);
5579 assert_eq!(
5580 serde_json::from_value::<SessionUpdate>(wire).unwrap(),
5581 announced
5582 );
5583
5584 let minimal = SubagentUpdate::new("sess_child_1");
5585 assert_eq!(
5586 serde_json::to_value(&minimal).unwrap(),
5587 json!({
5588 "sessionId": "sess_child_1"
5589 })
5590 );
5591 assert!(minimal.capabilities.is_undefined());
5592 assert!(minimal.state.is_undefined());
5593 assert!(minimal.meta.is_undefined());
5594
5595 let cleared_wire = json!({
5597 "sessionId": "sess_child_1",
5598 "capabilities": null,
5599 "state": null,
5600 "_meta": null
5601 });
5602 let cleared: SubagentUpdate = serde_json::from_value(cleared_wire.clone()).unwrap();
5603 assert!(cleared.capabilities.is_null());
5604 assert!(cleared.state.is_null());
5605 assert!(cleared.meta.is_null());
5606 assert_eq!(serde_json::to_value(cleared).unwrap(), cleared_wire);
5607
5608 let revoked: SubagentUpdate = serde_json::from_value(json!({
5609 "sessionId": "sess_child_1",
5610 "capabilities": {}
5611 }))
5612 .unwrap();
5613 assert_eq!(
5614 revoked.capabilities,
5615 MaybeUndefined::Value(SubagentSessionCapabilities::new())
5616 );
5617 assert!(
5618 matches!(revoked.capabilities, MaybeUndefined::Value(ref child) if child.cancel.is_none())
5619 );
5620
5621 assert!(
5622 serde_json::from_value::<SessionUpdate>(json!({
5623 "sessionUpdate": "subagent_update"
5624 }))
5625 .is_err()
5626 );
5627 }
5628
5629 #[test]
5630 fn subagent_cancel_capability_is_optional_object() {
5631 use serde_json::json;
5632
5633 for wire in [
5634 json!({}),
5635 json!({"cancel": null}),
5636 json!({"cancel": true}),
5637 json!({"cancel": false}),
5638 ] {
5639 let child: SubagentSessionCapabilities = serde_json::from_value(wire).unwrap();
5640 assert!(child.cancel.is_none());
5641 assert_eq!(serde_json::to_value(child).unwrap(), json!({}));
5642 }
5643 let enabled = SubagentSessionCapabilities::new().cancel(SessionCancelCapabilities::new());
5644 assert_eq!(
5645 serde_json::to_value(&enabled).unwrap(),
5646 json!({"cancel": {}})
5647 );
5648 assert_eq!(
5649 serde_json::from_value::<SubagentSessionCapabilities>(json!({"cancel": {}})).unwrap(),
5650 enabled
5651 );
5652 let meta: Meta = [("source".into(), json!("worker"))].into_iter().collect();
5653 let with_meta =
5654 SubagentSessionCapabilities::new().cancel(SessionCancelCapabilities::new().meta(meta));
5655 let wire = json!({"cancel": {"_meta": {"source": "worker"}}});
5656 assert_eq!(serde_json::to_value(&with_meta).unwrap(), wire);
5657 assert_eq!(
5658 serde_json::from_value::<SubagentSessionCapabilities>(wire).unwrap(),
5659 with_meta
5660 );
5661 assert!(enabled.cancel.is_some());
5662 assert!(enabled.cancel(None).cancel.is_none());
5663 let removed = SubagentUpdate::new("child").capabilities(SubagentSessionCapabilities::new());
5664 assert_eq!(
5665 serde_json::to_value(removed).unwrap(),
5666 json!({"sessionId": "child", "capabilities": {}})
5667 );
5668 }
5669
5670 #[test]
5671 fn subagent_display_metadata_uses_patch_semantics() {
5672 use serde_json::json;
5673
5674 let update = SubagentUpdate::new("child")
5675 .title("Test investigator".to_string())
5676 .description("Investigates platform-specific test failures.".to_string());
5677 let wire = json!({
5678 "sessionId": "child",
5679 "title": "Test investigator",
5680 "description": "Investigates platform-specific test failures."
5681 });
5682 assert_eq!(serde_json::to_value(&update).unwrap(), wire);
5683 assert_eq!(
5684 serde_json::from_value::<SubagentUpdate>(wire).unwrap(),
5685 update
5686 );
5687
5688 let minimal = SubagentUpdate::new("child");
5689 assert!(minimal.title.is_undefined());
5690 assert!(minimal.description.is_undefined());
5691 assert_eq!(
5692 serde_json::to_value(&minimal).unwrap(),
5693 json!({"sessionId": "child"})
5694 );
5695 let cleared_wire = json!({
5696 "sessionId": "child", "title": null, "description": null
5697 });
5698 let cleared: SubagentUpdate = serde_json::from_value(cleared_wire.clone()).unwrap();
5699 assert!(cleared.title.is_null());
5700 assert!(cleared.description.is_null());
5701 assert_eq!(serde_json::to_value(cleared).unwrap(), cleared_wire);
5702
5703 let title_only: SubagentUpdate = serde_json::from_value(json!({
5704 "sessionId": "child", "title": "Updated title"
5705 }))
5706 .unwrap();
5707 assert_eq!(
5708 title_only.title,
5709 MaybeUndefined::Value("Updated title".to_string())
5710 );
5711 assert!(title_only.description.is_undefined());
5712 let malformed: SubagentUpdate = serde_json::from_value(json!({
5713 "sessionId": "child", "title": false, "description": false
5714 }))
5715 .unwrap();
5716 assert_eq!(malformed, minimal);
5717 }
5718
5719 #[test]
5720 fn subagent_directories_use_strict_patch_semantics() {
5721 use serde_json::json;
5722
5723 let update = SubagentUpdate::new("child")
5724 .cwd("/home/user/project/.worktrees/investigator")
5725 .additional_directories(vec![]);
5726 let wire = json!({
5727 "sessionId": "child",
5728 "cwd": "/home/user/project/.worktrees/investigator",
5729 "additionalDirectories": []
5730 });
5731 assert_eq!(serde_json::to_value(&update).unwrap(), wire);
5732 assert_eq!(
5733 serde_json::from_value::<SubagentUpdate>(wire).unwrap(),
5734 update
5735 );
5736
5737 let inherited: SubagentUpdate =
5738 serde_json::from_value(json!({"sessionId": "child"})).unwrap();
5739 assert!(inherited.cwd.is_undefined());
5740 assert!(inherited.additional_directories.is_undefined());
5741
5742 let cleared_wire = json!({
5743 "sessionId": "child", "cwd": null, "additionalDirectories": null
5744 });
5745 let cleared: SubagentUpdate = serde_json::from_value(cleared_wire.clone()).unwrap();
5746 assert!(cleared.cwd.is_null());
5747 assert!(cleared.additional_directories.is_null());
5748 assert_eq!(serde_json::to_value(cleared).unwrap(), cleared_wire);
5749
5750 for malformed in [
5751 json!({"sessionId": "child", "cwd": false}),
5752 json!({"sessionId": "child", "additionalDirectories": "/tmp/wt"}),
5753 json!({"sessionId": "child", "additionalDirectories": ["/tmp/wt", false]}),
5754 ] {
5755 assert!(
5756 serde_json::from_value::<SubagentUpdate>(malformed.clone()).is_err(),
5757 "{malformed}"
5758 );
5759 }
5760 }
5761
5762 #[test]
5763 fn subagent_notification_keeps_parent_and_child_ids_nested() {
5764 use serde_json::json;
5765
5766 let notification = UpdateSessionNotification::new(
5767 "parent",
5768 SessionUpdate::SubagentUpdate(SubagentUpdate::new("child")),
5769 );
5770 let wire = json!({
5771 "sessionId": "parent",
5772 "update": {
5773 "sessionUpdate": "subagent_update",
5774 "sessionId": "child"
5775 }
5776 });
5777 assert_eq!(serde_json::to_value(¬ification).unwrap(), wire);
5778 assert_eq!(
5779 serde_json::from_value::<UpdateSessionNotification>(wire).unwrap(),
5780 notification
5781 );
5782 for malformed in [
5783 json!({"sessionId": "parent", "update": {"sessionUpdate": "subagent_update"}}),
5784 json!({"update": {"sessionUpdate": "subagent_update", "sessionId": "child"}}),
5785 ] {
5786 assert!(serde_json::from_value::<UpdateSessionNotification>(malformed).is_err());
5787 }
5788 }
5789
5790 #[test]
5791 fn subagent_mirrors_normal_child_state_notifications() {
5792 use serde_json::json;
5793
5794 let association = SubagentUpdate::new("sess_child");
5795 for state in [
5796 StateUpdate::Running(RunningStateUpdate::new()),
5797 StateUpdate::RequiresAction(RequiresActionStateUpdate::new()),
5798 StateUpdate::Unknown(UnknownStateUpdate::new()),
5799 StateUpdate::Running(RunningStateUpdate::new()),
5800 StateUpdate::Idle(IdleStateUpdate::new().stop_reason(StopReason::EndTurn)),
5801 StateUpdate::Running(RunningStateUpdate::new()),
5802 StateUpdate::Idle(IdleStateUpdate::new().stop_reason(StopReason::Cancelled)),
5803 ] {
5804 let child_notification = UpdateSessionNotification::new(
5805 association.session_id.clone(),
5806 SessionUpdate::StateUpdate(state.clone()),
5807 );
5808 let parent_notification = UpdateSessionNotification::new(
5809 "sess_parent",
5810 SessionUpdate::SubagentUpdate(association.clone().state(state)),
5811 );
5812 let child_wire = serde_json::to_value(&child_notification).unwrap();
5813 let parent_wire = serde_json::to_value(&parent_notification).unwrap();
5814 assert_eq!(child_wire["sessionId"], json!("sess_child"));
5815 assert_eq!(child_wire["update"]["sessionUpdate"], json!("state_update"));
5816 assert_eq!(parent_wire["sessionId"], json!("sess_parent"));
5817 assert_eq!(parent_wire["update"]["sessionId"], json!("sess_child"));
5818 let mut child_snapshot = child_wire["update"].clone();
5819 child_snapshot
5820 .as_object_mut()
5821 .unwrap()
5822 .remove("sessionUpdate");
5823 assert_eq!(parent_wire["update"]["state"], child_snapshot);
5824 assert_eq!(
5825 serde_json::from_value::<UpdateSessionNotification>(child_wire).unwrap(),
5826 child_notification
5827 );
5828 assert_eq!(
5829 serde_json::from_value::<UpdateSessionNotification>(parent_wire).unwrap(),
5830 parent_notification
5831 );
5832 }
5833 }
5834
5835 #[test]
5836 fn subagent_state_uses_whole_snapshot_patch_semantics() {
5837 use serde_json::json;
5838
5839 let minimal = SubagentUpdate::new("child");
5840 assert!(minimal.state.is_undefined());
5841 assert_eq!(
5842 serde_json::to_value(&minimal).unwrap(),
5843 json!({"sessionId": "child"})
5844 );
5845
5846 let cleared = minimal.clone().state(None::<StateUpdate>);
5847 assert!(cleared.state.is_null());
5848 assert_eq!(
5849 serde_json::to_value(&cleared).unwrap(),
5850 json!({"sessionId": "child", "state": null})
5851 );
5852 assert_eq!(
5853 serde_json::from_value::<SubagentUpdate>(json!({"sessionId": "child", "state": null}))
5854 .unwrap(),
5855 cleared
5856 );
5857
5858 for snapshot in [
5859 json!({"state": "running", "_meta": {"source": "worker"}}),
5860 json!({"state": "idle", "stopReason": "end_turn"}),
5861 json!({"state": "requires_action"}),
5862 json!({"state": "unknown"}),
5863 json!({"state": "_custom", "detail": {"phase": 2}}),
5864 ] {
5865 let state: StateUpdate = serde_json::from_value(snapshot.clone()).unwrap();
5866 let update = minimal.clone().state(state.clone());
5867 let wire = json!({"sessionId": "child", "state": snapshot});
5868 assert_eq!(serde_json::to_value(&update).unwrap(), wire);
5869 assert_eq!(
5870 serde_json::from_value::<SubagentUpdate>(wire).unwrap(),
5871 update
5872 );
5873 assert_eq!(update.state, MaybeUndefined::Value(state));
5874 }
5875
5876 let idle = SubagentUpdate::new("child").state(StateUpdate::Idle(
5879 IdleStateUpdate::new().stop_reason(StopReason::Cancelled),
5880 ));
5881 let running = idle.state(StateUpdate::Running(RunningStateUpdate::new()));
5882 assert_eq!(
5883 serde_json::to_value(running).unwrap(),
5884 json!({"sessionId": "child", "state": {"state": "running"}})
5885 );
5886 for invalid in [json!(false), json!(42), json!({}), json!({"state": 7})] {
5887 let parsed: SubagentUpdate =
5888 serde_json::from_value(json!({"sessionId": "child", "state": invalid})).unwrap();
5889 assert_eq!(parsed, minimal);
5890 }
5891 }
5892
5893 #[test]
5894 fn unknown_activity_is_a_known_state_update() {
5895 use serde_json::json;
5896
5897 let update = SessionUpdate::StateUpdate(StateUpdate::Unknown(
5898 UnknownStateUpdate::new().meta(
5899 [("source".into(), json!("worker"))]
5900 .into_iter()
5901 .collect::<Meta>(),
5902 ),
5903 ));
5904 let wire = json!({
5905 "sessionUpdate": "state_update",
5906 "state": "unknown",
5907 "_meta": { "source": "worker" }
5908 });
5909 assert_eq!(serde_json::to_value(&update).unwrap(), wire);
5910 assert_eq!(
5911 serde_json::from_value::<SessionUpdate>(wire).unwrap(),
5912 update
5913 );
5914
5915 for meta in [json!(null), json!(false)] {
5916 let state: StateUpdate = serde_json::from_value(json!({
5917 "state": "unknown",
5918 "_meta": meta
5919 }))
5920 .unwrap();
5921 assert_eq!(state, StateUpdate::Unknown(UnknownStateUpdate::new()));
5922 assert_eq!(
5923 serde_json::to_value(state).unwrap(),
5924 json!({"state": "unknown"})
5925 );
5926 }
5927 assert!(serde_json::from_value::<OtherStateUpdate>(json!({"state": "unknown"})).is_err());
5928 }
5929
5930 #[cfg(feature = "schemars")]
5931 #[test]
5932 fn subagent_schema_carries_optional_nullable_state_snapshot() {
5933 use serde_json::json;
5934
5935 let schema = serde_json::to_value(schemars::schema_for!(SubagentUpdate)).unwrap();
5936 let properties = schema["properties"].as_object().unwrap();
5937 assert!(properties.contains_key("sessionId"));
5938 assert!(properties.contains_key("title"));
5939 assert!(properties.contains_key("description"));
5940 assert!(properties.contains_key("capabilities"));
5941 assert!(properties.contains_key("state"));
5942 assert!(properties.contains_key("_meta"));
5943 assert!(!properties.contains_key("name"));
5944 assert!(!properties.contains_key("task"));
5945 assert_eq!(schema["required"], json!(["sessionId"]));
5946 assert_eq!(
5947 properties["state"]["x-deserialize-default-on-error"],
5948 json!(true)
5949 );
5950 let state_variants = properties["state"]["anyOf"].as_array().unwrap();
5951 assert!(state_variants.contains(&json!({"type": "null"})));
5952 assert!(
5953 state_variants
5954 .iter()
5955 .any(|variant| variant["$ref"] == "#/$defs/StateUpdate")
5956 );
5957 let child =
5958 serde_json::to_value(schemars::schema_for!(SubagentSessionCapabilities)).unwrap();
5959 let variants = child["properties"]["cancel"]["anyOf"]
5960 .as_array()
5961 .expect("cancel must allow the capability object or null");
5962 assert!(variants.contains(&json!({"type": "null"})));
5963 assert!(
5964 variants
5965 .iter()
5966 .any(|variant| variant["type"] == "object" || variant.get("$ref").is_some())
5967 );
5968 assert!(!variants.iter().any(|variant| variant["type"] == "boolean"));
5969 let cancel =
5970 serde_json::to_value(schemars::schema_for!(SessionCancelCapabilities)).unwrap();
5971 assert_eq!(cancel["type"], "object");
5972 assert!(
5973 !child["required"]
5974 .as_array()
5975 .is_some_and(|required| required.contains(&json!("cancel")))
5976 );
5977 }
5978
5979 #[test]
5980 fn notice_preserves_wire_shape_nullable_fields_and_open_severity() {
5981 use serde_json::json;
5982
5983 let mut meta = Meta::new();
5984 meta.insert("source".into(), json!("fallback"));
5985 let v2_notice = SessionUpdate::Notice(
5986 Notice::new(NoticeSeverity::Error, "Provider degraded")
5987 .description("Requests may take longer than usual.")
5988 .meta(meta.clone()),
5989 );
5990 let expected = json!({
5991 "sessionUpdate": "notice",
5992 "severity": "error",
5993 "title": "Provider degraded",
5994 "description": "Requests may take longer than usual.",
5995 "_meta": { "source": "fallback" }
5996 });
5997 assert_eq!(serde_json::to_value(&v2_notice).unwrap(), expected);
5998
5999 let v1_notice = crate::v1::SessionUpdate::Notice(
6000 crate::v1::Notice::new(crate::v1::NoticeSeverity::Error, "Provider degraded")
6001 .description("Requests may take longer than usual.")
6002 .meta(meta),
6003 );
6004 assert_eq!(
6005 serde_json::to_value(v2_notice).unwrap(),
6006 serde_json::to_value(v1_notice).unwrap()
6007 );
6008
6009 let SessionUpdate::Notice(notice) = serde_json::from_value(json!({
6010 "sessionUpdate": "notice",
6011 "severity": "critical",
6012 "title": "Provider degraded",
6013 "description": null,
6014 "_meta": null
6015 }))
6016 .unwrap() else {
6017 panic!("expected notice");
6018 };
6019
6020 assert_eq!(
6021 notice.severity,
6022 NoticeSeverity::Other("critical".to_string())
6023 );
6024 assert_eq!(notice.description, None);
6025 assert_eq!(notice.meta, None);
6026 assert_eq!(
6027 serde_json::to_value(SessionUpdate::Notice(notice)).unwrap(),
6028 json!({
6029 "sessionUpdate": "notice",
6030 "severity": "critical",
6031 "title": "Provider degraded"
6032 })
6033 );
6034 }
6035
6036 #[test]
6037 fn malformed_known_notice_is_not_hidden_as_unknown() {
6038 use serde_json::json;
6039
6040 for malformed in [
6041 json!({
6042 "sessionUpdate": "notice",
6043 "severity": "warning",
6044 "title": 42
6045 }),
6046 json!({
6047 "sessionUpdate": "notice",
6048 "severity": 42,
6049 "title": "MCP server unavailable"
6050 }),
6051 json!({
6052 "sessionUpdate": "notice",
6053 "severity": "warning"
6054 }),
6055 json!({
6056 "sessionUpdate": "notice",
6057 "severity": "warning",
6058 "title": null
6059 }),
6060 json!({
6061 "sessionUpdate": "notice",
6062 "title": "MCP server unavailable"
6063 }),
6064 json!({
6065 "sessionUpdate": "notice",
6066 "severity": null,
6067 "title": "MCP server unavailable"
6068 }),
6069 ] {
6070 assert!(serde_json::from_str::<SessionUpdate>(&malformed.to_string()).is_err());
6071 assert!(serde_json::from_value::<SessionUpdate>(malformed).is_err());
6072 }
6073 }
6074
6075 #[test]
6076 fn notice_tolerates_invalid_optional_display_fields_and_custom_severity() {
6077 use serde_json::json;
6078
6079 let wire = json!({
6080 "sessionUpdate": "notice",
6081 "severity": "_custom",
6082 "title": "Provider degraded",
6083 "description": 42,
6084 "_meta": false
6085 });
6086 let SessionUpdate::Notice(notice) = serde_json::from_value(wire.clone()).unwrap() else {
6087 panic!("expected notice");
6088 };
6089 assert_eq!(
6090 serde_json::from_str::<SessionUpdate>(&wire.to_string()).unwrap(),
6091 SessionUpdate::Notice(notice.clone())
6092 );
6093 assert_eq!(notice.severity, NoticeSeverity::Other("_custom".into()));
6094 assert_eq!(notice.description, None);
6095 assert_eq!(notice.meta, None);
6096 assert_eq!(
6097 serde_json::to_value(notice).unwrap(),
6098 json!({"severity": "_custom", "title": "Provider degraded"})
6099 );
6100 }
6101
6102 #[cfg(feature = "schemars")]
6103 #[test]
6104 fn notice_schema_preserves_required_fields_and_excludes_unknown_fallback() {
6105 use serde_json::json;
6106
6107 let schema = serde_json::to_value(schemars::schema_for!(Notice)).unwrap();
6108 assert_eq!(schema["required"], json!(["severity", "title"]));
6109 assert_eq!(schema["properties"]["title"]["minLength"], 1);
6110 for field in ["description", "_meta"] {
6111 assert!(
6112 schema["properties"][field]["type"]
6113 .as_array()
6114 .unwrap()
6115 .contains(&json!("null"))
6116 );
6117 }
6118 let fallback = serde_json::to_value(schemars::schema_for!(OtherSessionUpdate)).unwrap();
6119 assert!(
6120 fallback["not"]["anyOf"]
6121 .as_array()
6122 .unwrap()
6123 .iter()
6124 .any(|variant| variant["properties"]["sessionUpdate"]["const"] == "notice")
6125 );
6126 }
6127
6128 #[test]
6129 fn replay_complete_round_trips_with_and_without_meta() {
6130 use serde_json::json;
6131
6132 let bare = json!({ "sessionUpdate": "replay_complete" });
6133 assert_eq!(
6134 serde_json::to_value(SessionUpdate::ReplayComplete(ReplayComplete::new())).unwrap(),
6135 bare
6136 );
6137 assert_eq!(
6138 serde_json::from_value::<SessionUpdate>(bare).unwrap(),
6139 SessionUpdate::ReplayComplete(ReplayComplete::new())
6140 );
6141
6142 let mut meta = Meta::new();
6143 meta.insert("source".into(), json!("transcript"));
6144 let with_meta = json!({
6145 "sessionUpdate": "replay_complete",
6146 "_meta": { "source": "transcript" }
6147 });
6148 let update = SessionUpdate::ReplayComplete(ReplayComplete::new().meta(meta));
6149 assert_eq!(serde_json::to_value(&update).unwrap(), with_meta);
6150 assert_eq!(
6151 serde_json::from_value::<SessionUpdate>(with_meta).unwrap(),
6152 update
6153 );
6154 }
6155
6156 #[test]
6157 fn replay_complete_is_never_preserved_as_an_unknown_update() {
6158 use serde_json::json;
6159
6160 for wire in [
6164 json!({ "sessionUpdate": "replay_complete", "_meta": null }),
6165 json!({ "sessionUpdate": "replay_complete", "_meta": false }),
6166 json!({ "sessionUpdate": "replay_complete", "futureField": 1 }),
6167 ] {
6168 assert_eq!(
6169 serde_json::from_str::<SessionUpdate>(&wire.to_string()).unwrap(),
6170 SessionUpdate::ReplayComplete(ReplayComplete::new())
6171 );
6172 assert_eq!(
6173 serde_json::from_value::<SessionUpdate>(wire).unwrap(),
6174 SessionUpdate::ReplayComplete(ReplayComplete::new())
6175 );
6176 }
6177
6178 assert!(
6179 serde_json::from_value::<OtherSessionUpdate>(
6180 json!({ "sessionUpdate": "replay_complete" })
6181 )
6182 .is_err()
6183 );
6184 }
6185
6186 #[cfg(feature = "schemars")]
6187 #[test]
6188 fn replay_complete_schema_has_only_optional_meta_and_excludes_unknown_fallback() {
6189 use serde_json::json;
6190
6191 let schema = serde_json::to_value(schemars::schema_for!(ReplayComplete)).unwrap();
6192 assert!(schema.get("required").is_none());
6193 assert_eq!(
6194 schema["properties"]
6195 .as_object()
6196 .unwrap()
6197 .keys()
6198 .collect::<Vec<_>>(),
6199 ["_meta"]
6200 );
6201 assert_eq!(
6202 schema["properties"]["_meta"]["type"],
6203 json!(["object", "null"])
6204 );
6205 let fallback = serde_json::to_value(schemars::schema_for!(OtherSessionUpdate)).unwrap();
6206 assert!(
6207 fallback["not"]["anyOf"]
6208 .as_array()
6209 .unwrap()
6210 .iter()
6211 .any(|variant| variant["properties"]["sessionUpdate"]["const"]
6212 == "replay_complete")
6213 );
6214 }
6215
6216 #[cfg(feature = "unstable_prompt_suggestions")]
6217 #[test]
6218 fn prompt_suggestions_update_round_trips_prompt_content_and_meta() {
6219 use super::{ContentBlock, Meta, PromptSuggestion, PromptSuggestionsUpdate, SessionUpdate};
6220 use crate::v2::{ResourceLink, TextContent};
6221 use serde_json::json;
6222
6223 let mut meta = Meta::new();
6224 meta.insert("rank".into(), json!(1));
6225 let update = SessionUpdate::PromptSuggestionsUpdate(PromptSuggestionsUpdate::new(vec![
6226 PromptSuggestion::new(vec![ContentBlock::Text(TextContent::new(
6227 "Run the test suite and fix what breaks",
6228 ))])
6229 .meta(meta),
6230 PromptSuggestion::new(vec![
6231 ContentBlock::Text(TextContent::new("Add tests for ")),
6232 ContentBlock::ResourceLink(ResourceLink::new(
6233 "parser.rs",
6234 "file:///home/user/project/src/parser.rs",
6235 )),
6236 ]),
6237 ]));
6238 let wire = json!({
6239 "sessionUpdate": "prompt_suggestions_update",
6240 "suggestions": [
6241 {
6242 "prompt": [
6243 { "type": "text", "text": "Run the test suite and fix what breaks" }
6244 ],
6245 "_meta": { "rank": 1 }
6246 },
6247 {
6248 "prompt": [
6249 { "type": "text", "text": "Add tests for " },
6250 {
6251 "type": "resource_link",
6252 "name": "parser.rs",
6253 "uri": "file:///home/user/project/src/parser.rs"
6254 }
6255 ]
6256 }
6257 ]
6258 });
6259 assert_eq!(serde_json::to_value(&update).unwrap(), wire);
6260 assert_eq!(
6261 serde_json::from_value::<SessionUpdate>(wire).unwrap(),
6262 update
6263 );
6264 }
6265
6266 #[cfg(feature = "unstable_prompt_suggestions")]
6267 #[test]
6268 fn prompt_suggestions_update_with_an_empty_list_withdraws_suggestions() {
6269 use super::{PromptSuggestionsUpdate, SessionUpdate};
6270 use serde_json::json;
6271
6272 let update = SessionUpdate::PromptSuggestionsUpdate(PromptSuggestionsUpdate::new(vec![]));
6273 let wire = json!({
6274 "sessionUpdate": "prompt_suggestions_update",
6275 "suggestions": []
6276 });
6277 assert_eq!(serde_json::to_value(&update).unwrap(), wire);
6278 assert_eq!(
6279 serde_json::from_value::<SessionUpdate>(wire).unwrap(),
6280 update
6281 );
6282 }
6283
6284 #[cfg(feature = "unstable_prompt_suggestions")]
6285 #[test]
6286 fn prompt_suggestions_update_is_never_preserved_as_an_unknown_update() {
6287 use super::{OtherSessionUpdate, SessionUpdate};
6288 use serde_json::json;
6289
6290 for wire in [
6293 json!({ "sessionUpdate": "prompt_suggestions_update" }),
6294 json!({ "sessionUpdate": "prompt_suggestions_update", "suggestions": null }),
6295 json!({ "sessionUpdate": "prompt_suggestions_update", "suggestions": "none" }),
6296 json!({ "sessionUpdate": "prompt_suggestions_update", "suggestions": { "prompt": [] } }),
6297 ] {
6298 assert!(serde_json::from_str::<SessionUpdate>(&wire.to_string()).is_err());
6299 assert!(serde_json::from_value::<SessionUpdate>(wire).is_err());
6300 }
6301
6302 assert!(
6303 serde_json::from_value::<OtherSessionUpdate>(json!({
6304 "sessionUpdate": "prompt_suggestions_update",
6305 "suggestions": []
6306 }))
6307 .is_err()
6308 );
6309 }
6310
6311 #[cfg(feature = "unstable_prompt_suggestions")]
6312 #[test]
6313 fn prompt_suggestions_update_skips_whole_suggestions_it_cannot_parse() {
6314 use super::{ContentBlock, PromptSuggestion, PromptSuggestionsUpdate, SessionUpdate};
6315 use crate::v2::TextContent;
6316 use serde_json::json;
6317
6318 let text =
6319 |text: &str| PromptSuggestion::new(vec![ContentBlock::Text(TextContent::new(text))]);
6320
6321 let update: SessionUpdate = serde_json::from_value(json!({
6324 "sessionUpdate": "prompt_suggestions_update",
6325 "suggestions": [
6326 { "prompt": [{ "type": "text", "text": "Keep the first" }] },
6327 { "text": "A suggestion without a prompt" },
6328 { "prompt": "Not a list" },
6329 { "prompt": [{ "type": "text", "text": "Open " }, { "type": "text" }] },
6330 "not an object",
6331 { "prompt": [{ "type": "text", "text": "Keep the last" }], "_meta": false }
6332 ]
6333 }))
6334 .unwrap();
6335
6336 assert_eq!(
6337 update,
6338 SessionUpdate::PromptSuggestionsUpdate(PromptSuggestionsUpdate::new(vec![
6339 text("Keep the first"),
6340 text("Keep the last"),
6341 ]))
6342 );
6343 }
6344
6345 #[cfg(feature = "unstable_prompt_suggestions")]
6346 #[test]
6347 fn prompt_suggestions_update_preserves_custom_and_future_content_blocks() {
6348 use super::{ContentBlock, SessionUpdate};
6349 use serde_json::json;
6350
6351 let wire = json!({
6354 "sessionUpdate": "prompt_suggestions_update",
6355 "suggestions": [
6356 { "prompt": [{ "type": "_hologram", "data": "AAAA" }] }
6357 ]
6358 });
6359 let update: SessionUpdate = serde_json::from_value(wire.clone()).unwrap();
6360 let SessionUpdate::PromptSuggestionsUpdate(suggestions) = &update else {
6361 panic!("expected prompt_suggestions_update, got {update:?}");
6362 };
6363 assert!(matches!(
6364 suggestions.suggestions[0].prompt.as_slice(),
6365 [ContentBlock::Other(_)]
6366 ));
6367 assert_eq!(serde_json::to_value(&update).unwrap(), wire);
6368 }
6369
6370 #[cfg(feature = "unstable_prompt_suggestions")]
6371 #[test]
6372 fn prompt_suggestions_capability_advertises_support_and_content_types() {
6373 use super::{
6374 ClientCapabilities, ClientSessionCapabilities, PromptSuggestionsAudioCapabilities,
6375 PromptSuggestionsCapabilities, PromptSuggestionsEmbeddedContextCapabilities,
6376 PromptSuggestionsImageCapabilities,
6377 };
6378 use serde_json::json;
6379
6380 let capabilities = ClientCapabilities::new().session(
6381 ClientSessionCapabilities::new()
6382 .prompt_suggestions(PromptSuggestionsCapabilities::new()),
6383 );
6384 let value = serde_json::to_value(&capabilities).unwrap();
6385 assert_eq!(value, json!({ "session": { "promptSuggestions": {} } }));
6386 assert_eq!(
6387 serde_json::from_value::<ClientCapabilities>(value).unwrap(),
6388 capabilities
6389 );
6390
6391 let content_types = PromptSuggestionsCapabilities::new()
6392 .image(PromptSuggestionsImageCapabilities::new())
6393 .audio(PromptSuggestionsAudioCapabilities::new())
6394 .embedded_context(PromptSuggestionsEmbeddedContextCapabilities::new());
6395 let wire = json!({ "image": {}, "audio": {}, "embeddedContext": {} });
6396 assert_eq!(serde_json::to_value(&content_types).unwrap(), wire);
6397 assert_eq!(
6398 serde_json::from_value::<PromptSuggestionsCapabilities>(wire).unwrap(),
6399 content_types
6400 );
6401
6402 for unsupported in [
6404 json!({}),
6405 json!({ "session": null }),
6406 json!({ "session": {} }),
6407 json!({ "session": { "promptSuggestions": null } }),
6408 json!({ "session": { "promptSuggestions": false } }),
6409 json!({ "session": { "promptSuggestions": true } }),
6410 json!({ "session": { "promptSuggestions": "supported" } }),
6411 ] {
6412 let capabilities: ClientCapabilities = serde_json::from_value(unsupported).unwrap();
6413 assert!(
6414 capabilities
6415 .session
6416 .and_then(|session| session.prompt_suggestions)
6417 .is_none()
6418 );
6419 }
6420
6421 assert_eq!(
6424 serde_json::from_value::<PromptSuggestionsCapabilities>(json!({
6425 "image": true,
6426 "audio": null,
6427 "embeddedContext": {}
6428 }))
6429 .unwrap(),
6430 PromptSuggestionsCapabilities::new()
6431 .embedded_context(PromptSuggestionsEmbeddedContextCapabilities::new())
6432 );
6433 }
6434
6435 #[cfg(all(feature = "schemars", feature = "unstable_prompt_suggestions"))]
6436 #[test]
6437 fn prompt_suggestions_schema_requires_the_list_and_excludes_unknown_fallback() {
6438 use super::{
6439 ClientCapabilities, ClientSessionCapabilities, OtherSessionUpdate, PromptSuggestion,
6440 PromptSuggestionsCapabilities, PromptSuggestionsUpdate,
6441 };
6442 use serde_json::json;
6443
6444 let update = serde_json::to_value(schemars::schema_for!(PromptSuggestionsUpdate)).unwrap();
6445 assert_eq!(update["required"], json!(["suggestions"]));
6446 assert_eq!(update["properties"]["suggestions"]["type"], "array");
6447
6448 let suggestion = serde_json::to_value(schemars::schema_for!(PromptSuggestion)).unwrap();
6449 assert_eq!(suggestion["required"], json!(["prompt"]));
6450 assert_eq!(suggestion["properties"]["prompt"]["type"], "array");
6451 assert_eq!(suggestion["properties"]["prompt"]["minItems"], 1);
6452
6453 let fallback = serde_json::to_value(schemars::schema_for!(OtherSessionUpdate)).unwrap();
6454 assert!(
6455 fallback["not"]["anyOf"]
6456 .as_array()
6457 .unwrap()
6458 .iter()
6459 .any(|variant| variant["properties"]["sessionUpdate"]["const"]
6460 == "prompt_suggestions_update")
6461 );
6462
6463 for (schema, field) in [
6464 (
6465 serde_json::to_value(schemars::schema_for!(ClientCapabilities)).unwrap(),
6466 "session",
6467 ),
6468 (
6469 serde_json::to_value(schemars::schema_for!(ClientSessionCapabilities)).unwrap(),
6470 "promptSuggestions",
6471 ),
6472 ] {
6473 assert!(
6474 schema["properties"][field]["anyOf"]
6475 .as_array()
6476 .unwrap()
6477 .contains(&json!({"type": "null"}))
6478 );
6479 assert!(
6480 !schema["required"]
6481 .as_array()
6482 .is_some_and(|required| required.contains(&json!(field)))
6483 );
6484 }
6485
6486 let content_types =
6487 serde_json::to_value(schemars::schema_for!(PromptSuggestionsCapabilities)).unwrap();
6488 assert!(content_types.get("required").is_none());
6489 for field in ["image", "audio", "embeddedContext"] {
6490 assert!(
6491 content_types["properties"][field]["anyOf"]
6492 .as_array()
6493 .unwrap()
6494 .contains(&json!({"type": "null"}))
6495 );
6496 }
6497 }
6498
6499 #[test]
6500 fn compaction_updates_preserve_patch_and_open_status_semantics() {
6501 use serde_json::json;
6502
6503 assert_eq!(
6504 serde_json::to_value(SessionUpdate::CompactionUpdate(
6505 CompactionUpdate::new("cmp_001")
6506 .status(CompactionStatus::Completed)
6507 .summary(vec![ContentBlock::Text(crate::v2::TextContent::new(
6508 "retained",
6509 ))]),
6510 ))
6511 .unwrap(),
6512 json!({
6513 "sessionUpdate": "compaction_update",
6514 "compactionId": "cmp_001",
6515 "status": "completed",
6516 "summary": [{ "type": "text", "text": "retained" }]
6517 })
6518 );
6519
6520 let SessionUpdate::CompactionUpdate(update) = serde_json::from_value(json!({
6521 "sessionUpdate": "compaction_update",
6522 "compactionId": "cmp_001",
6523 "status": "paused",
6524 "summary": null
6525 }))
6526 .unwrap() else {
6527 panic!("expected compaction update");
6528 };
6529 assert_eq!(
6530 update.status,
6531 MaybeUndefined::Value(CompactionStatus::Other("paused".into()))
6532 );
6533 assert!(update.summary.is_null());
6534 assert!(update.error.is_undefined());
6535
6536 let SessionUpdate::CompactionUpdate(patch) = serde_json::from_value(json!({
6538 "sessionUpdate": "compaction_update",
6539 "compactionId": "cmp_001",
6540 "summary": []
6541 }))
6542 .unwrap() else {
6543 panic!("expected compaction update");
6544 };
6545 assert!(patch.status.is_undefined());
6546 assert_eq!(
6547 serde_json::to_value(CompactionUpdate::new("cmp_001")).unwrap(),
6548 json!({ "compactionId": "cmp_001" })
6549 );
6550 let reset: CompactionUpdate =
6551 serde_json::from_value(json!({ "compactionId": "cmp_001", "status": null })).unwrap();
6552 assert!(reset.status.is_null());
6553 }
6554
6555 #[test]
6556 fn malformed_known_compaction_update_is_not_hidden_as_unknown() {
6557 use serde_json::json;
6558
6559 assert!(
6560 serde_json::from_value::<SessionUpdate>(json!({
6561 "sessionUpdate": "compaction_update",
6562 "status": "completed"
6563 }))
6564 .is_err()
6565 );
6566 assert!(
6567 serde_json::from_value::<SessionUpdate>(json!({
6568 "sessionUpdate": "compaction_summary_chunk",
6569 "compactionId": "cmp_001"
6570 }))
6571 .is_err()
6572 );
6573 }
6574
6575 #[test]
6576 fn test_elicitation_capability_semantics() {
6577 use serde_json::json;
6578
6579 let unsupported: ClientCapabilities = serde_json::from_value(json!({})).unwrap();
6580 assert!(unsupported.elicitation.is_none());
6581
6582 let null: ClientCapabilities =
6583 serde_json::from_value(json!({ "elicitation": null })).unwrap();
6584 assert!(null.elicitation.is_none());
6585
6586 let malformed: ClientCapabilities =
6587 serde_json::from_value(json!({ "elicitation": false })).unwrap();
6588 assert!(malformed.elicitation.is_none());
6589
6590 let empty: ClientCapabilities =
6591 serde_json::from_value(json!({ "elicitation": {} })).unwrap();
6592 let empty = empty.elicitation.expect("present capability");
6593 assert!(!empty.supports_form());
6594 assert!(!empty.supports_url());
6595
6596 let form_only: ClientCapabilities = serde_json::from_value(json!({
6597 "elicitation": { "form": {} }
6598 }))
6599 .unwrap();
6600 let form_only = form_only.elicitation.expect("advertised capability");
6601 assert!(form_only.supports_form());
6602 assert!(!form_only.supports_url());
6603
6604 let url_only: ClientCapabilities = serde_json::from_value(json!({
6605 "elicitation": { "url": {} }
6606 }))
6607 .unwrap();
6608 let url_only = url_only.elicitation.expect("advertised capability");
6609 assert!(!url_only.supports_form());
6610 assert!(url_only.supports_url());
6611
6612 let both: ClientCapabilities = serde_json::from_value(json!({
6613 "elicitation": { "form": {}, "url": {} }
6614 }))
6615 .unwrap();
6616 let both = both.elicitation.expect("advertised capability");
6617 assert!(both.supports_form());
6618 assert!(both.supports_url());
6619 }
6620
6621 #[test]
6622 fn test_elicitation_method_routing_and_envelopes() {
6623 use serde_json::json;
6624
6625 assert_eq!(CLIENT_METHOD_NAMES.elicitation_create, "elicitation/create");
6626 assert_eq!(
6627 CLIENT_METHOD_NAMES.elicitation_complete,
6628 "elicitation/complete"
6629 );
6630
6631 let request =
6632 AgentRequest::CreateElicitationRequest(Box::new(CreateElicitationRequest::new(
6633 crate::v2::ElicitationFormMode::new(
6634 crate::v2::ElicitationSessionScope::new("sess_1"),
6635 crate::v2::ElicitationSchema::new(),
6636 ),
6637 "Choose a value",
6638 )));
6639 assert_eq!(request.method(), "elicitation/create");
6640 let method = Arc::from(request.method());
6641 let request = crate::v2::JsonRpcMessage::wrap(crate::v2::Request {
6642 id: crate::v2::RequestId::Number(7),
6643 method,
6644 params: Some(request),
6645 });
6646 assert_eq!(
6647 serde_json::to_value(request).unwrap(),
6648 json!({
6649 "jsonrpc": "2.0",
6650 "id": 7,
6651 "method": "elicitation/create",
6652 "params": {
6653 "mode": "form",
6654 "sessionId": "sess_1",
6655 "message": "Choose a value",
6656 "requestedSchema": { "type": "object", "properties": {} }
6657 }
6658 })
6659 );
6660
6661 let notification = AgentNotification::CompleteElicitationNotification(Box::new(
6662 CompleteElicitationNotification::new("elic_1"),
6663 ));
6664 assert_eq!(notification.method(), "elicitation/complete");
6665 let method = Arc::from(notification.method());
6666 let notification = crate::v2::JsonRpcMessage::wrap(crate::v2::Notification {
6667 method,
6668 params: Some(notification),
6669 });
6670 assert_eq!(
6671 serde_json::to_value(notification).unwrap(),
6672 json!({
6673 "jsonrpc": "2.0",
6674 "method": "elicitation/complete",
6675 "params": { "elicitationId": "elic_1" }
6676 })
6677 );
6678 }
6679
6680 #[test]
6681 fn test_client_capabilities_auth_defaults_on_malformed_value() {
6682 use serde_json::json;
6683
6684 let capabilities: ClientCapabilities = serde_json::from_value(json!({
6685 "auth": false
6686 }))
6687 .unwrap();
6688
6689 assert_eq!(capabilities.auth, None);
6690 }
6691
6692 #[test]
6693 fn test_serialization_behavior() {
6694 use serde_json::json;
6695
6696 assert_eq!(
6697 serde_json::from_value::<SessionInfoUpdate>(json!({})).unwrap(),
6698 SessionInfoUpdate {
6699 title: MaybeUndefined::Undefined,
6700 updated_at: MaybeUndefined::Undefined,
6701 meta: MaybeUndefined::Undefined
6702 }
6703 );
6704 assert_eq!(
6705 serde_json::from_value::<SessionInfoUpdate>(json!({"title": null, "updatedAt": null}))
6706 .unwrap(),
6707 SessionInfoUpdate {
6708 title: MaybeUndefined::Null,
6709 updated_at: MaybeUndefined::Null,
6710 meta: MaybeUndefined::Undefined
6711 }
6712 );
6713 assert_eq!(
6714 serde_json::from_value::<SessionInfoUpdate>(
6715 json!({"title": "title", "updatedAt": "timestamp"})
6716 )
6717 .unwrap(),
6718 SessionInfoUpdate {
6719 title: MaybeUndefined::Value("title".to_string()),
6720 updated_at: MaybeUndefined::Value("timestamp".to_string()),
6721 meta: MaybeUndefined::Undefined
6722 }
6723 );
6724
6725 let clear_meta =
6726 serde_json::from_value::<SessionInfoUpdate>(json!({"_meta": null})).unwrap();
6727 assert_eq!(clear_meta.meta, MaybeUndefined::Null);
6728
6729 let mut meta = Meta::new();
6730 meta.insert("source".to_string(), json!("session-info"));
6731
6732 assert_eq!(
6733 serde_json::from_value::<SessionInfoUpdate>(json!({"_meta": {
6734 "source": "session-info"
6735 }}))
6736 .unwrap()
6737 .meta,
6738 MaybeUndefined::Value(meta.clone())
6739 );
6740
6741 assert_eq!(
6742 serde_json::to_value(SessionInfoUpdate::new()).unwrap(),
6743 json!({})
6744 );
6745
6746 assert_eq!(
6747 serde_json::to_value(SessionInfoUpdate::new().meta(None::<Meta>)).unwrap(),
6748 json!({"_meta": null})
6749 );
6750
6751 assert_eq!(
6752 serde_json::to_value(SessionInfoUpdate::new().meta(meta)).unwrap(),
6753 json!({"_meta": {
6754 "source": "session-info"
6755 }})
6756 );
6757 assert_eq!(
6758 serde_json::to_value(SessionInfoUpdate::new().title("title")).unwrap(),
6759 json!({"title": "title"})
6760 );
6761 assert_eq!(
6762 serde_json::to_value(SessionInfoUpdate::new().title(None)).unwrap(),
6763 json!({"title": null})
6764 );
6765 assert_eq!(
6766 serde_json::to_value(
6767 SessionInfoUpdate::new()
6768 .title("title")
6769 .title(MaybeUndefined::Undefined)
6770 )
6771 .unwrap(),
6772 json!({})
6773 );
6774 }
6775
6776 #[test]
6777 fn test_content_chunk_message_id_serialization() {
6778 use serde_json::json;
6779
6780 assert_eq!(
6781 serde_json::to_value(SessionUpdate::AgentMessageChunk(ContentChunk::new(
6782 ContentBlock::Text(crate::v2::TextContent::new("Hello")),
6783 "msg_agent_c42b9",
6784 )))
6785 .unwrap(),
6786 json!({
6787 "sessionUpdate": "agent_message_chunk",
6788 "messageId": "msg_agent_c42b9",
6789 "content": {
6790 "type": "text",
6791 "text": "Hello"
6792 }
6793 })
6794 );
6795
6796 let err = serde_json::from_value::<ContentChunk>(json!({
6797 "content": {
6798 "type": "text",
6799 "text": "Hello"
6800 }
6801 }))
6802 .unwrap_err();
6803
6804 assert!(err.to_string().contains("messageId"), "{err}");
6805 }
6806
6807 #[test]
6808 fn test_tool_call_content_chunk_serialization() {
6809 use serde_json::json;
6810
6811 assert_eq!(
6812 serde_json::to_value(SessionUpdate::ToolCallContentChunk(
6813 ToolCallContentChunk::new(
6814 "call_001",
6815 crate::v2::ContentBlock::Text(crate::v2::TextContent::new("partial output")),
6816 )
6817 ))
6818 .unwrap(),
6819 json!({
6820 "sessionUpdate": "tool_call_content_chunk",
6821 "toolCallId": "call_001",
6822 "content": {
6823 "type": "content",
6824 "content": {
6825 "type": "text",
6826 "text": "partial output"
6827 }
6828 }
6829 })
6830 );
6831
6832 let err = serde_json::from_value::<ToolCallContentChunk>(json!({
6833 "content": {
6834 "type": "content",
6835 "content": {
6836 "type": "text",
6837 "text": "partial output"
6838 }
6839 }
6840 }))
6841 .unwrap_err();
6842
6843 assert!(err.to_string().contains("toolCallId"), "{err}");
6844 }
6845
6846 #[test]
6847 fn test_full_message_serialization() {
6848 use serde_json::json;
6849
6850 assert_eq!(
6851 serde_json::to_value(SessionUpdate::UserMessage(
6852 UserMessage::new("msg_user_8f7a1").content(vec![ContentBlock::Text(
6853 crate::v2::TextContent::new("Hello")
6854 )])
6855 ))
6856 .unwrap(),
6857 json!({
6858 "sessionUpdate": "user_message",
6859 "messageId": "msg_user_8f7a1",
6860 "content": [
6861 {
6862 "type": "text",
6863 "text": "Hello"
6864 }
6865 ]
6866 })
6867 );
6868
6869 assert_eq!(
6870 serde_json::to_value(SessionUpdate::AgentMessage(
6871 AgentMessage::new("msg_agent_c42b9").content(vec![ContentBlock::Text(
6872 crate::v2::TextContent::new("Hello")
6873 )])
6874 ))
6875 .unwrap(),
6876 json!({
6877 "sessionUpdate": "agent_message",
6878 "messageId": "msg_agent_c42b9",
6879 "content": [
6880 {
6881 "type": "text",
6882 "text": "Hello"
6883 }
6884 ]
6885 })
6886 );
6887
6888 assert_eq!(
6889 serde_json::to_value(SessionUpdate::AgentThought(
6890 AgentThought::new("msg_thought_a12").content(vec![ContentBlock::Text(
6891 crate::v2::TextContent::new("Need to inspect the call sites first.")
6892 )])
6893 ))
6894 .unwrap(),
6895 json!({
6896 "sessionUpdate": "agent_thought",
6897 "messageId": "msg_thought_a12",
6898 "content": [
6899 {
6900 "type": "text",
6901 "text": "Need to inspect the call sites first."
6902 }
6903 ]
6904 })
6905 );
6906 }
6907
6908 #[test]
6909 fn test_message_upsert_serialization() {
6910 use serde_json::json;
6911
6912 assert_eq!(
6913 serde_json::to_value(SessionUpdate::UserMessage(
6914 UserMessage::new("msg_empty").content(Vec::<ContentBlock>::new())
6915 ))
6916 .unwrap(),
6917 json!({
6918 "sessionUpdate": "user_message",
6919 "messageId": "msg_empty",
6920 "content": []
6921 })
6922 );
6923
6924 let empty = serde_json::from_value::<UserMessage>(json!({
6925 "messageId": "msg_empty",
6926 "content": []
6927 }))
6928 .unwrap();
6929 assert!(matches!(
6930 empty.content,
6931 MaybeUndefined::Value(ref content) if content.is_empty()
6932 ));
6933
6934 let patch = serde_json::from_value::<AgentMessage>(json!({
6935 "messageId": "msg_agent_c42b9"
6936 }))
6937 .unwrap();
6938 assert_eq!(patch.content, MaybeUndefined::Undefined);
6939 assert_eq!(patch.meta, MaybeUndefined::Undefined);
6940
6941 let malformed_meta = serde_json::from_value::<AgentMessage>(json!({
6942 "messageId": "msg_agent_c42b9",
6943 "_meta": false
6944 }))
6945 .unwrap();
6946 assert_eq!(malformed_meta.meta, MaybeUndefined::Undefined);
6947
6948 let patch = serde_json::from_value::<AgentThought>(json!({
6949 "messageId": "msg_thought_a12"
6950 }))
6951 .unwrap();
6952 assert_eq!(patch.content, MaybeUndefined::Undefined);
6953
6954 let clear = serde_json::from_value::<UserMessage>(json!({
6955 "messageId": "msg_user_8f7a1",
6956 "content": null
6957 }))
6958 .unwrap();
6959 assert_eq!(clear.content, MaybeUndefined::Null);
6960
6961 let clear_meta = serde_json::from_value::<UserMessage>(json!({
6962 "messageId": "msg_user_8f7a1",
6963 "_meta": null
6964 }))
6965 .unwrap();
6966 assert_eq!(clear_meta.meta, MaybeUndefined::Null);
6967
6968 let mut meta = Meta::new();
6969 meta.insert("source".to_string(), json!("replay"));
6970
6971 assert_eq!(
6972 serde_json::to_value(SessionUpdate::UserMessage(
6973 UserMessage::new("msg_user_8f7a1").meta(meta)
6974 ))
6975 .unwrap(),
6976 json!({
6977 "sessionUpdate": "user_message",
6978 "messageId": "msg_user_8f7a1",
6979 "_meta": {
6980 "source": "replay"
6981 }
6982 })
6983 );
6984
6985 assert_eq!(
6986 serde_json::to_value(SessionUpdate::UserMessage(
6987 UserMessage::new("msg_user_8f7a1").meta(None::<Meta>)
6988 ))
6989 .unwrap(),
6990 json!({
6991 "sessionUpdate": "user_message",
6992 "messageId": "msg_user_8f7a1",
6993 "_meta": null
6994 })
6995 );
6996 }
6997
6998 #[test]
6999 fn test_usage_update_serialization() {
7000 use serde_json::json;
7001
7002 assert_eq!(
7003 serde_json::to_value(SessionUpdate::UsageUpdate(UsageUpdate::new(
7004 53_000, 200_000
7005 )))
7006 .unwrap(),
7007 json!({
7008 "sessionUpdate": "usage_update",
7009 "used": 53000,
7010 "size": 200_000
7011 })
7012 );
7013
7014 assert_eq!(
7015 serde_json::to_value(SessionUpdate::UsageUpdate(
7016 UsageUpdate::new(53_000, 200_000).cost(Cost::new(0.045, "USD"))
7017 ))
7018 .unwrap(),
7019 json!({
7020 "sessionUpdate": "usage_update",
7021 "used": 53000,
7022 "size": 200_000,
7023 "cost": {
7024 "amount": 0.045,
7025 "currency": "USD"
7026 }
7027 })
7028 );
7029
7030 let SessionUpdate::UsageUpdate(update) = serde_json::from_value(json!({
7031 "sessionUpdate": "usage_update",
7032 "used": 53000,
7033 "size": 200_000,
7034 "cost": null
7035 }))
7036 .unwrap() else {
7037 panic!("expected usage update");
7038 };
7039
7040 assert_eq!(update.cost, MaybeUndefined::Null);
7041
7042 let SessionUpdate::UsageUpdate(update) = serde_json::from_value(json!({
7043 "sessionUpdate": "usage_update",
7044 "used": 53000,
7045 "size": 200_000
7046 }))
7047 .unwrap() else {
7048 panic!("expected usage update");
7049 };
7050
7051 assert_eq!(update.cost, MaybeUndefined::Undefined);
7052 }
7053
7054 #[test]
7055 fn usage_update_meta_is_a_patch() {
7056 use serde_json::json;
7057
7058 let wire = |meta: Option<serde_json::Value>| {
7059 let mut wire = json!({"sessionUpdate": "usage_update", "used": 1, "size": 2});
7060 if let Some(meta) = meta {
7061 wire["_meta"] = meta;
7062 }
7063 wire
7064 };
7065 let patch = json!({"com.example/a": 1, "com.example/b": null});
7066 for (meta, expected) in [
7067 (None, MaybeUndefined::Undefined),
7068 (Some(json!(null)), MaybeUndefined::Null),
7069 (
7070 Some(patch.clone()),
7071 MaybeUndefined::Value(patch.as_object().unwrap().clone()),
7072 ),
7073 ] {
7074 let SessionUpdate::UsageUpdate(update) =
7075 serde_json::from_value(wire(meta.clone())).unwrap()
7076 else {
7077 panic!("expected usage update");
7078 };
7079 assert_eq!(update.meta, expected);
7080 assert_eq!(
7081 serde_json::to_value(SessionUpdate::UsageUpdate(update)).unwrap(),
7082 wire(meta)
7083 );
7084 }
7085 }
7086
7087 #[test]
7088 fn error_stop_reason_carries_failure_beside_discriminator() {
7089 use crate::v2::{Error, ErrorStopReason};
7090 use serde_json::json;
7091
7092 let update =
7093 SessionUpdate::StateUpdate(StateUpdate::Idle(IdleStateUpdate::new().stop_reason(
7094 StopReason::from(ErrorStopReason::new().error(Error::auth_required())),
7095 )));
7096 let wire = json!({
7097 "sessionUpdate": "state_update",
7098 "state": "idle",
7099 "stopReason": "error",
7100 "error": { "code": -32000, "message": "Authentication required" }
7101 });
7102 assert_eq!(serde_json::to_value(&update).unwrap(), wire);
7103 assert_eq!(
7104 serde_json::from_value::<SessionUpdate>(wire).unwrap(),
7105 update
7106 );
7107
7108 let with_data =
7109 StateUpdate::Idle(IdleStateUpdate::new().stop_reason(StopReason::from(
7110 ErrorStopReason::new().error(
7111 Error::new(-32099, "Provider unavailable").data(json!({ "status": 503 })),
7112 ),
7113 )));
7114 let wire = json!({
7115 "state": "idle",
7116 "stopReason": "error",
7117 "error": {
7118 "code": -32099,
7119 "message": "Provider unavailable",
7120 "data": { "status": 503 }
7121 }
7122 });
7123 assert_eq!(serde_json::to_value(&with_data).unwrap(), wire);
7124 assert_eq!(
7125 serde_json::from_value::<StateUpdate>(wire).unwrap(),
7126 with_data
7127 );
7128
7129 let without_details = StateUpdate::Idle(
7132 IdleStateUpdate::new().stop_reason(StopReason::from(ErrorStopReason::new())),
7133 );
7134 for error in [
7135 None,
7136 Some(json!(null)),
7137 Some(json!("failed")),
7138 Some(json!({ "message": "missing code" })),
7139 ] {
7140 let mut wire = json!({ "state": "idle", "stopReason": "error" });
7141 if let Some(error) = error {
7142 wire["error"] = error;
7143 }
7144 assert_eq!(
7145 serde_json::from_value::<StateUpdate>(wire).unwrap(),
7146 without_details
7147 );
7148 }
7149 assert_eq!(
7150 serde_json::to_value(&without_details).unwrap(),
7151 json!({ "state": "idle", "stopReason": "error" })
7152 );
7153
7154 let parsed: StateUpdate = serde_json::from_value(json!({
7158 "state": "idle",
7159 "stopReason": "end_turn",
7160 "error": { "code": -32603, "message": "Internal error" }
7161 }))
7162 .unwrap();
7163 assert_eq!(
7164 parsed,
7165 StateUpdate::Idle(IdleStateUpdate::new().stop_reason(StopReason::EndTurn))
7166 );
7167 }
7168
7169 #[test]
7170 fn flattened_stop_reason_keeps_open_enum_tolerance() {
7171 use crate::v2::OtherStopReason;
7172 use serde_json::json;
7173
7174 let meta: Meta = [("source".into(), json!("test"))].into_iter().collect();
7175
7176 for stop_reason in [None, Some(json!(null)), Some(json!(true)), Some(json!({}))] {
7179 let mut wire = json!({ "state": "idle", "_meta": { "source": "test" } });
7180 if let Some(stop_reason) = stop_reason {
7181 wire["stopReason"] = stop_reason;
7182 }
7183 let StateUpdate::Idle(idle) = serde_json::from_value(wire).unwrap() else {
7184 panic!("expected idle state update");
7185 };
7186 assert_eq!(idle.stop_reason, None);
7187 assert_eq!(idle.meta, Some(meta.clone()));
7188 }
7189
7190 let wire = json!({
7193 "state": "idle",
7194 "stopReason": "_paused",
7195 "resumeAfter": 30,
7196 "_meta": { "source": "test" }
7197 });
7198 let parsed: StateUpdate = serde_json::from_value(wire.clone()).unwrap();
7199 let expected = StateUpdate::Idle(
7200 IdleStateUpdate::new()
7201 .stop_reason(StopReason::Other(OtherStopReason::new(
7202 "_paused",
7203 [("resumeAfter".into(), json!(30))].into_iter().collect(),
7204 )))
7205 .meta(meta),
7206 );
7207 assert_eq!(parsed, expected);
7208 assert_eq!(serde_json::to_value(&parsed).unwrap(), wire);
7209 }
7210
7211 #[test]
7212 fn known_stop_reasons_are_never_read_as_other() {
7213 use crate::v2::{ErrorStopReason, OtherStopReason};
7214 use serde_json::json;
7215
7216 let known = [
7217 StopReason::EndTurn,
7218 StopReason::MaxTokens,
7219 StopReason::MaxTurnRequests,
7220 StopReason::Refusal,
7221 StopReason::Cancelled,
7222 StopReason::Error(ErrorStopReason::new()),
7223 ];
7224 for stop_reason in &known {
7226 match stop_reason {
7227 StopReason::EndTurn
7228 | StopReason::MaxTokens
7229 | StopReason::MaxTurnRequests
7230 | StopReason::Refusal
7231 | StopReason::Cancelled
7232 | StopReason::Error(_)
7233 | StopReason::Other(_) => {}
7234 }
7235 }
7236
7237 for stop_reason in known {
7238 let update = StateUpdate::Idle(IdleStateUpdate::new().stop_reason(stop_reason));
7239 let wire = serde_json::to_value(&update).unwrap();
7240 assert_eq!(
7241 serde_json::from_value::<StateUpdate>(wire.clone()).unwrap(),
7242 update
7243 );
7244 assert!(
7245 serde_json::from_value::<OtherStopReason>(
7246 json!({ "stopReason": wire["stopReason"] })
7247 )
7248 .is_err(),
7249 "{} must not be accepted as a custom stop reason",
7250 wire["stopReason"]
7251 );
7252 }
7253 }
7254
7255 #[test]
7256 fn unknown_stop_reason_leaves_usage_on_the_idle_update() {
7257 use serde_json::json;
7258
7259 let usage = json!({ "totalTokens": 10, "inputTokens": 6, "outputTokens": 4 });
7260 let wire = json!({ "state": "idle", "stopReason": "_paused", "usage": usage });
7261 let StateUpdate::Idle(idle) = serde_json::from_value(wire.clone()).unwrap() else {
7262 panic!("expected idle state update");
7263 };
7264 let Some(StopReason::Other(other)) = &idle.stop_reason else {
7265 panic!("expected a custom stop reason");
7266 };
7267 assert!(other.fields.is_empty());
7268
7269 #[cfg(feature = "unstable_end_turn_token_usage")]
7270 {
7271 assert!(idle.usage.is_some());
7272 assert_eq!(serde_json::to_value(&idle).unwrap()["usage"], usage);
7273 }
7274 #[cfg(not(feature = "unstable_end_turn_token_usage"))]
7277 assert!(serde_json::to_value(&idle).unwrap().get("usage").is_none());
7278 }
7279
7280 #[test]
7281 fn test_state_update_serialization() {
7282 use serde_json::json;
7283
7284 assert_eq!(
7285 serde_json::to_value(SessionUpdate::StateUpdate(StateUpdate::Running(
7286 RunningStateUpdate::new()
7287 )))
7288 .unwrap(),
7289 json!({
7290 "sessionUpdate": "state_update",
7291 "state": "running"
7292 })
7293 );
7294
7295 assert_eq!(
7296 serde_json::to_value(SessionUpdate::StateUpdate(StateUpdate::Idle(
7297 IdleStateUpdate::new().stop_reason(StopReason::EndTurn)
7298 )))
7299 .unwrap(),
7300 json!({
7301 "sessionUpdate": "state_update",
7302 "state": "idle",
7303 "stopReason": "end_turn"
7304 })
7305 );
7306
7307 let SessionUpdate::StateUpdate(update) = serde_json::from_value(json!({
7308 "sessionUpdate": "state_update",
7309 "state": "requires_action"
7310 }))
7311 .unwrap() else {
7312 panic!("expected state update");
7313 };
7314
7315 assert!(matches!(update, StateUpdate::RequiresAction(_)));
7316
7317 let SessionUpdate::StateUpdate(StateUpdate::Idle(update)) = serde_json::from_value(json!({
7318 "sessionUpdate": "state_update",
7319 "state": "idle",
7320 "stopReason": null
7321 }))
7322 .unwrap() else {
7323 panic!("expected idle state update");
7324 };
7325
7326 assert_eq!(update.stop_reason, None);
7327
7328 let SessionUpdate::StateUpdate(StateUpdate::Other(update)) =
7329 serde_json::from_value(json!({
7330 "sessionUpdate": "state_update",
7331 "state": "_paused",
7332 "label": "Paused"
7333 }))
7334 .unwrap()
7335 else {
7336 panic!("expected unknown state update");
7337 };
7338
7339 assert_eq!(update.state, "_paused");
7340 assert_eq!(update.fields["label"], json!("Paused"));
7341 }
7342
7343 #[test]
7344 fn session_update_preserves_unknown_variant() {
7345 use serde_json::json;
7346
7347 let update: SessionUpdate = serde_json::from_value(json!({
7348 "sessionUpdate": "_status_badge",
7349 "label": "Indexing",
7350 "progress": 0.5
7351 }))
7352 .unwrap();
7353
7354 let SessionUpdate::Other(unknown) = update else {
7355 panic!("expected unknown session update");
7356 };
7357
7358 assert_eq!(unknown.session_update, "_status_badge");
7359 assert_eq!(unknown.fields.get("label"), Some(&json!("Indexing")));
7360 assert_eq!(unknown.fields.get("progress"), Some(&json!(0.5)));
7361
7362 assert_eq!(
7363 serde_json::to_value(SessionUpdate::Other(unknown)).unwrap(),
7364 json!({
7365 "sessionUpdate": "_status_badge",
7366 "label": "Indexing",
7367 "progress": 0.5
7368 })
7369 );
7370 }
7371
7372 #[test]
7373 fn terminal_session_updates_use_known_discriminators() {
7374 use serde_json::json;
7375
7376 assert_eq!(
7377 serde_json::to_value(SessionUpdate::TerminalUpdate(
7378 TerminalUpdate::new("term_1").command("cargo test")
7379 ))
7380 .unwrap(),
7381 json!({
7382 "sessionUpdate": "terminal_update",
7383 "terminalId": "term_1",
7384 "command": "cargo test"
7385 })
7386 );
7387 assert_eq!(
7388 serde_json::to_value(SessionUpdate::TerminalOutputChunk(
7389 TerminalOutputChunk::new("term_1", "dGVzdAo=")
7390 ))
7391 .unwrap(),
7392 json!({
7393 "sessionUpdate": "terminal_output_chunk",
7394 "terminalId": "term_1",
7395 "data": "dGVzdAo="
7396 })
7397 );
7398 }
7399
7400 #[test]
7401 fn session_update_does_not_hide_malformed_known_terminal_variants() {
7402 use serde_json::json;
7403
7404 assert!(
7405 serde_json::from_value::<SessionUpdate>(json!({
7406 "sessionUpdate": "terminal_update"
7407 }))
7408 .is_err()
7409 );
7410 assert!(
7411 serde_json::from_value::<SessionUpdate>(json!({
7412 "sessionUpdate": "terminal_output_chunk",
7413 "terminalId": "term_1"
7414 }))
7415 .is_err()
7416 );
7417 }
7418
7419 #[test]
7420 fn test_plan_update_serialization() {
7421 use serde_json::json;
7422
7423 let plan_update =
7424 SessionUpdate::PlanUpdate(PlanUpdate::new(crate::v2::PlanUpdateContent::items(
7425 "plan-1",
7426 vec![crate::v2::PlanEntry::new(
7427 "Step 1",
7428 crate::v2::PlanEntryPriority::High,
7429 crate::v2::PlanEntryStatus::Pending,
7430 )],
7431 )));
7432
7433 assert_eq!(
7434 serde_json::to_value(plan_update).unwrap(),
7435 json!({
7436 "sessionUpdate": "plan_update",
7437 "plan": {
7438 "type": "items",
7439 "planId": "plan-1",
7440 "entries": [
7441 {
7442 "content": "Step 1",
7443 "priority": "high",
7444 "status": "pending"
7445 }
7446 ]
7447 }
7448 })
7449 );
7450 }
7451
7452 #[test]
7453 fn plan_operations_round_trip_as_known_session_updates() {
7454 use serde_json::json;
7455
7456 let markdown = crate::v2::PlanUpdateContent::markdown("plan-1", "# Next steps");
7457 for (wire, expected) in [
7458 (
7459 json!({"sessionUpdate": "plan_update", "plan": {
7460 "type": "markdown", "planId": "plan-1", "content": "# Next steps"
7461 }}),
7462 SessionUpdate::PlanUpdate(PlanUpdate::new(markdown)),
7463 ),
7464 (
7465 json!({"sessionUpdate": "plan_removed", "planId": "plan-1"}),
7466 SessionUpdate::PlanRemoved(PlanRemoved::new("plan-1")),
7467 ),
7468 ] {
7469 assert_eq!(
7470 serde_json::from_value::<SessionUpdate>(wire.clone()).unwrap(),
7471 expected
7472 );
7473 assert_eq!(serde_json::to_value(expected).unwrap(), wire);
7474 }
7475 }
7476
7477 #[test]
7478 fn available_command_uses_type_discriminator() {
7479 use serde_json::json;
7480
7481 let command = AvailableCommand::Command(
7482 Command::new("web", "Search the web")
7483 .input(AvailableCommandInput::Text(TextCommandInput::new("Query"))),
7484 );
7485
7486 let json = serde_json::to_value(&command).unwrap();
7487 assert_eq!(
7488 json,
7489 json!({
7490 "type": "command",
7491 "name": "web",
7492 "description": "Search the web",
7493 "input": { "type": "text", "hint": "Query" }
7494 })
7495 );
7496
7497 let roundtripped: AvailableCommand = serde_json::from_value(json).unwrap();
7498 assert_eq!(roundtripped, command);
7499 assert_eq!(roundtripped.name(), "web");
7500 assert_eq!(roundtripped.description(), "Search the web");
7501 }
7502
7503 #[test]
7504 fn available_command_preserves_unknown_typed_variant() {
7505 use serde_json::json;
7506
7507 let payload = json!({
7508 "type": "_skill",
7509 "name": "pdf-processing",
7510 "description": "Extract text from PDFs",
7511 "uri": "skill://pdf-processing/SKILL.md",
7512 "_meta": { "example.com/source": "mcp" }
7513 });
7514 let command: AvailableCommand = serde_json::from_value(payload.clone()).unwrap();
7515
7516 assert_eq!(command.name(), "pdf-processing");
7517 assert_eq!(command.description(), "Extract text from PDFs");
7518 assert!(command.meta().is_some());
7519
7520 let AvailableCommand::Other(unknown) = &command else {
7521 panic!("expected unknown command");
7522 };
7523 assert_eq!(unknown.type_, "_skill");
7524 assert_eq!(
7525 unknown.fields.get("uri"),
7526 Some(&json!("skill://pdf-processing/SKILL.md"))
7527 );
7528 assert_eq!(serde_json::to_value(&command).unwrap(), payload);
7529 }
7530
7531 #[test]
7532 fn available_command_unknown_tolerates_invalid_meta() {
7533 use serde_json::json;
7534
7535 let command: AvailableCommand = serde_json::from_value(json!({
7536 "type": "_skill",
7537 "name": "pdf-processing",
7538 "description": "Extract text from PDFs",
7539 "_meta": "oops"
7540 }))
7541 .unwrap();
7542
7543 assert!(matches!(command, AvailableCommand::Other(_)));
7544 assert!(command.meta().is_none());
7545 }
7546
7547 #[test]
7548 fn available_command_unknown_does_not_hide_malformed_command_variant() {
7549 use serde_json::json;
7550
7551 assert!(
7553 serde_json::from_value::<AvailableCommand>(json!({
7554 "name": "test",
7555 "description": "Run project tests"
7556 }))
7557 .is_err()
7558 );
7559 assert!(
7560 serde_json::from_value::<AvailableCommand>(json!({
7561 "type": "command",
7562 "name": "test"
7563 }))
7564 .is_err()
7565 );
7566 assert!(
7567 serde_json::from_value::<OtherAvailableCommand>(json!({
7568 "type": "command",
7569 "name": "test",
7570 "description": "Run project tests"
7571 }))
7572 .is_err()
7573 );
7574 assert!(
7575 serde_json::from_value::<AvailableCommand>(json!({
7576 "type": "_skill",
7577 "name": "pdf-processing"
7578 }))
7579 .is_err()
7580 );
7581 }
7582
7583 #[cfg(feature = "unstable_agent_skills")]
7584 #[test]
7585 fn skill_command_uses_type_discriminator() {
7586 use serde_json::json;
7587
7588 let skill = AvailableCommand::Skill(
7589 Skill::new("pdf-processing", "Extract text and tables from PDF files").path(
7590 AbsolutePath::new("/home/alice/.agents/skills/pdf-processing/SKILL.md"),
7591 ),
7592 );
7593
7594 let wire = json!({
7595 "type": "skill",
7596 "name": "pdf-processing",
7597 "description": "Extract text and tables from PDF files",
7598 "path": "/home/alice/.agents/skills/pdf-processing/SKILL.md"
7599 });
7600 assert_eq!(serde_json::to_value(&skill).unwrap(), wire);
7601
7602 let roundtripped: AvailableCommand = serde_json::from_value(wire).unwrap();
7603 assert_eq!(roundtripped, skill);
7604 assert_eq!(roundtripped.name(), "pdf-processing");
7605 assert_eq!(
7606 roundtripped.description(),
7607 "Extract text and tables from PDF files"
7608 );
7609 assert!(roundtripped.meta().is_none());
7610
7611 assert_eq!(
7613 serde_json::to_value(AvailableCommand::Skill(Skill::new(
7614 "simplify",
7615 "Simplify the changed code"
7616 )))
7617 .unwrap(),
7618 json!({
7619 "type": "skill",
7620 "name": "simplify",
7621 "description": "Simplify the changed code"
7622 })
7623 );
7624 }
7625
7626 #[cfg(feature = "unstable_agent_skills")]
7627 #[test]
7628 fn skill_command_treats_invalid_display_fields_as_absent() {
7629 use serde_json::json;
7630
7631 let expected = AvailableCommand::Skill(Skill::new("pdf-processing", "Extract text"));
7632 for (field, value) in [
7633 ("path", json!(null)),
7634 ("path", json!(7)),
7635 ("path", json!({ "uri": "file:///SKILL.md" })),
7636 ("_meta", json!(null)),
7637 ("_meta", json!("oops")),
7638 ] {
7639 let mut wire = json!({
7640 "type": "skill",
7641 "name": "pdf-processing",
7642 "description": "Extract text"
7643 });
7644 wire[field] = value;
7645 assert_eq!(
7646 serde_json::from_value::<AvailableCommand>(wire).unwrap(),
7647 expected,
7648 "{field}"
7649 );
7650 }
7651 }
7652
7653 #[cfg(feature = "unstable_agent_skills")]
7654 #[test]
7655 fn skill_command_has_no_input_specification() {
7656 use serde_json::json;
7657
7658 let skill: AvailableCommand = serde_json::from_value(json!({
7660 "type": "skill",
7661 "name": "pdf-processing",
7662 "description": "Extract text",
7663 "input": { "type": "text", "hint": "file or instructions" }
7664 }))
7665 .unwrap();
7666 assert_eq!(
7667 skill,
7668 AvailableCommand::Skill(Skill::new("pdf-processing", "Extract text"))
7669 );
7670 assert!(serde_json::to_value(&skill).unwrap().get("input").is_none());
7671 }
7672
7673 #[cfg(feature = "unstable_agent_skills")]
7674 #[test]
7675 fn malformed_skill_command_is_skipped_and_never_preserved_as_unknown() {
7676 use serde_json::json;
7677
7678 for malformed in [
7679 json!({ "type": "skill", "name": "pdf-processing" }),
7680 json!({ "type": "skill", "description": "Extract text" }),
7681 json!({ "type": "skill", "name": 1, "description": "Extract text" }),
7682 ] {
7683 assert!(serde_json::from_value::<AvailableCommand>(malformed.clone()).is_err());
7684 assert!(serde_json::from_value::<OtherAvailableCommand>(malformed).is_err());
7685 }
7686
7687 let update: AvailableCommandsUpdate = serde_json::from_value(json!({
7689 "availableCommands": [
7690 { "type": "skill", "name": "pdf-processing", "description": "Extract text" },
7691 { "type": "skill", "name": "broken" },
7692 { "type": "command", "name": "test", "description": "Run project tests" }
7693 ]
7694 }))
7695 .unwrap();
7696 assert_eq!(
7697 update.available_commands,
7698 vec![
7699 AvailableCommand::Skill(Skill::new("pdf-processing", "Extract text")),
7700 AvailableCommand::Command(Command::new("test", "Run project tests")),
7701 ]
7702 );
7703 }
7704
7705 #[cfg(feature = "unstable_agent_skills")]
7706 #[test]
7707 fn skill_commands_capability_is_advertised_only_by_an_object() {
7708 use serde_json::json;
7709
7710 let capabilities = ClientCapabilities::new().session(
7711 ClientSessionCapabilities::new()
7712 .commands(CommandsCapabilities::new().skill(CommandsSkillCapabilities::new())),
7713 );
7714 let wire = json!({ "session": { "commands": { "skill": {} } } });
7715 assert_eq!(serde_json::to_value(&capabilities).unwrap(), wire);
7716 assert_eq!(
7717 serde_json::from_value::<ClientCapabilities>(wire).unwrap(),
7718 capabilities
7719 );
7720
7721 for unsupported in [
7723 json!({}),
7724 json!({ "session": null }),
7725 json!({ "session": {} }),
7726 json!({ "session": { "commands": null } }),
7727 json!({ "session": { "commands": {} } }),
7728 json!({ "session": { "commands": true } }),
7729 json!({ "session": { "commands": { "skill": null } } }),
7730 json!({ "session": { "commands": { "skill": true } } }),
7731 json!({ "session": { "commands": { "skill": "supported" } } }),
7732 ] {
7733 let capabilities: ClientCapabilities = serde_json::from_value(unsupported).unwrap();
7734 assert!(
7735 capabilities
7736 .session
7737 .and_then(|session| session.commands)
7738 .and_then(|commands| commands.skill)
7739 .is_none()
7740 );
7741 }
7742 }
7743
7744 #[cfg(all(
7745 feature = "unstable_agent_skills",
7746 feature = "unstable_prompt_suggestions"
7747 ))]
7748 #[test]
7749 fn client_session_capabilities_are_independent_of_each_other() {
7750 use serde_json::json;
7751
7752 let capabilities: ClientCapabilities = serde_json::from_value(json!({
7754 "session": {
7755 "promptSuggestions": true,
7756 "commands": { "skill": {} }
7757 }
7758 }))
7759 .unwrap();
7760 let session = capabilities.session.unwrap();
7761 assert!(session.prompt_suggestions.is_none());
7762 assert!(session.commands.unwrap().skill.is_some());
7763 }
7764
7765 #[cfg(all(feature = "schemars", feature = "unstable_agent_skills"))]
7766 #[test]
7767 fn skill_schemas_keep_acted_on_fields_strict() {
7768 use serde_json::json;
7769
7770 let skill = serde_json::to_value(schemars::schema_for!(Skill)).unwrap();
7771 assert_eq!(skill["required"], json!(["name", "description"]));
7772 for lenient in ["path", "_meta"] {
7773 assert_eq!(
7774 skill["properties"][lenient]["x-deserialize-default-on-error"], true,
7775 "{lenient}"
7776 );
7777 }
7778
7779 let reference =
7781 serde_json::to_value(schemars::schema_for!(crate::v2::SkillReference)).unwrap();
7782 assert_eq!(reference["required"], json!(["name"]));
7783 assert!(
7784 reference["properties"]["name"]
7785 .get("x-deserialize-default-on-error")
7786 .is_none()
7787 );
7788 }
7789
7790 #[test]
7791 fn available_command_input_preserves_unknown_typed_variant() {
7792 use serde_json::json;
7793
7794 let input: AvailableCommandInput = serde_json::from_value(json!({
7795 "type": "_choices",
7796 "hint": "Pick one",
7797 "options": ["fast", "careful"]
7798 }))
7799 .unwrap();
7800
7801 let AvailableCommandInput::Other(unknown) = input else {
7802 panic!("expected unknown command input");
7803 };
7804
7805 assert_eq!(unknown.type_, "_choices");
7806 assert_eq!(unknown.fields.get("hint"), Some(&json!("Pick one")));
7807 assert_eq!(
7808 unknown.fields.get("options"),
7809 Some(&json!(["fast", "careful"]))
7810 );
7811 assert_eq!(
7812 serde_json::to_value(AvailableCommandInput::Other(unknown)).unwrap(),
7813 json!({
7814 "type": "_choices",
7815 "hint": "Pick one",
7816 "options": ["fast", "careful"]
7817 })
7818 );
7819 }
7820
7821 #[test]
7822 fn available_command_input_text_uses_type_discriminator() {
7823 use serde_json::json;
7824
7825 let input = AvailableCommandInput::Text(TextCommandInput::new("Describe changes"));
7826
7827 let json = serde_json::to_value(&input).unwrap();
7828 assert_eq!(
7829 json,
7830 json!({
7831 "type": "text",
7832 "hint": "Describe changes"
7833 })
7834 );
7835
7836 let roundtripped: AvailableCommandInput = serde_json::from_value(json).unwrap();
7837 assert!(matches!(roundtripped, AvailableCommandInput::Text(_)));
7838 }
7839
7840 #[test]
7841 fn request_permission_subject_tool_call_uses_type_discriminator() {
7842 use serde_json::json;
7843
7844 let subject = RequestPermissionSubject::from(ToolCallUpdate::new("call_001"));
7845
7846 let json = serde_json::to_value(&subject).unwrap();
7847 assert_eq!(
7848 json,
7849 json!({
7850 "type": "tool_call",
7851 "toolCall": {
7852 "toolCallId": "call_001"
7853 }
7854 })
7855 );
7856
7857 let roundtripped: RequestPermissionSubject = serde_json::from_value(json).unwrap();
7858 assert!(matches!(
7859 roundtripped,
7860 RequestPermissionSubject::ToolCall(_)
7861 ));
7862 }
7863
7864 #[test]
7865 fn request_permission_subject_command_uses_type_discriminator() {
7866 use serde_json::json;
7867
7868 let mut meta = Meta::new();
7869 meta.insert("source".to_string(), json!("shell"));
7870 let subject = RequestPermissionSubject::from(
7871 CommandPermissionSubject::new("cargo test", "/workspace/project")
7872 .tool_call_id("call_001")
7873 .terminal_id("term_1")
7874 .meta(meta),
7875 );
7876
7877 let json = serde_json::to_value(&subject).unwrap();
7878 assert_eq!(
7879 json,
7880 json!({
7881 "type": "command",
7882 "command": "cargo test",
7883 "cwd": "/workspace/project",
7884 "toolCallId": "call_001",
7885 "terminalId": "term_1",
7886 "_meta": {
7887 "source": "shell"
7888 }
7889 })
7890 );
7891
7892 let roundtripped: RequestPermissionSubject = serde_json::from_value(json).unwrap();
7893 assert!(matches!(roundtripped, RequestPermissionSubject::Command(_)));
7894 }
7895
7896 #[test]
7897 fn command_permission_subject_treats_optional_association_nulls_as_omitted() {
7898 use serde_json::json;
7899
7900 let subject: RequestPermissionSubject = serde_json::from_value(json!({
7901 "type": "command",
7902 "command": "cargo test",
7903 "cwd": "/workspace/project",
7904 "toolCallId": null,
7905 "terminalId": null,
7906 "_meta": null
7907 }))
7908 .unwrap();
7909
7910 let RequestPermissionSubject::Command(subject) = subject else {
7911 panic!("expected command permission subject");
7912 };
7913 assert_eq!(subject.cwd, AbsolutePath::new("/workspace/project"));
7914 assert_eq!(subject.tool_call_id, None);
7915 assert_eq!(subject.terminal_id, None);
7916 assert_eq!(subject.meta, None);
7917 assert_eq!(
7918 serde_json::to_value(RequestPermissionSubject::Command(subject)).unwrap(),
7919 json!({
7920 "type": "command",
7921 "command": "cargo test",
7922 "cwd": "/workspace/project"
7923 })
7924 );
7925 }
7926
7927 #[test]
7928 fn request_permission_subject_preserves_unknown_variant() {
7929 use serde_json::json;
7930
7931 let subject: RequestPermissionSubject = serde_json::from_value(json!({
7932 "type": "_review",
7933 "reason": "needs-review",
7934 "retryAfterSeconds": 30
7935 }))
7936 .unwrap();
7937
7938 let RequestPermissionSubject::Other(unknown) = subject else {
7939 panic!("expected unknown permission subject");
7940 };
7941
7942 assert_eq!(unknown.type_, "_review");
7943 assert_eq!(unknown.fields.get("reason"), Some(&json!("needs-review")));
7944 assert_eq!(unknown.fields.get("retryAfterSeconds"), Some(&json!(30)));
7945 assert_eq!(
7946 serde_json::to_value(RequestPermissionSubject::Other(unknown)).unwrap(),
7947 json!({
7948 "type": "_review",
7949 "reason": "needs-review",
7950 "retryAfterSeconds": 30
7951 })
7952 );
7953 }
7954
7955 #[test]
7956 fn request_permission_subject_unknown_does_not_hide_malformed_known_variant() {
7957 use serde_json::json;
7958
7959 assert!(
7960 serde_json::from_value::<RequestPermissionSubject>(json!({
7961 "type": "tool_call"
7962 }))
7963 .is_err()
7964 );
7965 assert!(
7966 serde_json::from_value::<RequestPermissionSubject>(json!({
7967 "type": 1
7968 }))
7969 .is_err()
7970 );
7971 assert!(
7972 serde_json::from_value::<RequestPermissionSubject>(json!({
7973 "type": "command",
7974 "cwd": "/workspace/project"
7975 }))
7976 .is_err()
7977 );
7978 assert!(
7979 serde_json::from_value::<RequestPermissionSubject>(json!({
7980 "type": "command",
7981 "command": "cargo test"
7982 }))
7983 .is_err()
7984 );
7985 assert!(
7986 serde_json::from_value::<RequestPermissionSubject>(json!({
7987 "type": "command",
7988 "command": "cargo test",
7989 "cwd": null
7990 }))
7991 .is_err()
7992 );
7993 }
7994
7995 #[test]
7996 fn request_permission_title_and_description_are_separate_from_tool_call_content() {
7997 use serde_json::json;
7998
7999 let request =
8000 RequestPermissionRequest::new("sess_abc123def456", "Approve file edit?", Vec::new())
8001 .description("Allow this tool to edit src/main.rs?")
8002 .subject(RequestPermissionSubject::from(ToolCallUpdate::new(
8003 "call_001",
8004 )));
8005
8006 assert_eq!(
8007 serde_json::to_value(request).unwrap(),
8008 json!({
8009 "sessionId": "sess_abc123def456",
8010 "title": "Approve file edit?",
8011 "description": "Allow this tool to edit src/main.rs?",
8012 "subject": {
8013 "type": "tool_call",
8014 "toolCall": {
8015 "toolCallId": "call_001"
8016 }
8017 },
8018 "options": []
8019 })
8020 );
8021 }
8022
8023 #[test]
8024 fn request_permission_requires_title_and_allows_missing_subject() {
8025 use serde_json::json;
8026
8027 let request = RequestPermissionRequest::new(
8028 "sess_abc123def456",
8029 "Approve elevated permissions?",
8030 Vec::new(),
8031 );
8032
8033 assert_eq!(
8034 serde_json::to_value(request).unwrap(),
8035 json!({
8036 "sessionId": "sess_abc123def456",
8037 "title": "Approve elevated permissions?",
8038 "options": []
8039 })
8040 );
8041
8042 let options = json!([{ "optionId": "allow", "name": "Allow", "kind": "allow_once" }]);
8043 let missing_subject: RequestPermissionRequest = serde_json::from_value(json!({
8044 "sessionId": "sess_abc123def456",
8045 "title": "Approve elevated permissions?",
8046 "options": options
8047 }))
8048 .unwrap();
8049 assert!(missing_subject.subject.is_none());
8050
8051 let null_subject: RequestPermissionRequest = serde_json::from_value(json!({
8052 "sessionId": "sess_abc123def456",
8053 "title": "Approve elevated permissions?",
8054 "subject": null,
8055 "options": options
8056 }))
8057 .unwrap();
8058 assert!(null_subject.subject.is_none());
8059
8060 assert!(
8061 serde_json::from_value::<RequestPermissionRequest>(json!({
8062 "sessionId": "sess_abc123def456",
8063 "options": options
8064 }))
8065 .is_err()
8066 );
8067 }
8068
8069 #[test]
8070 fn request_permission_outcome_preserves_unknown_variant() {
8071 use serde_json::json;
8072
8073 let outcome: RequestPermissionOutcome = serde_json::from_value(json!({
8074 "outcome": "_defer",
8075 "reason": "needs-review",
8076 "retryAfterSeconds": 30
8077 }))
8078 .unwrap();
8079
8080 let RequestPermissionOutcome::Other(unknown) = outcome else {
8081 panic!("expected unknown permission outcome");
8082 };
8083
8084 assert_eq!(unknown.outcome, "_defer");
8085 assert_eq!(unknown.fields.get("reason"), Some(&json!("needs-review")));
8086 assert_eq!(unknown.fields.get("retryAfterSeconds"), Some(&json!(30)));
8087 assert_eq!(
8088 serde_json::to_value(RequestPermissionOutcome::Other(unknown)).unwrap(),
8089 json!({
8090 "outcome": "_defer",
8091 "reason": "needs-review",
8092 "retryAfterSeconds": 30
8093 })
8094 );
8095 }
8096
8097 #[test]
8098 fn request_permission_outcome_unknown_does_not_hide_malformed_known_variant() {
8099 use serde_json::json;
8100
8101 assert!(
8102 serde_json::from_value::<RequestPermissionOutcome>(json!({
8103 "outcome": "selected"
8104 }))
8105 .is_err()
8106 );
8107 assert!(
8108 serde_json::from_value::<RequestPermissionOutcome>(json!({
8109 "outcome": 1
8110 }))
8111 .is_err()
8112 );
8113 }
8114
8115 #[test]
8116 fn available_command_input_unknown_does_not_hide_malformed_text_variant() {
8117 use serde_json::json;
8118
8119 assert!(serde_json::from_value::<AvailableCommandInput>(json!({})).is_err());
8120 assert!(
8121 serde_json::from_value::<AvailableCommandInput>(json!({
8122 "hint": "Pick one"
8123 }))
8124 .is_err()
8125 );
8126 assert!(
8127 serde_json::from_value::<AvailableCommandInput>(json!({
8128 "type": 1,
8129 "hint": "Pick one"
8130 }))
8131 .is_err()
8132 );
8133 assert!(
8134 serde_json::from_value::<OtherAvailableCommandInput>(json!({
8135 "type": "text",
8136 "hint": "Pick one"
8137 }))
8138 .is_err()
8139 );
8140 }
8141
8142 #[cfg(feature = "unstable_mcp_over_acp")]
8143 #[test]
8144 fn test_agent_mcp_request_method_names() {
8145 use serde_json::json;
8146
8147 let params: serde_json::Map<String, serde_json::Value> =
8148 [("cursor".to_string(), json!("abc"))].into_iter().collect();
8149
8150 assert_eq!(CLIENT_METHOD_NAMES.mcp_message, "mcp/message");
8151 assert_eq!(
8152 AgentRequest::MessageMcpRequest(Box::new(MessageMcpRequest::new(
8153 "server-1",
8154 "req-1",
8155 "tools/list"
8156 )))
8157 .method(),
8158 "mcp/message"
8159 );
8160 assert_eq!(
8161 serde_json::to_value(
8162 MessageMcpRequest::new("server-1", "req-1", "tools/list").params(params)
8163 )
8164 .unwrap(),
8165 json!({
8166 "serverId": "server-1",
8167 "requestId": "req-1",
8168 "method": "tools/list",
8169 "params": { "cursor": "abc" }
8170 })
8171 );
8172
8173 let request_with_null_params: MessageMcpRequest = serde_json::from_value(json!({
8174 "serverId": "server-1",
8175 "requestId": "req-1",
8176 "method": "tools/list",
8177 "params": null,
8178 "_meta": null
8179 }))
8180 .unwrap();
8181 assert_eq!(request_with_null_params.params, None);
8182 assert_eq!(request_with_null_params.meta, None);
8183 for key in ["serverId", "requestId", "method"] {
8184 let mut value =
8185 json!({"serverId":"server-1", "requestId":"req-1", "method":"tools/list"});
8186 value.as_object_mut().unwrap().remove(key);
8187 assert!(serde_json::from_value::<MessageMcpRequest>(value).is_err());
8188 }
8189 for key in ["serverId", "requestId", "method"] {
8190 let mut value =
8191 json!({"serverId":"server-1", "requestId":"req-1", "method":"tools/list"});
8192 value[key] = serde_json::Value::Null;
8193 assert!(serde_json::from_value::<MessageMcpRequest>(value).is_err());
8194 }
8195 }
8196
8197 #[test]
8198 fn test_auth_capabilities_serialize_terminal_support_as_object() {
8199 use serde_json::json;
8200
8201 let capabilities = ClientAuthCapabilities::new().terminal(TerminalAuthCapabilities::new());
8202
8203 assert_eq!(
8204 serde_json::to_value(&capabilities).unwrap(),
8205 json!({
8206 "terminal": {}
8207 })
8208 );
8209
8210 let deserialized: ClientAuthCapabilities = serde_json::from_value(json!({
8211 "terminal": false
8212 }))
8213 .unwrap();
8214 assert!(deserialized.terminal.is_none());
8215 }
8216
8217 #[test]
8218 fn request_permission_request_rejects_malformed_options() {
8219 use serde_json::json;
8220
8221 assert!(
8222 serde_json::from_value::<RequestPermissionRequest>(json!({
8223 "sessionId": "sess-1",
8224 "title": "Run tool?",
8225 "options": "not-an-array"
8226 }))
8227 .is_err()
8228 );
8229 assert!(
8230 serde_json::from_value::<RequestPermissionRequest>(json!({
8231 "sessionId": "sess-1",
8232 "title": "Run tool?",
8233 "options": [{"optionId": "allow"}]
8234 }))
8235 .is_err()
8236 );
8237 assert!(
8239 serde_json::from_value::<RequestPermissionRequest>(json!({
8240 "sessionId": "sess-1",
8241 "title": "Run tool?",
8242 "options": []
8243 }))
8244 .is_err()
8245 );
8246 }
8247
8248 #[test]
8249 fn malformed_plan_removed_is_not_hidden_as_unknown_update() {
8250 use serde_json::json;
8251
8252 assert!(
8253 serde_json::from_value::<SessionUpdate>(json!({
8254 "sessionUpdate": "plan_removed"
8255 }))
8256 .is_err()
8257 );
8258 }
8259
8260 #[cfg(feature = "unstable_session_cursors")]
8261 #[test]
8262 fn cursor_updates_round_trip_and_patch_capabilities() {
8263 use serde_json::json;
8264
8265 let update = SessionUpdate::CursorUpdate(
8266 CursorUpdate::new("cur_1")
8267 .capabilities(CursorCapabilities::new())
8268 .anchor(CursorAnchor::UserMessage(CursorMessageAnchor::new(
8269 "msg_user_2",
8270 CursorAnchorPosition::Before,
8271 ))),
8272 );
8273 let wire = json!({
8274 "sessionUpdate": "cursor_update",
8275 "cursorId": "cur_1",
8276 "capabilities": {},
8277 "anchor": { "type": "user_message", "messageId": "msg_user_2", "position": "before" }
8278 });
8279 assert_eq!(serde_json::to_value(&update).unwrap(), wire);
8280 assert_eq!(
8281 serde_json::from_value::<SessionUpdate>(wire).unwrap(),
8282 update
8283 );
8284
8285 let SessionUpdate::CursorUpdate(omitted) = serde_json::from_value(json!({
8287 "sessionUpdate": "cursor_update",
8288 "cursorId": "cur_1"
8289 }))
8290 .unwrap() else {
8291 panic!("expected cursor update");
8292 };
8293 assert!(omitted.capabilities.is_undefined());
8294 assert_eq!(omitted.anchor, None);
8295 assert!(omitted.meta.is_undefined());
8296 assert_eq!(
8297 serde_json::to_value(SessionUpdate::CursorUpdate(CursorUpdate::new("cur_1"))).unwrap(),
8298 json!({ "sessionUpdate": "cursor_update", "cursorId": "cur_1" })
8299 );
8300
8301 let SessionUpdate::CursorUpdate(cleared) = serde_json::from_value(json!({
8303 "sessionUpdate": "cursor_update",
8304 "cursorId": "cur_1",
8305 "capabilities": null,
8306 "anchor": null
8307 }))
8308 .unwrap() else {
8309 panic!("expected cursor update");
8310 };
8311 assert!(cleared.capabilities.is_null());
8312 assert_eq!(cleared.anchor, None);
8313 assert_eq!(
8314 serde_json::to_value(SessionUpdate::CursorUpdate(
8315 CursorUpdate::new("cur_1").capabilities(None)
8316 ))
8317 .unwrap(),
8318 json!({ "sessionUpdate": "cursor_update", "cursorId": "cur_1", "capabilities": null })
8319 );
8320 }
8321
8322 #[cfg(feature = "unstable_session_cursors")]
8323 #[test]
8324 fn cursor_anchors_cover_each_entity_type_and_preserve_unknown_ones() {
8325 use serde_json::json;
8326
8327 for (anchor, wire) in [
8328 (
8329 CursorAnchor::AgentMessage(CursorMessageAnchor::new(
8330 "msg_agent_1",
8331 CursorAnchorPosition::After,
8332 )),
8333 json!({ "type": "agent_message", "messageId": "msg_agent_1", "position": "after" }),
8334 ),
8335 (
8336 CursorAnchor::AgentThought(CursorMessageAnchor::new(
8337 "msg_agent_1",
8338 CursorAnchorPosition::After,
8339 )),
8340 json!({ "type": "agent_thought", "messageId": "msg_agent_1", "position": "after" }),
8341 ),
8342 (
8343 CursorAnchor::SessionMessage(CursorMessageAnchor::new(
8344 "msg_session_1",
8345 CursorAnchorPosition::Before,
8346 )),
8347 json!({ "type": "session_message", "messageId": "msg_session_1", "position": "before" }),
8348 ),
8349 (
8350 CursorAnchor::ToolCall(CursorToolCallAnchor::new(
8351 "call_1",
8352 CursorAnchorPosition::After,
8353 )),
8354 json!({ "type": "tool_call", "toolCallId": "call_1", "position": "after" }),
8355 ),
8356 (
8357 CursorAnchor::Compaction(CursorCompactionAnchor::new(
8358 "cmp_1",
8359 CursorAnchorPosition::Before,
8360 )),
8361 json!({ "type": "compaction", "compactionId": "cmp_1", "position": "before" }),
8362 ),
8363 ] {
8364 assert_eq!(serde_json::to_value(&anchor).unwrap(), wire);
8365 assert_eq!(
8366 serde_json::from_value::<CursorAnchor>(wire).unwrap(),
8367 anchor
8368 );
8369 }
8370
8371 let wire = json!({ "type": "_acme_marker", "markerId": "mk_1", "position": "after" });
8373 let other = serde_json::from_value::<CursorAnchor>(wire.clone()).unwrap();
8374 assert!(matches!(other, CursorAnchor::Other(_)));
8375 assert_eq!(serde_json::to_value(&other).unwrap(), wire);
8376
8377 let wire =
8379 json!({ "type": "user_message", "messageId": "msg_user_2", "position": "inside" });
8380 let future = serde_json::from_value::<CursorAnchor>(wire.clone()).unwrap();
8381 assert_eq!(
8382 future,
8383 CursorAnchor::UserMessage(CursorMessageAnchor::new(
8384 "msg_user_2",
8385 CursorAnchorPosition::Other("inside".into()),
8386 ))
8387 );
8388 assert_eq!(serde_json::to_value(&future).unwrap(), wire);
8389 }
8390
8391 #[cfg(feature = "unstable_session_cursors")]
8392 #[test]
8393 fn malformed_cursor_anchor_fails_the_update() {
8394 use serde_json::json;
8395
8396 for anchor in [
8398 json!({ "type": "user_message", "position": "before" }),
8399 json!({ "type": "tool_call", "toolCallId": 7, "position": "after" }),
8400 json!({ "type": "compaction", "compactionId": "cmp_1" }),
8401 json!({ "messageId": "msg_user_2", "position": "before" }),
8402 json!("before"),
8403 ] {
8404 assert!(
8405 serde_json::from_value::<SessionUpdate>(json!({
8406 "sessionUpdate": "cursor_update",
8407 "cursorId": "cur_1",
8408 "anchor": anchor
8409 }))
8410 .is_err(),
8411 "{anchor}"
8412 );
8413 }
8414 assert!(
8416 serde_json::from_value::<SessionUpdate>(json!({ "sessionUpdate": "cursor_update" }))
8417 .is_err()
8418 );
8419 }
8420
8421 #[cfg(feature = "unstable_session_cursors")]
8422 #[test]
8423 fn malformed_cursor_capabilities_are_not_advertised() {
8424 use serde_json::json;
8425
8426 let SessionUpdate::CursorUpdate(update) = serde_json::from_value(json!({
8428 "sessionUpdate": "cursor_update",
8429 "cursorId": "cur_1",
8430 "capabilities": "fork"
8431 }))
8432 .unwrap() else {
8433 panic!("expected cursor update");
8434 };
8435 assert!(update.capabilities.is_undefined());
8436
8437 assert_eq!(
8439 serde_json::from_value::<CursorCapabilities>(json!({ "futureMethod": {} })).unwrap(),
8440 CursorCapabilities::new()
8441 );
8442
8443 #[cfg(feature = "unstable_session_fork")]
8444 {
8445 assert_eq!(
8446 serde_json::to_value(CursorCapabilities::new().fork(CursorForkCapabilities::new()))
8447 .unwrap(),
8448 json!({ "fork": {} })
8449 );
8450 assert_eq!(
8451 serde_json::from_value::<CursorCapabilities>(json!({ "fork": {} }))
8452 .unwrap()
8453 .fork,
8454 Some(CursorForkCapabilities::new())
8455 );
8456 for fork in [json!(null), json!(true), json!("yes")] {
8457 assert_eq!(
8458 serde_json::from_value::<CursorCapabilities>(json!({ "fork": fork }))
8459 .unwrap()
8460 .fork,
8461 None
8462 );
8463 }
8464 }
8465 }
8466}