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]
1682 pub fn description(mut self, description: impl IntoMaybeUndefined<String>) -> Self {
1683 self.description = description.into_maybe_undefined();
1684 self
1685 }
1686
1687 #[must_use]
1689 pub fn capabilities(
1690 mut self,
1691 capabilities: impl IntoMaybeUndefined<SubagentSessionCapabilities>,
1692 ) -> Self {
1693 self.capabilities = capabilities.into_maybe_undefined();
1694 self
1695 }
1696
1697 #[must_use]
1699 pub fn state(mut self, state: impl IntoMaybeUndefined<StateUpdate>) -> Self {
1700 self.state = state.into_maybe_undefined();
1701 self
1702 }
1703
1704 #[must_use]
1708 pub fn cwd(mut self, cwd: impl IntoMaybeUndefined<AbsolutePath>) -> Self {
1709 self.cwd = cwd.into_maybe_undefined();
1710 self
1711 }
1712
1713 #[must_use]
1717 pub fn additional_directories(
1718 mut self,
1719 additional_directories: impl IntoMaybeUndefined<Vec<AbsolutePath>>,
1720 ) -> Self {
1721 self.additional_directories = additional_directories.into_maybe_undefined();
1722 self
1723 }
1724
1725 #[must_use]
1730 pub fn meta(mut self, meta: impl IntoMaybeUndefined<Meta>) -> Self {
1731 self.meta = meta.into_maybe_undefined();
1732 self
1733 }
1734}
1735
1736#[serde_as]
1743#[skip_serializing_none]
1744#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1745#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1746#[serde(rename_all = "camelCase")]
1747#[non_exhaustive]
1748pub struct SubagentSessionCapabilities {
1749 #[serde_as(deserialize_as = "DefaultOnError")]
1753 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1754 #[serde(default)]
1755 pub cancel: Option<SessionCancelCapabilities>,
1756 #[serde_as(deserialize_as = "DefaultOnError")]
1762 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1763 #[serde(default)]
1764 #[serde(rename = "_meta")]
1765 pub meta: Option<Meta>,
1766}
1767
1768impl SubagentSessionCapabilities {
1769 #[must_use]
1771 pub fn new() -> Self {
1772 Self::default()
1773 }
1774
1775 #[must_use]
1777 pub fn cancel(mut self, cancel: impl IntoOption<SessionCancelCapabilities>) -> Self {
1778 self.cancel = cancel.into_option();
1779 self
1780 }
1781
1782 #[must_use]
1786 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1787 self.meta = meta.into_option();
1788 self
1789 }
1790}
1791
1792#[serde_as]
1796#[skip_serializing_none]
1797#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1798#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1799#[non_exhaustive]
1800pub struct SessionCancelCapabilities {
1801 #[serde_as(deserialize_as = "DefaultOnError")]
1807 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1808 #[serde(default)]
1809 #[serde(rename = "_meta")]
1810 pub meta: Option<Meta>,
1811}
1812
1813impl SessionCancelCapabilities {
1814 #[must_use]
1816 pub fn new() -> Self {
1817 Self::default()
1818 }
1819
1820 #[must_use]
1826 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1827 self.meta = meta.into_option();
1828 self
1829 }
1830}
1831
1832#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1838#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
1839#[cfg_attr(feature = "schemars", schemars(inline))]
1840#[cfg_attr(feature = "schemars", schemars(transform = other_session_update_schema))]
1841#[serde(rename_all = "camelCase")]
1842#[non_exhaustive]
1843pub struct OtherSessionUpdate {
1844 #[serde(rename = "sessionUpdate")]
1850 pub session_update: String,
1851 #[serde(flatten)]
1853 pub fields: IndexMap<String, serde_json::Value>,
1854}
1855
1856impl OtherSessionUpdate {
1857 #[must_use]
1859 pub fn new(
1860 session_update: impl Into<String>,
1861 mut fields: IndexMap<String, serde_json::Value>,
1862 ) -> Self {
1863 fields.shift_remove("sessionUpdate");
1864 Self {
1865 session_update: session_update.into(),
1866 fields,
1867 }
1868 }
1869}
1870
1871impl<'de> Deserialize<'de> for OtherSessionUpdate {
1872 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1873 where
1874 D: serde::Deserializer<'de>,
1875 {
1876 let mut fields = IndexMap::<String, serde_json::Value>::deserialize(deserializer)?;
1877 let session_update = fields
1878 .shift_remove("sessionUpdate")
1879 .ok_or_else(|| serde::de::Error::missing_field("sessionUpdate"))?;
1880 let serde_json::Value::String(session_update) = session_update else {
1881 return Err(serde::de::Error::custom("`sessionUpdate` must be a string"));
1882 };
1883
1884 if is_known_session_update(&session_update) {
1885 return Err(serde::de::Error::custom(format!(
1886 "known session update `{session_update}` did not match its schema"
1887 )));
1888 }
1889
1890 Ok(Self {
1891 session_update,
1892 fields,
1893 })
1894 }
1895}
1896
1897fn is_known_session_update(session_update: &str) -> bool {
1898 if session_update == "notice" {
1899 return true;
1900 }
1901 if matches!(
1902 session_update,
1903 "compaction_update" | "compaction_summary_chunk" | "replay_complete"
1904 ) {
1905 return true;
1906 }
1907 #[cfg(feature = "unstable_prompt_suggestions")]
1908 if session_update == "prompt_suggestions_update" {
1909 return true;
1910 }
1911 #[cfg(feature = "unstable_session_cursors")]
1912 if session_update == "cursor_update" {
1913 return true;
1914 }
1915 if matches!(
1916 session_update,
1917 "subagent_update" | "session_message" | "session_message_chunk"
1918 ) {
1919 return true;
1920 }
1921 matches!(
1922 session_update,
1923 "user_message_chunk"
1924 | "user_message"
1925 | "agent_message_chunk"
1926 | "agent_message"
1927 | "agent_thought_chunk"
1928 | "agent_thought"
1929 | "state_update"
1930 | "tool_call_content_chunk"
1931 | "tool_call_update"
1932 | "terminal_update"
1933 | "terminal_output_chunk"
1934 | "plan_update"
1935 | "plan_removed"
1936 | "available_commands_update"
1937 | "config_option_update"
1938 | "session_info_update"
1939 | "usage_update"
1940 )
1941}
1942
1943#[cfg(feature = "schemars")]
1944fn other_session_update_schema(schema: &mut Schema) {
1945 super::schema_util::reject_known_string_discriminators(
1946 schema,
1947 "sessionUpdate",
1948 &[
1949 "user_message_chunk",
1950 "user_message",
1951 "agent_message_chunk",
1952 "agent_message",
1953 "agent_thought_chunk",
1954 "agent_thought",
1955 "state_update",
1956 "tool_call_content_chunk",
1957 "tool_call_update",
1958 "terminal_update",
1959 "terminal_output_chunk",
1960 "plan_update",
1961 "plan_removed",
1962 "available_commands_update",
1963 "config_option_update",
1964 "session_info_update",
1965 "usage_update",
1966 "notice",
1967 "compaction_update",
1968 "compaction_summary_chunk",
1969 "replay_complete",
1970 #[cfg(feature = "unstable_prompt_suggestions")]
1971 "prompt_suggestions_update",
1972 #[cfg(feature = "unstable_session_cursors")]
1973 "cursor_update",
1974 "subagent_update",
1975 "session_message",
1976 "session_message_chunk",
1977 ],
1978 );
1979}
1980
1981#[serde_as]
1983#[skip_serializing_none]
1984#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1985#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1986#[serde(rename_all = "camelCase")]
1987#[non_exhaustive]
1988pub struct ConfigOptionUpdate {
1989 #[serde_as(deserialize_as = "VecSkipError<_>")]
1991 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-skip-invalid-items" = true)))]
1992 pub config_options: Vec<SessionConfigOption>,
1993 #[serde_as(deserialize_as = "DefaultOnError")]
1999 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2000 #[serde(default)]
2001 #[serde(rename = "_meta")]
2002 pub meta: Option<Meta>,
2003}
2004
2005impl ConfigOptionUpdate {
2006 #[must_use]
2008 pub fn new(config_options: Vec<SessionConfigOption>) -> Self {
2009 Self {
2010 config_options,
2011 meta: None,
2012 }
2013 }
2014
2015 #[must_use]
2021 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2022 self.meta = meta.into_option();
2023 self
2024 }
2025}
2026
2027#[serde_as]
2036#[skip_serializing_none]
2037#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2038#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2039#[serde(rename_all = "camelCase")]
2040#[non_exhaustive]
2041pub struct SessionInfoUpdate {
2042 #[serde_as(deserialize_as = "DefaultOnError")]
2044 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2045 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
2046 pub title: MaybeUndefined<String>,
2047 #[serde_as(deserialize_as = "DefaultOnError")]
2049 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "format" = "date-time")))]
2050 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
2051 pub updated_at: MaybeUndefined<String>,
2052 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
2061 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2062 #[serde(
2063 rename = "_meta",
2064 default,
2065 skip_serializing_if = "MaybeUndefined::is_undefined"
2066 )]
2067 pub meta: MaybeUndefined<Meta>,
2068}
2069
2070impl SessionInfoUpdate {
2071 #[must_use]
2073 pub fn new() -> Self {
2074 Self::default()
2075 }
2076
2077 #[must_use]
2079 pub fn title(mut self, title: impl IntoMaybeUndefined<String>) -> Self {
2080 self.title = title.into_maybe_undefined();
2081 self
2082 }
2083
2084 #[must_use]
2086 pub fn updated_at(mut self, updated_at: impl IntoMaybeUndefined<String>) -> Self {
2087 self.updated_at = updated_at.into_maybe_undefined();
2088 self
2089 }
2090
2091 #[must_use]
2096 pub fn meta(mut self, meta: impl IntoMaybeUndefined<Meta>) -> Self {
2097 self.meta = meta.into_maybe_undefined();
2098 self
2099 }
2100}
2101
2102#[serde_as]
2104#[skip_serializing_none]
2105#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2106#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
2107#[serde(rename_all = "camelCase")]
2108#[non_exhaustive]
2109pub struct UsageUpdate {
2110 pub used: u64,
2112 pub size: u64,
2114 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
2118 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2119 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
2120 pub cost: MaybeUndefined<Cost>,
2121 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
2130 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2131 #[serde(
2132 rename = "_meta",
2133 default,
2134 skip_serializing_if = "MaybeUndefined::is_undefined"
2135 )]
2136 pub meta: MaybeUndefined<Meta>,
2137}
2138
2139impl UsageUpdate {
2140 #[must_use]
2142 pub fn new(used: u64, size: u64) -> Self {
2143 Self {
2144 used,
2145 size,
2146 cost: MaybeUndefined::Undefined,
2147 meta: MaybeUndefined::Undefined,
2148 }
2149 }
2150
2151 #[must_use]
2153 pub fn cost(mut self, cost: impl IntoMaybeUndefined<Cost>) -> Self {
2154 self.cost = cost.into_maybe_undefined();
2155 self
2156 }
2157
2158 #[must_use]
2163 pub fn meta(mut self, meta: impl IntoMaybeUndefined<Meta>) -> Self {
2164 self.meta = meta.into_maybe_undefined();
2165 self
2166 }
2167}
2168
2169#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2210#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2211#[serde(tag = "state", rename_all = "snake_case")]
2212#[non_exhaustive]
2213pub enum StateUpdate {
2214 Running(RunningStateUpdate),
2216 Idle(IdleStateUpdate),
2218 RequiresAction(RequiresActionStateUpdate),
2220 Unknown(UnknownStateUpdate),
2223 #[serde(untagged)]
2235 Other(OtherStateUpdate),
2236}
2237
2238impl StateUpdate {
2239 #[must_use]
2247 pub fn background(&self) -> Option<&[BackgroundWork]> {
2248 match self {
2249 Self::Running(state) => state.background.as_deref(),
2250 Self::Idle(state) => state.background.as_deref(),
2251 Self::RequiresAction(state) => state.background.as_deref(),
2252 Self::Unknown(state) => state.background.as_deref(),
2253 Self::Other(_) => None,
2254 }
2255 }
2256}
2257
2258#[serde_as]
2260#[skip_serializing_none]
2261#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2262#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2263#[serde(rename_all = "camelCase")]
2264#[non_exhaustive]
2265pub struct RunningStateUpdate {
2266 #[serde_as(deserialize_as = "DefaultOnError")]
2275 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2276 #[serde(default)]
2277 pub background: Option<Vec<BackgroundWork>>,
2278 #[serde_as(deserialize_as = "DefaultOnError")]
2284 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2285 #[serde(default)]
2286 #[serde(rename = "_meta")]
2287 pub meta: Option<Meta>,
2288}
2289
2290impl RunningStateUpdate {
2291 #[must_use]
2293 pub fn new() -> Self {
2294 Self::default()
2295 }
2296
2297 #[must_use]
2299 pub fn background(mut self, background: impl IntoOption<Vec<BackgroundWork>>) -> Self {
2300 self.background = background.into_option();
2301 self
2302 }
2303
2304 #[must_use]
2310 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2311 self.meta = meta.into_option();
2312 self
2313 }
2314}
2315
2316#[serde_as]
2324#[skip_serializing_none]
2325#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2326#[cfg_attr(feature = "schemars", schemars(transform = idle_state_update_schema))]
2327#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2328#[serde(rename_all = "camelCase")]
2329#[non_exhaustive]
2330pub struct IdleStateUpdate {
2331 #[serde(flatten)]
2333 pub stop_reason: Option<StopReason>,
2334 #[cfg(feature = "unstable_end_turn_token_usage")]
2344 #[serde_as(deserialize_as = "DefaultOnError")]
2345 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2346 #[serde(default)]
2347 pub usage: Option<Box<Usage>>,
2348 #[serde_as(deserialize_as = "DefaultOnError")]
2357 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2358 #[serde(default)]
2359 pub background: Option<Vec<BackgroundWork>>,
2360 #[serde_as(deserialize_as = "DefaultOnError")]
2366 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2367 #[serde(default)]
2368 #[serde(rename = "_meta")]
2369 pub meta: Option<Meta>,
2370}
2371
2372impl IdleStateUpdate {
2373 #[must_use]
2375 pub fn new() -> Self {
2376 Self::default()
2377 }
2378
2379 #[must_use]
2381 pub fn stop_reason(mut self, stop_reason: impl IntoOption<StopReason>) -> Self {
2382 self.stop_reason = stop_reason.into_option();
2383 self
2384 }
2385
2386 #[cfg(feature = "unstable_end_turn_token_usage")]
2392 #[must_use]
2393 pub fn usage(mut self, usage: impl IntoOption<Usage>) -> Self {
2394 self.usage = usage.into_option().map(Box::new);
2395 self
2396 }
2397
2398 #[must_use]
2400 pub fn background(mut self, background: impl IntoOption<Vec<BackgroundWork>>) -> Self {
2401 self.background = background.into_option();
2402 self
2403 }
2404
2405 #[must_use]
2411 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2412 self.meta = meta.into_option();
2413 self
2414 }
2415}
2416
2417#[cfg(feature = "schemars")]
2426fn idle_state_update_schema(schema: &mut Schema) {
2427 if let Some(properties) = schema
2428 .get_mut("properties")
2429 .and_then(serde_json::Value::as_object_mut)
2430 {
2431 properties.insert(
2432 "stopReason".into(),
2433 serde_json::json!({
2434 "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)",
2435 "type": ["string", "null"],
2436 "x-deserialize-default-on-error": true
2437 }),
2438 );
2439 }
2440 let Some(variants) = schema
2441 .get_mut("anyOf")
2442 .and_then(serde_json::Value::as_array_mut)
2443 else {
2444 return;
2445 };
2446 for variant in variants {
2447 if variant.as_object().is_some_and(serde_json::Map::is_empty) {
2448 *variant = serde_json::json!({
2449 "title": "none",
2450 "description": "No stop reason: `stopReason` is omitted or `null`.",
2451 "type": "object",
2452 "properties": {
2453 "stopReason": { "type": "null" }
2454 }
2455 });
2456 }
2457 }
2458}
2459
2460#[serde_as]
2469#[skip_serializing_none]
2470#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2471#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2472#[serde(rename_all = "camelCase")]
2473#[non_exhaustive]
2474pub struct RequiresActionStateUpdate {
2475 #[serde_as(deserialize_as = "DefaultOnError")]
2484 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2485 #[serde(default)]
2486 pub background: Option<Vec<BackgroundWork>>,
2487 #[serde_as(deserialize_as = "DefaultOnError")]
2493 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2494 #[serde(default)]
2495 #[serde(rename = "_meta")]
2496 pub meta: Option<Meta>,
2497}
2498
2499impl RequiresActionStateUpdate {
2500 #[must_use]
2502 pub fn new() -> Self {
2503 Self::default()
2504 }
2505
2506 #[must_use]
2508 pub fn background(mut self, background: impl IntoOption<Vec<BackgroundWork>>) -> Self {
2509 self.background = background.into_option();
2510 self
2511 }
2512
2513 #[must_use]
2519 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2520 self.meta = meta.into_option();
2521 self
2522 }
2523}
2524
2525#[serde_as]
2538#[skip_serializing_none]
2539#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2540#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2541#[serde(rename_all = "camelCase")]
2542#[non_exhaustive]
2543pub struct UnknownStateUpdate {
2544 #[serde_as(deserialize_as = "DefaultOnError")]
2553 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2554 #[serde(default)]
2555 pub background: Option<Vec<BackgroundWork>>,
2556 #[serde_as(deserialize_as = "DefaultOnError")]
2562 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2563 #[serde(default, rename = "_meta")]
2564 pub meta: Option<Meta>,
2565}
2566
2567impl UnknownStateUpdate {
2568 #[must_use]
2570 pub fn new() -> Self {
2571 Self::default()
2572 }
2573
2574 #[must_use]
2576 pub fn background(mut self, background: impl IntoOption<Vec<BackgroundWork>>) -> Self {
2577 self.background = background.into_option();
2578 self
2579 }
2580
2581 #[must_use]
2583 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2584 self.meta = meta.into_option();
2585 self
2586 }
2587}
2588
2589#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2594#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
2595#[cfg_attr(feature = "schemars", schemars(inline))]
2596#[cfg_attr(feature = "schemars", schemars(transform = other_state_update_schema))]
2597#[serde(rename_all = "camelCase")]
2598#[non_exhaustive]
2599pub struct OtherStateUpdate {
2600 #[serde(rename = "state")]
2606 pub state: String,
2607 #[serde(flatten)]
2609 pub fields: IndexMap<String, serde_json::Value>,
2610}
2611
2612impl OtherStateUpdate {
2613 #[must_use]
2615 pub fn new(state: impl Into<String>, mut fields: IndexMap<String, serde_json::Value>) -> Self {
2616 fields.shift_remove("state");
2617 Self {
2618 state: state.into(),
2619 fields,
2620 }
2621 }
2622}
2623
2624impl<'de> Deserialize<'de> for OtherStateUpdate {
2625 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2626 where
2627 D: serde::Deserializer<'de>,
2628 {
2629 let mut fields = IndexMap::<String, serde_json::Value>::deserialize(deserializer)?;
2630 let state = fields
2631 .shift_remove("state")
2632 .ok_or_else(|| serde::de::Error::missing_field("state"))?;
2633 let serde_json::Value::String(state) = state else {
2634 return Err(serde::de::Error::custom("`state` must be a string"));
2635 };
2636
2637 if is_known_state_update(&state) {
2638 return Err(serde::de::Error::custom(format!(
2639 "known state update `{state}` did not match its schema"
2640 )));
2641 }
2642
2643 Ok(Self { state, fields })
2644 }
2645}
2646
2647const KNOWN_STATE_UPDATE_STATES: &[&str] = &["running", "idle", "requires_action", "unknown"];
2648
2649fn is_known_state_update(state: &str) -> bool {
2650 KNOWN_STATE_UPDATE_STATES.contains(&state)
2651}
2652
2653#[cfg(feature = "schemars")]
2654fn other_state_update_schema(schema: &mut Schema) {
2655 super::schema_util::reject_known_string_discriminators(
2656 schema,
2657 "state",
2658 KNOWN_STATE_UPDATE_STATES,
2659 );
2660}
2661
2662#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2672#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2673#[serde(tag = "type", rename_all = "snake_case")]
2674#[non_exhaustive]
2675pub enum BackgroundWork {
2676 Terminal(BackgroundTerminal),
2679 ToolCall(BackgroundToolCall),
2683 Subagent(BackgroundSubagent),
2686 #[serde(untagged)]
2695 Other(OtherBackgroundWork),
2696}
2697
2698#[serde_as]
2700#[skip_serializing_none]
2701#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2702#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2703#[serde(rename_all = "camelCase")]
2704#[non_exhaustive]
2705pub struct BackgroundTerminal {
2706 pub terminal_id: TerminalId,
2708 #[serde_as(deserialize_as = "DefaultOnError")]
2714 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2715 #[serde(default)]
2716 #[serde(rename = "_meta")]
2717 pub meta: Option<Meta>,
2718}
2719
2720impl BackgroundTerminal {
2721 #[must_use]
2723 pub fn new(terminal_id: impl Into<TerminalId>) -> Self {
2724 Self {
2725 terminal_id: terminal_id.into(),
2726 meta: None,
2727 }
2728 }
2729
2730 #[must_use]
2736 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2737 self.meta = meta.into_option();
2738 self
2739 }
2740}
2741
2742#[serde_as]
2744#[skip_serializing_none]
2745#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2746#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2747#[serde(rename_all = "camelCase")]
2748#[non_exhaustive]
2749pub struct BackgroundToolCall {
2750 pub tool_call_id: ToolCallId,
2752 #[serde_as(deserialize_as = "DefaultOnError")]
2758 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2759 #[serde(default)]
2760 #[serde(rename = "_meta")]
2761 pub meta: Option<Meta>,
2762}
2763
2764impl BackgroundToolCall {
2765 #[must_use]
2767 pub fn new(tool_call_id: impl Into<ToolCallId>) -> Self {
2768 Self {
2769 tool_call_id: tool_call_id.into(),
2770 meta: None,
2771 }
2772 }
2773
2774 #[must_use]
2780 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2781 self.meta = meta.into_option();
2782 self
2783 }
2784}
2785
2786#[serde_as]
2788#[skip_serializing_none]
2789#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2790#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2791#[serde(rename_all = "camelCase")]
2792#[non_exhaustive]
2793pub struct BackgroundSubagent {
2794 pub session_id: SessionId,
2796 #[serde_as(deserialize_as = "DefaultOnError")]
2802 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2803 #[serde(default)]
2804 #[serde(rename = "_meta")]
2805 pub meta: Option<Meta>,
2806}
2807
2808impl BackgroundSubagent {
2809 #[must_use]
2811 pub fn new(session_id: impl Into<SessionId>) -> Self {
2812 Self {
2813 session_id: session_id.into(),
2814 meta: None,
2815 }
2816 }
2817
2818 #[must_use]
2824 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2825 self.meta = meta.into_option();
2826 self
2827 }
2828}
2829
2830#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2835#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
2836#[cfg_attr(feature = "schemars", schemars(inline))]
2837#[cfg_attr(feature = "schemars", schemars(transform = other_background_work_schema))]
2838#[serde(rename_all = "camelCase")]
2839#[non_exhaustive]
2840pub struct OtherBackgroundWork {
2841 #[serde(rename = "type")]
2847 pub kind: String,
2848 #[serde(flatten)]
2850 pub fields: IndexMap<String, serde_json::Value>,
2851}
2852
2853impl OtherBackgroundWork {
2854 #[must_use]
2856 pub fn new(kind: impl Into<String>, mut fields: IndexMap<String, serde_json::Value>) -> Self {
2857 fields.shift_remove("type");
2858 Self {
2859 kind: kind.into(),
2860 fields,
2861 }
2862 }
2863}
2864
2865impl<'de> Deserialize<'de> for OtherBackgroundWork {
2866 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2867 where
2868 D: serde::Deserializer<'de>,
2869 {
2870 let mut fields = IndexMap::<String, serde_json::Value>::deserialize(deserializer)?;
2871 let kind = fields
2872 .shift_remove("type")
2873 .ok_or_else(|| serde::de::Error::missing_field("type"))?;
2874 let serde_json::Value::String(kind) = kind else {
2875 return Err(serde::de::Error::custom("`type` must be a string"));
2876 };
2877
2878 if KNOWN_BACKGROUND_WORK_TYPES.contains(&kind.as_str()) {
2879 return Err(serde::de::Error::custom(format!(
2880 "known background work `{kind}` did not match its schema"
2881 )));
2882 }
2883
2884 Ok(Self { kind, fields })
2885 }
2886}
2887
2888const KNOWN_BACKGROUND_WORK_TYPES: &[&str] = &["terminal", "tool_call", "subagent"];
2889
2890#[cfg(feature = "schemars")]
2891fn other_background_work_schema(schema: &mut Schema) {
2892 super::schema_util::reject_known_string_discriminators(
2893 schema,
2894 "type",
2895 KNOWN_BACKGROUND_WORK_TYPES,
2896 );
2897}
2898
2899#[serde_as]
2901#[skip_serializing_none]
2902#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2903#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
2904#[serde(rename_all = "camelCase")]
2905#[non_exhaustive]
2906pub struct Cost {
2907 pub amount: f64,
2909 pub currency: String,
2912 #[serde_as(deserialize_as = "DefaultOnError")]
2918 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2919 #[serde(default)]
2920 #[serde(rename = "_meta")]
2921 pub meta: Option<Meta>,
2922}
2923
2924impl Cost {
2925 #[must_use]
2927 pub fn new(amount: f64, currency: impl Into<String>) -> Self {
2928 Self {
2929 amount,
2930 currency: currency.into(),
2931 meta: None,
2932 }
2933 }
2934
2935 #[must_use]
2941 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2942 self.meta = meta.into_option();
2943 self
2944 }
2945}
2946
2947#[serde_as]
2949#[skip_serializing_none]
2950#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2951#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2952#[serde(rename_all = "camelCase")]
2953#[non_exhaustive]
2954pub struct ContentChunk {
2955 pub message_id: MessageId,
2960 pub content: ContentBlock,
2962 #[serde_as(deserialize_as = "DefaultOnError")]
2969 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2970 #[serde(default)]
2971 #[serde(rename = "_meta")]
2972 pub meta: Option<Meta>,
2973}
2974
2975impl ContentChunk {
2976 #[must_use]
2978 pub fn new(content: ContentBlock, message_id: impl Into<MessageId>) -> Self {
2979 Self {
2980 content,
2981 message_id: message_id.into(),
2982 meta: None,
2983 }
2984 }
2985
2986 #[must_use]
2992 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2993 self.meta = meta.into_option();
2994 self
2995 }
2996}
2997
2998#[serde_as]
3012#[skip_serializing_none]
3013#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3014#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3015#[serde(rename_all = "camelCase")]
3016#[non_exhaustive]
3017pub struct UserMessage {
3018 pub message_id: MessageId,
3020 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<VecSkipError<_>>>")]
3022 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
3023 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
3024 pub content: MaybeUndefined<Vec<ContentBlock>>,
3025 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
3034 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3035 #[serde(
3036 rename = "_meta",
3037 default,
3038 skip_serializing_if = "MaybeUndefined::is_undefined"
3039 )]
3040 pub meta: MaybeUndefined<Meta>,
3041}
3042
3043impl UserMessage {
3044 #[must_use]
3046 pub fn new(message_id: impl Into<MessageId>) -> Self {
3047 Self {
3048 message_id: message_id.into(),
3049 content: MaybeUndefined::Undefined,
3050 meta: MaybeUndefined::Undefined,
3051 }
3052 }
3053
3054 #[must_use]
3056 pub fn content(mut self, content: impl IntoMaybeUndefined<Vec<ContentBlock>>) -> Self {
3057 self.content = content.into_maybe_undefined();
3058 self
3059 }
3060
3061 #[must_use]
3066 pub fn meta(mut self, meta: impl IntoMaybeUndefined<Meta>) -> Self {
3067 self.meta = meta.into_maybe_undefined();
3068 self
3069 }
3070}
3071
3072#[serde_as]
3086#[skip_serializing_none]
3087#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3088#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3089#[serde(rename_all = "camelCase")]
3090#[non_exhaustive]
3091pub struct AgentMessage {
3092 pub message_id: MessageId,
3094 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<VecSkipError<_>>>")]
3096 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
3097 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
3098 pub content: MaybeUndefined<Vec<ContentBlock>>,
3099 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
3108 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3109 #[serde(
3110 rename = "_meta",
3111 default,
3112 skip_serializing_if = "MaybeUndefined::is_undefined"
3113 )]
3114 pub meta: MaybeUndefined<Meta>,
3115}
3116
3117impl AgentMessage {
3118 #[must_use]
3120 pub fn new(message_id: impl Into<MessageId>) -> Self {
3121 Self {
3122 message_id: message_id.into(),
3123 content: MaybeUndefined::Undefined,
3124 meta: MaybeUndefined::Undefined,
3125 }
3126 }
3127
3128 #[must_use]
3130 pub fn content(mut self, content: impl IntoMaybeUndefined<Vec<ContentBlock>>) -> Self {
3131 self.content = content.into_maybe_undefined();
3132 self
3133 }
3134
3135 #[must_use]
3140 pub fn meta(mut self, meta: impl IntoMaybeUndefined<Meta>) -> Self {
3141 self.meta = meta.into_maybe_undefined();
3142 self
3143 }
3144}
3145
3146#[serde_as]
3160#[skip_serializing_none]
3161#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3162#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3163#[serde(rename_all = "camelCase")]
3164#[non_exhaustive]
3165pub struct AgentThought {
3166 pub message_id: MessageId,
3168 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<VecSkipError<_>>>")]
3170 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
3171 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
3172 pub content: MaybeUndefined<Vec<ContentBlock>>,
3173 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
3182 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3183 #[serde(
3184 rename = "_meta",
3185 default,
3186 skip_serializing_if = "MaybeUndefined::is_undefined"
3187 )]
3188 pub meta: MaybeUndefined<Meta>,
3189}
3190
3191impl AgentThought {
3192 #[must_use]
3194 pub fn new(message_id: impl Into<MessageId>) -> Self {
3195 Self {
3196 message_id: message_id.into(),
3197 content: MaybeUndefined::Undefined,
3198 meta: MaybeUndefined::Undefined,
3199 }
3200 }
3201
3202 #[must_use]
3204 pub fn content(mut self, content: impl IntoMaybeUndefined<Vec<ContentBlock>>) -> Self {
3205 self.content = content.into_maybe_undefined();
3206 self
3207 }
3208
3209 #[must_use]
3214 pub fn meta(mut self, meta: impl IntoMaybeUndefined<Meta>) -> Self {
3215 self.meta = meta.into_maybe_undefined();
3216 self
3217 }
3218}
3219
3220#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3226#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
3227#[serde(transparent)]
3228#[from(forward)]
3229#[non_exhaustive]
3230pub struct MessageId(pub Arc<str>);
3231
3232impl MessageId {
3233 #[must_use]
3235 pub fn new(id: impl Into<Self>) -> Self {
3236 id.into()
3237 }
3238}
3239
3240#[cfg(feature = "unstable_prompt_suggestions")]
3257#[serde_as]
3258#[skip_serializing_none]
3259#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3260#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3261#[serde(rename_all = "camelCase")]
3262#[non_exhaustive]
3263pub struct PromptSuggestionsUpdate {
3264 #[serde_as(deserialize_as = "VecSkipError<_>")]
3269 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-skip-invalid-items" = true)))]
3270 pub suggestions: Vec<PromptSuggestion>,
3271 #[serde_as(deserialize_as = "DefaultOnError")]
3277 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3278 #[serde(default)]
3279 #[serde(rename = "_meta")]
3280 pub meta: Option<Meta>,
3281}
3282
3283#[cfg(feature = "unstable_prompt_suggestions")]
3284impl PromptSuggestionsUpdate {
3285 #[must_use]
3289 pub fn new(suggestions: Vec<PromptSuggestion>) -> Self {
3290 Self {
3291 suggestions,
3292 meta: None,
3293 }
3294 }
3295
3296 #[must_use]
3302 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3303 self.meta = meta.into_option();
3304 self
3305 }
3306}
3307
3308#[cfg(feature = "unstable_prompt_suggestions")]
3314#[serde_as]
3315#[skip_serializing_none]
3316#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3317#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3318#[serde(rename_all = "camelCase")]
3319#[non_exhaustive]
3320pub struct PromptSuggestion {
3321 #[cfg_attr(feature = "schemars", schemars(length(min = 1)))]
3333 pub prompt: Vec<ContentBlock>,
3334 #[serde_as(deserialize_as = "DefaultOnError")]
3340 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3341 #[serde(default)]
3342 #[serde(rename = "_meta")]
3343 pub meta: Option<Meta>,
3344}
3345
3346#[cfg(feature = "unstable_prompt_suggestions")]
3347impl PromptSuggestion {
3348 #[must_use]
3350 pub fn new(prompt: Vec<ContentBlock>) -> Self {
3351 Self { prompt, meta: None }
3352 }
3353
3354 #[must_use]
3360 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3361 self.meta = meta.into_option();
3362 self
3363 }
3364}
3365
3366#[serde_as]
3368#[skip_serializing_none]
3369#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3370#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3371#[serde(rename_all = "camelCase")]
3372#[non_exhaustive]
3373pub struct AvailableCommandsUpdate {
3374 #[serde_as(deserialize_as = "VecSkipError<_>")]
3376 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-skip-invalid-items" = true)))]
3377 pub available_commands: Vec<AvailableCommand>,
3378 #[serde_as(deserialize_as = "DefaultOnError")]
3384 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3385 #[serde(default)]
3386 #[serde(rename = "_meta")]
3387 pub meta: Option<Meta>,
3388}
3389
3390impl AvailableCommandsUpdate {
3391 #[must_use]
3393 pub fn new(available_commands: Vec<AvailableCommand>) -> Self {
3394 Self {
3395 available_commands,
3396 meta: None,
3397 }
3398 }
3399
3400 #[must_use]
3406 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3407 self.meta = meta.into_option();
3408 self
3409 }
3410}
3411
3412#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3416#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3417#[serde(tag = "type", rename_all = "snake_case")]
3418#[non_exhaustive]
3419pub enum AvailableCommand {
3420 Command(Command),
3422 #[cfg(feature = "unstable_agent_skills")]
3431 Skill(Skill),
3432 #[serde(untagged)]
3443 Other(OtherAvailableCommand),
3444}
3445
3446impl AvailableCommand {
3447 #[must_use]
3449 pub fn name(&self) -> &str {
3450 match self {
3451 Self::Command(c) => &c.name,
3452 #[cfg(feature = "unstable_agent_skills")]
3453 Self::Skill(c) => &c.name,
3454 Self::Other(c) => &c.name,
3455 }
3456 }
3457
3458 #[must_use]
3461 pub fn description(&self) -> &str {
3462 match self {
3463 Self::Command(c) => &c.description,
3464 #[cfg(feature = "unstable_agent_skills")]
3465 Self::Skill(c) => &c.description,
3466 Self::Other(c) => &c.description,
3467 }
3468 }
3469
3470 #[must_use]
3476 pub fn meta(&self) -> Option<&Meta> {
3477 match self {
3478 Self::Command(c) => c.meta.as_ref(),
3479 #[cfg(feature = "unstable_agent_skills")]
3480 Self::Skill(c) => c.meta.as_ref(),
3481 Self::Other(c) => c.fields.get("_meta").and_then(serde_json::Value::as_object),
3482 }
3483 }
3484}
3485
3486#[serde_as]
3488#[skip_serializing_none]
3489#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3490#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
3491#[cfg_attr(feature = "schemars", schemars(inline))]
3492#[cfg_attr(feature = "schemars", schemars(transform = other_available_command_schema))]
3493#[serde(rename_all = "camelCase")]
3494#[non_exhaustive]
3495pub struct OtherAvailableCommand {
3496 #[serde(rename = "type")]
3502 pub type_: String,
3503 pub name: String,
3505 pub description: String,
3508 #[serde(flatten)]
3511 pub fields: IndexMap<String, serde_json::Value>,
3512}
3513
3514impl OtherAvailableCommand {
3515 #[must_use]
3517 pub fn new(
3518 type_: impl Into<String>,
3519 name: impl Into<String>,
3520 description: impl Into<String>,
3521 mut fields: IndexMap<String, serde_json::Value>,
3522 ) -> Self {
3523 fields.shift_remove("type");
3524 fields.shift_remove("name");
3525 fields.shift_remove("description");
3526 Self {
3527 type_: type_.into(),
3528 name: name.into(),
3529 description: description.into(),
3530 fields,
3531 }
3532 }
3533}
3534
3535impl<'de> Deserialize<'de> for OtherAvailableCommand {
3536 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
3537 where
3538 D: serde::Deserializer<'de>,
3539 {
3540 #[derive(Deserialize)]
3541 struct RawOtherAvailableCommand {
3542 #[serde(rename = "type")]
3543 type_: String,
3544 name: String,
3545 description: String,
3546 #[serde(flatten)]
3547 fields: IndexMap<String, serde_json::Value>,
3548 }
3549
3550 let raw = RawOtherAvailableCommand::deserialize(deserializer)?;
3551 if is_known_available_command_type(&raw.type_) {
3552 return Err(serde::de::Error::custom(format!(
3553 "known available command type `{}` did not match its schema",
3554 raw.type_
3555 )));
3556 }
3557
3558 Ok(Self {
3559 type_: raw.type_,
3560 name: raw.name,
3561 description: raw.description,
3562 fields: raw.fields,
3563 })
3564 }
3565}
3566
3567const KNOWN_AVAILABLE_COMMAND_TYPES: &[&str] = &[
3568 "command",
3569 #[cfg(feature = "unstable_agent_skills")]
3570 "skill",
3571];
3572
3573fn is_known_available_command_type(type_: &str) -> bool {
3574 KNOWN_AVAILABLE_COMMAND_TYPES.contains(&type_)
3575}
3576
3577#[cfg(feature = "schemars")]
3578fn other_available_command_schema(schema: &mut Schema) {
3579 super::schema_util::reject_known_string_discriminators(
3580 schema,
3581 "type",
3582 KNOWN_AVAILABLE_COMMAND_TYPES,
3583 );
3584}
3585
3586#[serde_as]
3590#[skip_serializing_none]
3591#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3592#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3593#[serde(rename_all = "camelCase")]
3594#[non_exhaustive]
3595pub struct Command {
3596 pub name: String,
3600 pub description: String,
3603 #[serde_as(deserialize_as = "DefaultOnError")]
3607 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3608 #[serde(default)]
3609 pub input: Option<AvailableCommandInput>,
3610 #[serde_as(deserialize_as = "DefaultOnError")]
3616 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3617 #[serde(default)]
3618 #[serde(rename = "_meta")]
3619 pub meta: Option<Meta>,
3620}
3621
3622impl Command {
3623 #[must_use]
3625 pub fn new(name: impl Into<String>, description: impl Into<String>) -> Self {
3626 Self {
3627 name: name.into(),
3628 description: description.into(),
3629 input: None,
3630 meta: None,
3631 }
3632 }
3633
3634 #[must_use]
3636 pub fn input(mut self, input: impl IntoOption<AvailableCommandInput>) -> Self {
3637 self.input = input.into_option();
3638 self
3639 }
3640
3641 #[must_use]
3647 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3648 self.meta = meta.into_option();
3649 self
3650 }
3651}
3652
3653#[cfg(feature = "unstable_agent_skills")]
3669#[serde_as]
3670#[skip_serializing_none]
3671#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3672#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3673#[serde(rename_all = "camelCase")]
3674#[non_exhaustive]
3675pub struct Skill {
3676 pub name: String,
3682 pub description: String,
3685 #[serde_as(deserialize_as = "DefaultOnError")]
3691 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3692 #[serde(default)]
3693 pub path: Option<AbsolutePath>,
3694 #[serde_as(deserialize_as = "DefaultOnError")]
3700 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3701 #[serde(default)]
3702 #[serde(rename = "_meta")]
3703 pub meta: Option<Meta>,
3704}
3705
3706#[cfg(feature = "unstable_agent_skills")]
3707impl Skill {
3708 #[must_use]
3710 pub fn new(name: impl Into<String>, description: impl Into<String>) -> Self {
3711 Self {
3712 name: name.into(),
3713 description: description.into(),
3714 path: None,
3715 meta: None,
3716 }
3717 }
3718
3719 #[must_use]
3722 pub fn path(mut self, path: impl IntoOption<AbsolutePath>) -> Self {
3723 self.path = path.into_option();
3724 self
3725 }
3726
3727 #[must_use]
3733 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3734 self.meta = meta.into_option();
3735 self
3736 }
3737}
3738
3739#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3741#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3742#[serde(tag = "type", rename_all = "snake_case")]
3743#[non_exhaustive]
3744pub enum AvailableCommandInput {
3745 #[serde(rename = "text")]
3747 Text(TextCommandInput),
3748 #[serde(untagged)]
3759 Other(OtherAvailableCommandInput),
3760}
3761
3762#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3764#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
3765#[cfg_attr(feature = "schemars", schemars(inline))]
3766#[cfg_attr(feature = "schemars", schemars(transform = other_available_command_input_schema))]
3767#[serde(rename_all = "camelCase")]
3768#[non_exhaustive]
3769pub struct OtherAvailableCommandInput {
3770 #[serde(rename = "type")]
3776 pub type_: String,
3777 #[serde(flatten)]
3779 pub fields: IndexMap<String, serde_json::Value>,
3780}
3781
3782impl OtherAvailableCommandInput {
3783 #[must_use]
3785 pub fn new(type_: impl Into<String>, mut fields: IndexMap<String, serde_json::Value>) -> Self {
3786 fields.shift_remove("type");
3787 Self {
3788 type_: type_.into(),
3789 fields,
3790 }
3791 }
3792}
3793
3794impl<'de> Deserialize<'de> for OtherAvailableCommandInput {
3795 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
3796 where
3797 D: serde::Deserializer<'de>,
3798 {
3799 let mut fields = IndexMap::<String, serde_json::Value>::deserialize(deserializer)?;
3800 let type_ = fields
3801 .shift_remove("type")
3802 .ok_or_else(|| serde::de::Error::missing_field("type"))?;
3803 let serde_json::Value::String(type_) = type_ else {
3804 return Err(serde::de::Error::custom("`type` must be a string"));
3805 };
3806
3807 if is_known_available_command_input_type(&type_) {
3808 return Err(serde::de::Error::custom(format!(
3809 "known available command input type `{type_}` did not match its schema"
3810 )));
3811 }
3812
3813 Ok(Self { type_, fields })
3814 }
3815}
3816
3817const KNOWN_AVAILABLE_COMMAND_INPUT_TYPES: &[&str] = &["text"];
3818
3819fn is_known_available_command_input_type(type_: &str) -> bool {
3820 KNOWN_AVAILABLE_COMMAND_INPUT_TYPES.contains(&type_)
3821}
3822
3823#[cfg(feature = "schemars")]
3824fn other_available_command_input_schema(schema: &mut Schema) {
3825 super::schema_util::reject_known_string_discriminators(
3826 schema,
3827 "type",
3828 KNOWN_AVAILABLE_COMMAND_INPUT_TYPES,
3829 );
3830}
3831
3832#[serde_as]
3834#[skip_serializing_none]
3835#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3836#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3837#[serde(rename_all = "camelCase")]
3838#[non_exhaustive]
3839pub struct TextCommandInput {
3840 pub hint: String,
3843 #[serde_as(deserialize_as = "DefaultOnError")]
3849 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3850 #[serde(default)]
3851 #[serde(rename = "_meta")]
3852 pub meta: Option<Meta>,
3853}
3854
3855impl TextCommandInput {
3856 #[must_use]
3858 pub fn new(hint: impl Into<String>) -> Self {
3859 Self {
3860 hint: hint.into(),
3861 meta: None,
3862 }
3863 }
3864
3865 #[must_use]
3871 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3872 self.meta = meta.into_option();
3873 self
3874 }
3875}
3876
3877#[serde_as]
3885#[skip_serializing_none]
3886#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3887#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3888#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = SESSION_REQUEST_PERMISSION_METHOD_NAME)))]
3889#[cfg_attr(feature = "schemars", schemars(extend("x-scope" = {"session": ["sessionId"], "toolCall": ["subject.toolCall.toolCallId", "subject.toolCallId"]})))]
3890#[cfg_attr(feature = "schemars", schemars(extend("x-state" = {"session": [{"action": "upsert", "target": "toolCall", "id": "subject.toolCall.toolCallId", "value": "subject.toolCall"}]})))]
3891#[serde(rename_all = "camelCase")]
3892#[non_exhaustive]
3893pub struct RequestPermissionRequest {
3894 pub session_id: SessionId,
3896 pub title: String,
3901 #[serde_as(deserialize_as = "DefaultOnError")]
3908 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3909 #[serde(default)]
3910 pub description: Option<String>,
3911 #[serde(default)]
3915 pub subject: Option<RequestPermissionSubject>,
3916 #[cfg_attr(feature = "schemars", schemars(length(min = 1)))]
3919 #[serde(deserialize_with = "deserialize_permission_options")]
3920 pub options: Vec<PermissionOption>,
3921 #[serde_as(deserialize_as = "DefaultOnError")]
3927 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3928 #[serde(default)]
3929 #[serde(rename = "_meta")]
3930 pub meta: Option<Meta>,
3931}
3932
3933fn deserialize_permission_options<'de, D>(
3936 deserializer: D,
3937) -> Result<Vec<PermissionOption>, D::Error>
3938where
3939 D: serde::Deserializer<'de>,
3940{
3941 let options = Vec::<PermissionOption>::deserialize(deserializer)?;
3942 if options.is_empty() {
3943 return Err(serde::de::Error::invalid_length(
3944 0,
3945 &"at least one permission option",
3946 ));
3947 }
3948 Ok(options)
3949}
3950
3951impl RequestPermissionRequest {
3952 #[must_use]
3954 pub fn new(
3955 session_id: impl Into<SessionId>,
3956 title: impl Into<String>,
3957 options: Vec<PermissionOption>,
3958 ) -> Self {
3959 Self {
3960 session_id: session_id.into(),
3961 title: title.into(),
3962 description: None,
3963 subject: None,
3964 options,
3965 meta: None,
3966 }
3967 }
3968
3969 #[must_use]
3972 pub fn description(mut self, description: impl IntoOption<String>) -> Self {
3973 self.description = description.into_option();
3974 self
3975 }
3976
3977 #[must_use]
3979 pub fn subject(mut self, subject: impl IntoOption<RequestPermissionSubject>) -> Self {
3980 self.subject = subject.into_option();
3981 self
3982 }
3983
3984 #[must_use]
3990 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3991 self.meta = meta.into_option();
3992 self
3993 }
3994}
3995
3996#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3998#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3999#[serde(tag = "type", rename_all = "snake_case")]
4000#[non_exhaustive]
4001pub enum RequestPermissionSubject {
4002 ToolCall(Box<ToolCallPermissionSubject>),
4004 Command(CommandPermissionSubject),
4006 #[serde(untagged)]
4017 Other(OtherRequestPermissionSubject),
4018}
4019
4020impl From<ToolCallPermissionSubject> for RequestPermissionSubject {
4021 fn from(subject: ToolCallPermissionSubject) -> Self {
4022 Self::ToolCall(Box::new(subject))
4023 }
4024}
4025
4026impl From<ToolCallUpdate> for RequestPermissionSubject {
4027 fn from(tool_call: ToolCallUpdate) -> Self {
4028 ToolCallPermissionSubject::new(tool_call).into()
4029 }
4030}
4031
4032impl From<CommandPermissionSubject> for RequestPermissionSubject {
4033 fn from(subject: CommandPermissionSubject) -> Self {
4034 Self::Command(subject)
4035 }
4036}
4037
4038#[serde_as]
4040#[skip_serializing_none]
4041#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4042#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4043#[serde(rename_all = "camelCase")]
4044#[non_exhaustive]
4045pub struct ToolCallPermissionSubject {
4046 pub tool_call: ToolCallUpdate,
4052 #[serde_as(deserialize_as = "DefaultOnError")]
4058 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4059 #[serde(default)]
4060 #[serde(rename = "_meta")]
4061 pub meta: Option<Meta>,
4062}
4063
4064impl ToolCallPermissionSubject {
4065 #[must_use]
4067 pub fn new(tool_call: ToolCallUpdate) -> Self {
4068 Self {
4069 tool_call,
4070 meta: None,
4071 }
4072 }
4073
4074 #[must_use]
4080 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4081 self.meta = meta.into_option();
4082 self
4083 }
4084}
4085
4086#[serde_as]
4088#[skip_serializing_none]
4089#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4090#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4091#[serde(rename_all = "camelCase")]
4092#[non_exhaustive]
4093pub struct CommandPermissionSubject {
4094 pub command: String,
4096 pub cwd: AbsolutePath,
4098 #[serde_as(deserialize_as = "DefaultOnError")]
4100 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4101 #[serde(default)]
4102 pub tool_call_id: Option<ToolCallId>,
4103 #[serde_as(deserialize_as = "DefaultOnError")]
4105 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4106 #[serde(default)]
4107 pub terminal_id: Option<TerminalId>,
4108 #[serde_as(deserialize_as = "DefaultOnError")]
4114 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4115 #[serde(default)]
4116 #[serde(rename = "_meta")]
4117 pub meta: Option<Meta>,
4118}
4119
4120impl CommandPermissionSubject {
4121 #[must_use]
4123 pub fn new(command: impl Into<String>, cwd: impl Into<AbsolutePath>) -> Self {
4124 Self {
4125 command: command.into(),
4126 cwd: cwd.into(),
4127 tool_call_id: None,
4128 terminal_id: None,
4129 meta: None,
4130 }
4131 }
4132
4133 #[must_use]
4135 pub fn tool_call_id(mut self, tool_call_id: impl IntoOption<ToolCallId>) -> Self {
4136 self.tool_call_id = tool_call_id.into_option();
4137 self
4138 }
4139
4140 #[must_use]
4142 pub fn terminal_id(mut self, terminal_id: impl IntoOption<TerminalId>) -> Self {
4143 self.terminal_id = terminal_id.into_option();
4144 self
4145 }
4146
4147 #[must_use]
4149 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4150 self.meta = meta.into_option();
4151 self
4152 }
4153}
4154
4155#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4157#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
4158#[cfg_attr(feature = "schemars", schemars(inline))]
4159#[cfg_attr(feature = "schemars", schemars(transform = other_request_permission_subject_schema))]
4160#[serde(rename_all = "camelCase")]
4161#[non_exhaustive]
4162pub struct OtherRequestPermissionSubject {
4163 #[serde(rename = "type")]
4169 pub type_: String,
4170 #[serde(flatten)]
4172 pub fields: IndexMap<String, serde_json::Value>,
4173}
4174
4175impl OtherRequestPermissionSubject {
4176 #[must_use]
4178 pub fn new(type_: impl Into<String>, mut fields: IndexMap<String, serde_json::Value>) -> Self {
4179 fields.shift_remove("type");
4180 Self {
4181 type_: type_.into(),
4182 fields,
4183 }
4184 }
4185}
4186
4187impl<'de> Deserialize<'de> for OtherRequestPermissionSubject {
4188 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
4189 where
4190 D: serde::Deserializer<'de>,
4191 {
4192 let mut fields = IndexMap::<String, serde_json::Value>::deserialize(deserializer)?;
4193 let type_ = fields
4194 .shift_remove("type")
4195 .ok_or_else(|| serde::de::Error::missing_field("type"))?;
4196 let serde_json::Value::String(type_) = type_ else {
4197 return Err(serde::de::Error::custom("`type` must be a string"));
4198 };
4199
4200 if is_known_request_permission_subject_type(&type_) {
4201 return Err(serde::de::Error::custom(format!(
4202 "known request permission subject `{type_}` did not match its schema"
4203 )));
4204 }
4205
4206 Ok(Self { type_, fields })
4207 }
4208}
4209
4210fn is_known_request_permission_subject_type(type_: &str) -> bool {
4211 matches!(type_, "tool_call" | "command")
4212}
4213
4214#[cfg(feature = "schemars")]
4215fn other_request_permission_subject_schema(schema: &mut Schema) {
4216 super::schema_util::reject_known_string_discriminators(
4217 schema,
4218 "type",
4219 &["tool_call", "command"],
4220 );
4221}
4222
4223#[serde_as]
4225#[skip_serializing_none]
4226#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4227#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4228#[serde(rename_all = "camelCase")]
4229#[non_exhaustive]
4230pub struct PermissionOption {
4231 pub option_id: PermissionOptionId,
4233 pub name: String,
4235 pub kind: PermissionOptionKind,
4237 #[serde_as(deserialize_as = "DefaultOnError")]
4243 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4244 #[serde(default)]
4245 #[serde(rename = "_meta")]
4246 pub meta: Option<Meta>,
4247}
4248
4249impl PermissionOption {
4250 #[must_use]
4252 pub fn new(
4253 option_id: impl Into<PermissionOptionId>,
4254 name: impl Into<String>,
4255 kind: PermissionOptionKind,
4256 ) -> Self {
4257 Self {
4258 option_id: option_id.into(),
4259 name: name.into(),
4260 kind,
4261 meta: None,
4262 }
4263 }
4264
4265 #[must_use]
4271 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4272 self.meta = meta.into_option();
4273 self
4274 }
4275}
4276
4277#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4279#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
4280#[serde(transparent)]
4281#[from(forward)]
4282#[non_exhaustive]
4283pub struct PermissionOptionId(pub Arc<str>);
4284
4285impl PermissionOptionId {
4286 #[must_use]
4288 pub fn new(id: impl Into<Self>) -> Self {
4289 id.into()
4290 }
4291}
4292
4293#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4299#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4300#[serde(rename_all = "snake_case")]
4301#[non_exhaustive]
4302pub enum PermissionOptionKind {
4303 AllowOnce,
4305 AllowAlways,
4307 RejectOnce,
4309 RejectAlways,
4311 #[serde(untagged)]
4317 Other(String),
4318}
4319
4320#[serde_as]
4322#[skip_serializing_none]
4323#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4324#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4325#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = SESSION_REQUEST_PERMISSION_METHOD_NAME)))]
4326#[serde(rename_all = "camelCase")]
4327#[non_exhaustive]
4328pub struct RequestPermissionResponse {
4329 pub outcome: RequestPermissionOutcome,
4331 #[serde_as(deserialize_as = "DefaultOnError")]
4337 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4338 #[serde(default)]
4339 #[serde(rename = "_meta")]
4340 pub meta: Option<Meta>,
4341}
4342
4343impl RequestPermissionResponse {
4344 #[must_use]
4346 pub fn new(outcome: RequestPermissionOutcome) -> Self {
4347 Self {
4348 outcome,
4349 meta: None,
4350 }
4351 }
4352
4353 #[must_use]
4359 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4360 self.meta = meta.into_option();
4361 self
4362 }
4363}
4364
4365#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4367#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4368#[serde(tag = "outcome", rename_all = "snake_case")]
4369#[non_exhaustive]
4370pub enum RequestPermissionOutcome {
4371 Cancelled(CancelledPermissionOutcome),
4382 #[serde(rename_all = "camelCase")]
4389 Selected(SelectedPermissionOutcome),
4390 #[serde(untagged)]
4401 Other(OtherRequestPermissionOutcome),
4402}
4403
4404#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4410#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
4411#[cfg_attr(feature = "schemars", schemars(inline))]
4412#[cfg_attr(feature = "schemars", schemars(transform = other_request_permission_outcome_schema))]
4413#[serde(rename_all = "camelCase")]
4414#[non_exhaustive]
4415pub struct OtherRequestPermissionOutcome {
4416 pub outcome: String,
4422 #[serde(flatten)]
4424 pub fields: IndexMap<String, serde_json::Value>,
4425}
4426
4427impl OtherRequestPermissionOutcome {
4428 #[must_use]
4430 pub fn new(
4431 outcome: impl Into<String>,
4432 mut fields: IndexMap<String, serde_json::Value>,
4433 ) -> Self {
4434 fields.shift_remove("outcome");
4435 Self {
4436 outcome: outcome.into(),
4437 fields,
4438 }
4439 }
4440}
4441
4442impl<'de> Deserialize<'de> for OtherRequestPermissionOutcome {
4443 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
4444 where
4445 D: serde::Deserializer<'de>,
4446 {
4447 let mut fields = IndexMap::<String, serde_json::Value>::deserialize(deserializer)?;
4448 let outcome = fields
4449 .shift_remove("outcome")
4450 .ok_or_else(|| serde::de::Error::missing_field("outcome"))?;
4451 let serde_json::Value::String(outcome) = outcome else {
4452 return Err(serde::de::Error::custom("`outcome` must be a string"));
4453 };
4454
4455 if is_known_request_permission_outcome(&outcome) {
4456 return Err(serde::de::Error::custom(format!(
4457 "known request permission outcome `{outcome}` did not match its schema"
4458 )));
4459 }
4460
4461 Ok(Self { outcome, fields })
4462 }
4463}
4464
4465fn is_known_request_permission_outcome(outcome: &str) -> bool {
4466 matches!(outcome, "cancelled" | "selected")
4467}
4468
4469#[cfg(feature = "schemars")]
4470fn other_request_permission_outcome_schema(schema: &mut Schema) {
4471 super::schema_util::reject_known_string_discriminators(
4472 schema,
4473 "outcome",
4474 &["cancelled", "selected"],
4475 );
4476}
4477
4478#[serde_as]
4480#[skip_serializing_none]
4481#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4482#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4483#[serde(rename_all = "camelCase")]
4484#[non_exhaustive]
4485pub struct CancelledPermissionOutcome {
4486 #[serde_as(deserialize_as = "DefaultOnError")]
4492 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4493 #[serde(default)]
4494 #[serde(rename = "_meta")]
4495 pub meta: Option<Meta>,
4496}
4497
4498impl CancelledPermissionOutcome {
4499 #[must_use]
4501 pub fn new() -> Self {
4502 Self::default()
4503 }
4504
4505 #[must_use]
4511 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4512 self.meta = meta.into_option();
4513 self
4514 }
4515}
4516
4517impl From<CancelledPermissionOutcome> for RequestPermissionOutcome {
4518 fn from(outcome: CancelledPermissionOutcome) -> Self {
4519 Self::Cancelled(outcome)
4520 }
4521}
4522
4523#[serde_as]
4525#[skip_serializing_none]
4526#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4527#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4528#[serde(rename_all = "camelCase")]
4529#[non_exhaustive]
4530pub struct SelectedPermissionOutcome {
4531 pub option_id: PermissionOptionId,
4533 #[serde_as(deserialize_as = "DefaultOnError")]
4539 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4540 #[serde(default)]
4541 #[serde(rename = "_meta")]
4542 pub meta: Option<Meta>,
4543}
4544
4545impl SelectedPermissionOutcome {
4546 #[must_use]
4548 pub fn new(option_id: impl Into<PermissionOptionId>) -> Self {
4549 Self {
4550 option_id: option_id.into(),
4551 meta: None,
4552 }
4553 }
4554
4555 #[must_use]
4561 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4562 self.meta = meta.into_option();
4563 self
4564 }
4565}
4566
4567#[serde_as]
4576#[skip_serializing_none]
4577#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4578#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4579#[serde(rename_all = "camelCase")]
4580#[non_exhaustive]
4581pub struct ClientCapabilities {
4582 #[serde_as(deserialize_as = "DefaultOnError")]
4589 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4590 #[serde(default)]
4591 pub auth: Option<ClientAuthCapabilities>,
4592 #[serde_as(deserialize_as = "DefaultOnError")]
4598 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4599 #[serde(default)]
4600 pub elicitation: Option<ElicitationCapabilities>,
4601 #[cfg(any(
4611 feature = "unstable_prompt_suggestions",
4612 feature = "unstable_agent_skills"
4613 ))]
4614 #[serde_as(deserialize_as = "DefaultOnError")]
4615 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4616 #[serde(default)]
4617 pub session: Option<ClientSessionCapabilities>,
4618
4619 #[serde_as(deserialize_as = "DefaultOnError")]
4625 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4626 #[serde(default)]
4627 #[serde(rename = "_meta")]
4628 pub meta: Option<Meta>,
4629}
4630
4631impl ClientCapabilities {
4632 #[must_use]
4634 pub fn new() -> Self {
4635 Self::default()
4636 }
4637
4638 #[must_use]
4642 pub fn auth(mut self, auth: impl IntoOption<ClientAuthCapabilities>) -> Self {
4643 self.auth = auth.into_option();
4644 self
4645 }
4646
4647 #[must_use]
4650 pub fn elicitation(mut self, elicitation: impl IntoOption<ElicitationCapabilities>) -> Self {
4651 self.elicitation = elicitation.into_option();
4652 self
4653 }
4654
4655 #[cfg(any(
4661 feature = "unstable_prompt_suggestions",
4662 feature = "unstable_agent_skills"
4663 ))]
4664 #[must_use]
4665 pub fn session(mut self, session: impl IntoOption<ClientSessionCapabilities>) -> Self {
4666 self.session = session.into_option();
4667 self
4668 }
4669
4670 #[must_use]
4676 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4677 self.meta = meta.into_option();
4678 self
4679 }
4680}
4681
4682#[cfg(any(
4692 feature = "unstable_prompt_suggestions",
4693 feature = "unstable_agent_skills"
4694))]
4695#[serde_as]
4696#[skip_serializing_none]
4697#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4698#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4699#[serde(rename_all = "camelCase")]
4700#[non_exhaustive]
4701pub struct ClientSessionCapabilities {
4702 #[cfg(feature = "unstable_prompt_suggestions")]
4708 #[serde_as(deserialize_as = "DefaultOnError")]
4709 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4710 #[serde(default)]
4711 pub prompt_suggestions: Option<PromptSuggestionsCapabilities>,
4712 #[cfg(feature = "unstable_agent_skills")]
4717 #[serde_as(deserialize_as = "DefaultOnError")]
4718 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4719 #[serde(default)]
4720 pub commands: Option<CommandsCapabilities>,
4721 #[serde_as(deserialize_as = "DefaultOnError")]
4727 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4728 #[serde(default)]
4729 #[serde(rename = "_meta")]
4730 pub meta: Option<Meta>,
4731}
4732
4733#[cfg(any(
4734 feature = "unstable_prompt_suggestions",
4735 feature = "unstable_agent_skills"
4736))]
4737impl ClientSessionCapabilities {
4738 #[must_use]
4740 pub fn new() -> Self {
4741 Self::default()
4742 }
4743
4744 #[cfg(feature = "unstable_prompt_suggestions")]
4746 #[must_use]
4747 pub fn prompt_suggestions(
4748 mut self,
4749 prompt_suggestions: impl IntoOption<PromptSuggestionsCapabilities>,
4750 ) -> Self {
4751 self.prompt_suggestions = prompt_suggestions.into_option();
4752 self
4753 }
4754
4755 #[cfg(feature = "unstable_agent_skills")]
4757 #[must_use]
4758 pub fn commands(mut self, commands: impl IntoOption<CommandsCapabilities>) -> Self {
4759 self.commands = commands.into_option();
4760 self
4761 }
4762
4763 #[must_use]
4769 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4770 self.meta = meta.into_option();
4771 self
4772 }
4773}
4774
4775#[cfg(feature = "unstable_agent_skills")]
4785#[serde_as]
4786#[skip_serializing_none]
4787#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4788#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4789#[serde(rename_all = "camelCase")]
4790#[non_exhaustive]
4791pub struct CommandsCapabilities {
4792 #[serde_as(deserialize_as = "DefaultOnError")]
4798 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4799 #[serde(default)]
4800 pub skill: Option<CommandsSkillCapabilities>,
4801 #[serde_as(deserialize_as = "DefaultOnError")]
4807 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4808 #[serde(default)]
4809 #[serde(rename = "_meta")]
4810 pub meta: Option<Meta>,
4811}
4812
4813#[cfg(feature = "unstable_agent_skills")]
4814impl CommandsCapabilities {
4815 #[must_use]
4817 pub fn new() -> Self {
4818 Self::default()
4819 }
4820
4821 #[must_use]
4823 pub fn skill(mut self, skill: impl IntoOption<CommandsSkillCapabilities>) -> Self {
4824 self.skill = skill.into_option();
4825 self
4826 }
4827
4828 #[must_use]
4834 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4835 self.meta = meta.into_option();
4836 self
4837 }
4838}
4839
4840#[cfg(feature = "unstable_agent_skills")]
4849#[serde_as]
4850#[skip_serializing_none]
4851#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4852#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4853#[non_exhaustive]
4854pub struct CommandsSkillCapabilities {
4855 #[serde_as(deserialize_as = "DefaultOnError")]
4861 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4862 #[serde(default)]
4863 #[serde(rename = "_meta")]
4864 pub meta: Option<Meta>,
4865}
4866
4867#[cfg(feature = "unstable_agent_skills")]
4868impl CommandsSkillCapabilities {
4869 #[must_use]
4871 pub fn new() -> Self {
4872 Self::default()
4873 }
4874
4875 #[must_use]
4881 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4882 self.meta = meta.into_option();
4883 self
4884 }
4885}
4886
4887#[cfg(feature = "unstable_prompt_suggestions")]
4898#[serde_as]
4899#[skip_serializing_none]
4900#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4901#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4902#[serde(rename_all = "camelCase")]
4903#[non_exhaustive]
4904pub struct PromptSuggestionsCapabilities {
4905 #[serde_as(deserialize_as = "DefaultOnError")]
4910 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4911 #[serde(default)]
4912 pub image: Option<PromptSuggestionsImageCapabilities>,
4913 #[serde_as(deserialize_as = "DefaultOnError")]
4918 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4919 #[serde(default)]
4920 pub audio: Option<PromptSuggestionsAudioCapabilities>,
4921 #[serde_as(deserialize_as = "DefaultOnError")]
4927 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4928 #[serde(default)]
4929 pub embedded_context: Option<PromptSuggestionsEmbeddedContextCapabilities>,
4930 #[serde_as(deserialize_as = "DefaultOnError")]
4936 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4937 #[serde(default)]
4938 #[serde(rename = "_meta")]
4939 pub meta: Option<Meta>,
4940}
4941
4942#[cfg(feature = "unstable_prompt_suggestions")]
4943impl PromptSuggestionsCapabilities {
4944 #[must_use]
4946 pub fn new() -> Self {
4947 Self::default()
4948 }
4949
4950 #[must_use]
4952 pub fn image(mut self, image: impl IntoOption<PromptSuggestionsImageCapabilities>) -> Self {
4953 self.image = image.into_option();
4954 self
4955 }
4956
4957 #[must_use]
4959 pub fn audio(mut self, audio: impl IntoOption<PromptSuggestionsAudioCapabilities>) -> Self {
4960 self.audio = audio.into_option();
4961 self
4962 }
4963
4964 #[must_use]
4966 pub fn embedded_context(
4967 mut self,
4968 embedded_context: impl IntoOption<PromptSuggestionsEmbeddedContextCapabilities>,
4969 ) -> Self {
4970 self.embedded_context = embedded_context.into_option();
4971 self
4972 }
4973
4974 #[must_use]
4980 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4981 self.meta = meta.into_option();
4982 self
4983 }
4984}
4985
4986#[cfg(feature = "unstable_prompt_suggestions")]
4994#[serde_as]
4995#[skip_serializing_none]
4996#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4997#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4998#[non_exhaustive]
4999pub struct PromptSuggestionsImageCapabilities {
5000 #[serde_as(deserialize_as = "DefaultOnError")]
5006 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5007 #[serde(default)]
5008 #[serde(rename = "_meta")]
5009 pub meta: Option<Meta>,
5010}
5011
5012#[cfg(feature = "unstable_prompt_suggestions")]
5013impl PromptSuggestionsImageCapabilities {
5014 #[must_use]
5016 pub fn new() -> Self {
5017 Self::default()
5018 }
5019
5020 #[must_use]
5026 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5027 self.meta = meta.into_option();
5028 self
5029 }
5030}
5031
5032#[cfg(feature = "unstable_prompt_suggestions")]
5040#[serde_as]
5041#[skip_serializing_none]
5042#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5043#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5044#[non_exhaustive]
5045pub struct PromptSuggestionsAudioCapabilities {
5046 #[serde_as(deserialize_as = "DefaultOnError")]
5052 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5053 #[serde(default)]
5054 #[serde(rename = "_meta")]
5055 pub meta: Option<Meta>,
5056}
5057
5058#[cfg(feature = "unstable_prompt_suggestions")]
5059impl PromptSuggestionsAudioCapabilities {
5060 #[must_use]
5062 pub fn new() -> Self {
5063 Self::default()
5064 }
5065
5066 #[must_use]
5072 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5073 self.meta = meta.into_option();
5074 self
5075 }
5076}
5077
5078#[cfg(feature = "unstable_prompt_suggestions")]
5087#[serde_as]
5088#[skip_serializing_none]
5089#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5090#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5091#[non_exhaustive]
5092pub struct PromptSuggestionsEmbeddedContextCapabilities {
5093 #[serde_as(deserialize_as = "DefaultOnError")]
5099 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5100 #[serde(default)]
5101 #[serde(rename = "_meta")]
5102 pub meta: Option<Meta>,
5103}
5104
5105#[cfg(feature = "unstable_prompt_suggestions")]
5106impl PromptSuggestionsEmbeddedContextCapabilities {
5107 #[must_use]
5109 pub fn new() -> Self {
5110 Self::default()
5111 }
5112
5113 #[must_use]
5119 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5120 self.meta = meta.into_option();
5121 self
5122 }
5123}
5124
5125#[serde_as]
5131#[skip_serializing_none]
5132#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5133#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5134#[serde(rename_all = "camelCase")]
5135#[non_exhaustive]
5136pub struct ClientAuthCapabilities {
5137 #[serde_as(deserialize_as = "DefaultOnError")]
5144 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5145 #[serde(default)]
5146 pub terminal: Option<TerminalAuthCapabilities>,
5147 #[serde_as(deserialize_as = "DefaultOnError")]
5153 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5154 #[serde(default)]
5155 #[serde(rename = "_meta")]
5156 pub meta: Option<Meta>,
5157}
5158
5159impl ClientAuthCapabilities {
5160 #[must_use]
5162 pub fn new() -> Self {
5163 Self::default()
5164 }
5165
5166 #[must_use]
5173 pub fn terminal(mut self, terminal: impl IntoOption<TerminalAuthCapabilities>) -> Self {
5174 self.terminal = terminal.into_option();
5175 self
5176 }
5177
5178 #[must_use]
5184 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5185 self.meta = meta.into_option();
5186 self
5187 }
5188}
5189
5190#[serde_as]
5196#[skip_serializing_none]
5197#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5198#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5199#[non_exhaustive]
5200pub struct TerminalAuthCapabilities {
5201 #[serde_as(deserialize_as = "DefaultOnError")]
5207 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5208 #[serde(default)]
5209 #[serde(rename = "_meta")]
5210 pub meta: Option<Meta>,
5211}
5212
5213impl TerminalAuthCapabilities {
5214 #[must_use]
5216 pub fn new() -> Self {
5217 Self::default()
5218 }
5219
5220 #[must_use]
5226 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5227 self.meta = meta.into_option();
5228 self
5229 }
5230}
5231
5232#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5238#[non_exhaustive]
5239pub struct ClientMethodNames {
5240 pub session_request_permission: &'static str,
5242 pub session_update: &'static str,
5244 #[cfg(feature = "unstable_mcp_over_acp")]
5246 pub mcp_message: &'static str,
5247 pub elicitation_create: &'static str,
5249 pub elicitation_complete: &'static str,
5251 #[cfg(feature = "unstable_auth_status")]
5253 pub auth_status_update: &'static str,
5254}
5255
5256pub const CLIENT_METHOD_NAMES: ClientMethodNames = ClientMethodNames {
5258 session_update: SESSION_UPDATE_NOTIFICATION,
5259 session_request_permission: SESSION_REQUEST_PERMISSION_METHOD_NAME,
5260 #[cfg(feature = "unstable_mcp_over_acp")]
5261 mcp_message: MCP_MESSAGE_METHOD_NAME,
5262 elicitation_create: ELICITATION_CREATE_METHOD_NAME,
5263 elicitation_complete: ELICITATION_COMPLETE_NOTIFICATION,
5264 #[cfg(feature = "unstable_auth_status")]
5265 auth_status_update: AUTH_STATUS_UPDATE_NOTIFICATION,
5266};
5267
5268pub(crate) const SESSION_UPDATE_NOTIFICATION: &str = "session/update";
5270pub(crate) const SESSION_REQUEST_PERMISSION_METHOD_NAME: &str = "session/request_permission";
5272pub(crate) const ELICITATION_CREATE_METHOD_NAME: &str = "elicitation/create";
5274pub(crate) const ELICITATION_COMPLETE_NOTIFICATION: &str = "elicitation/complete";
5276#[cfg(feature = "unstable_auth_status")]
5278pub(crate) const AUTH_STATUS_UPDATE_NOTIFICATION: &str = "auth/status_update";
5279
5280#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5287#[derive(Clone, Debug, Serialize, Deserialize)]
5288#[serde(untagged)]
5289#[cfg_attr(feature = "schemars", schemars(inline))]
5290#[non_exhaustive]
5291pub enum AgentRequest {
5292 RequestPermissionRequest(Box<RequestPermissionRequest>),
5310 CreateElicitationRequest(Box<CreateElicitationRequest>),
5314 #[cfg(feature = "unstable_mcp_over_acp")]
5320 MessageMcpRequest(Box<MessageMcpRequest>),
5321 ExtMethodRequest(Box<ExtRequest>),
5328}
5329
5330impl_request_dispatch! {
5331 AgentRequest => ClientResponse {
5332 RequestPermissionRequest => RequestPermissionResponse: CLIENT_METHOD_NAMES.session_request_permission,
5333 CreateElicitationRequest => CreateElicitationResponse: CLIENT_METHOD_NAMES.elicitation_create,
5334 #[cfg(feature = "unstable_mcp_over_acp")]
5335 MessageMcpRequest => MessageMcpResponse: CLIENT_METHOD_NAMES.mcp_message,
5336 }
5337 extension ExtMethodRequest(Box<ExtRequest>) => ExtMethodResponse;
5338}
5339
5340#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5347#[derive(Clone, Debug, Serialize, Deserialize)]
5348#[serde(untagged)]
5349#[cfg_attr(feature = "schemars", schemars(inline))]
5350#[non_exhaustive]
5351pub enum ClientResponse {
5352 RequestPermissionResponse(Box<RequestPermissionResponse>),
5354 CreateElicitationResponse(Box<CreateElicitationResponse>),
5356 #[cfg(feature = "unstable_mcp_over_acp")]
5358 MessageMcpResponse(Box<MessageMcpResponse>),
5359 ExtMethodResponse(Box<ExtResponse>),
5361}
5362
5363#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5370#[derive(Clone, Debug, Serialize, Deserialize)]
5371#[serde(untagged)]
5372#[cfg_attr(feature = "schemars", schemars(inline))]
5373#[non_exhaustive]
5374pub enum AgentNotification {
5375 UpdateSessionNotification(Box<UpdateSessionNotification>),
5387 CompleteElicitationNotification(Box<CompleteElicitationNotification>),
5391 #[cfg(feature = "unstable_auth_status")]
5399 AuthStatusUpdateNotification(Box<AuthStatusUpdateNotification>),
5400 ExtNotification(Box<ExtNotification>),
5407}
5408
5409impl_message_dispatch! {
5410 AgentNotification {
5411 UpdateSessionNotification => CLIENT_METHOD_NAMES.session_update,
5412 CompleteElicitationNotification => CLIENT_METHOD_NAMES.elicitation_complete,
5413 #[cfg(feature = "unstable_auth_status")]
5414 AuthStatusUpdateNotification => CLIENT_METHOD_NAMES.auth_status_update,
5415 }
5416 extension ExtNotification(Box<ExtNotification>);
5417}
5418
5419#[cfg(test)]
5420mod tests {
5421
5422 #[test]
5423 fn background_list_round_trips_on_state_updates() {
5424 use serde_json::json;
5425 let idle = super::StateUpdate::Idle(super::IdleStateUpdate::new().background(vec![
5426 super::BackgroundWork::Terminal(super::BackgroundTerminal::new("term_003")),
5427 super::BackgroundWork::ToolCall(super::BackgroundToolCall::new("call_012")),
5428 ]));
5429 let wire = json!({
5430 "state": "idle",
5431 "background": [
5432 { "type": "terminal", "terminalId": "term_003" },
5433 { "type": "tool_call", "toolCallId": "call_012" }
5434 ]
5435 });
5436 assert_eq!(serde_json::to_value(&idle).unwrap(), wire);
5437 assert_eq!(
5438 serde_json::from_value::<super::StateUpdate>(wire).unwrap(),
5439 idle
5440 );
5441
5442 assert_eq!(idle.background().map(<[_]>::len), Some(2));
5443
5444 let empty = super::RunningStateUpdate::new().background(vec![]);
5445 assert_eq!(
5446 serde_json::to_value(&empty).unwrap(),
5447 json!({ "background": [] })
5448 );
5449 assert_eq!(
5450 super::StateUpdate::Running(empty).background(),
5451 Some(&[][..])
5452 );
5453 assert_eq!(
5454 super::StateUpdate::RequiresAction(super::RequiresActionStateUpdate::new())
5455 .background(),
5456 None
5457 );
5458 let custom: super::StateUpdate = serde_json::from_value(json!({
5459 "state": "_waiting",
5460 "background": [{ "type": "terminal", "terminalId": "term_003" }]
5461 }))
5462 .unwrap();
5463 assert_eq!(custom.background(), None);
5464 }
5465
5466 #[test]
5467 fn background_list_keeps_unknown_items_and_drops_malformed_lists() {
5468 use serde_json::json;
5469 let parsed: super::RunningStateUpdate = serde_json::from_value(json!({
5470 "background": [{ "type": "_cron", "schedule": "* * * * *" }]
5471 }))
5472 .unwrap();
5473 let Some([super::BackgroundWork::Other(other)]) = parsed.background.as_deref() else {
5474 panic!("expected one unknown item: {parsed:?}");
5475 };
5476 assert_eq!(other.kind, "_cron");
5477 assert_eq!(other.fields["schedule"], json!("* * * * *"));
5478
5479 for background in [
5480 json!(null),
5481 json!("oops"),
5482 json!([{ "type": "terminal" }]),
5483 json!([{ "type": "tool_call", "toolCallId": "call_1" }, { "type": "terminal", "terminalId": 7 }]),
5484 ] {
5485 let parsed: super::IdleStateUpdate =
5486 serde_json::from_value(json!({ "background": background })).unwrap();
5487 assert_eq!(parsed.background, None, "{background}");
5488 }
5489 }
5490
5491 #[test]
5492 fn replacement_lists_reject_non_arrays_instead_of_clearing() {
5493 use serde_json::json;
5494 for (update, key) in [
5495 ("config_option_update", "configOptions"),
5496 ("available_commands_update", "availableCommands"),
5497 ] {
5498 let empty = json!({ "sessionUpdate": update, key: [] });
5499 serde_json::from_value::<super::SessionUpdate>(empty).unwrap();
5500 for bad in [json!("oops"), json!(null), json!({})] {
5501 let wire = json!({ "sessionUpdate": update, key: bad });
5502 assert!(
5503 serde_json::from_value::<super::SessionUpdate>(wire).is_err(),
5504 "{update} {bad}"
5505 );
5506 }
5507 }
5508 let plan = |entries: serde_json::Value| {
5509 json!({ "sessionUpdate": "plan_update",
5510 "plan": { "type": "items", "planId": "p", "entries": entries } })
5511 };
5512 serde_json::from_value::<super::SessionUpdate>(plan(json!([]))).unwrap();
5513 assert!(serde_json::from_value::<super::SessionUpdate>(plan(json!("oops"))).is_err());
5514 let skipped =
5516 plan(json!([42, { "content": "a", "priority": "high", "status": "pending" }]));
5517 let super::SessionUpdate::PlanUpdate(update) =
5518 serde_json::from_value::<super::SessionUpdate>(skipped).unwrap()
5519 else {
5520 panic!("expected plan_update");
5521 };
5522 let crate::v2::PlanUpdateContent::Items(items) = update.plan else {
5523 panic!("expected items");
5524 };
5525 assert_eq!(items.entries.len(), 1);
5526 }
5527
5528 #[test]
5529 fn other_available_command_preserves_meta_verbatim() {
5530 for meta in [serde_json::json!({ "k": 1 }), serde_json::json!("bad")] {
5531 let wire = serde_json::json!({ "type": "_custom", "name": "c",
5532 "description": "d", "_meta": meta, "extra": true });
5533 let command: super::AvailableCommand = serde_json::from_value(wire.clone()).unwrap();
5534 assert_eq!(command.meta(), meta.as_object());
5535 assert_eq!(serde_json::to_value(&command).unwrap(), wire);
5536 }
5537 }
5538
5539 #[test]
5540 fn cancelled_permission_outcome_wire_format() {
5541 let outcome: RequestPermissionOutcome =
5542 serde_json::from_value(serde_json::json!({ "outcome": "cancelled" })).unwrap();
5543 assert_eq!(outcome, CancelledPermissionOutcome::new().into());
5544 assert_eq!(
5545 serde_json::to_value(&outcome).unwrap(),
5546 serde_json::json!({ "outcome": "cancelled" })
5547 );
5548
5549 let with_meta: RequestPermissionOutcome = CancelledPermissionOutcome::new()
5550 .meta(serde_json::Map::from_iter([(
5551 "k".to_string(),
5552 serde_json::json!(1),
5553 )]))
5554 .into();
5555 let json = serde_json::to_value(&with_meta).unwrap();
5556 assert_eq!(
5557 json,
5558 serde_json::json!({ "outcome": "cancelled", "_meta": { "k": 1 } })
5559 );
5560 assert_eq!(
5561 serde_json::from_value::<RequestPermissionOutcome>(json).unwrap(),
5562 with_meta
5563 );
5564 }
5565
5566 use super::*;
5567
5568 #[test]
5569 fn subagent_update_serializes_as_upsert() {
5570 use serde_json::json;
5571
5572 let announced =
5573 SessionUpdate::SubagentUpdate(SubagentUpdate::new("sess_child_1").capabilities(
5574 SubagentSessionCapabilities::new().cancel(SessionCancelCapabilities::new()),
5575 ));
5576 let wire = json!({
5577 "sessionUpdate": "subagent_update",
5578 "sessionId": "sess_child_1",
5579 "capabilities": { "cancel": {} }
5580 });
5581 assert_eq!(serde_json::to_value(&announced).unwrap(), wire);
5582 assert_eq!(
5583 serde_json::from_value::<SessionUpdate>(wire).unwrap(),
5584 announced
5585 );
5586
5587 let minimal = SubagentUpdate::new("sess_child_1");
5588 assert_eq!(
5589 serde_json::to_value(&minimal).unwrap(),
5590 json!({
5591 "sessionId": "sess_child_1"
5592 })
5593 );
5594 assert!(minimal.capabilities.is_undefined());
5595 assert!(minimal.state.is_undefined());
5596 assert!(minimal.meta.is_undefined());
5597
5598 let cleared_wire = json!({
5600 "sessionId": "sess_child_1",
5601 "capabilities": null,
5602 "state": null,
5603 "_meta": null
5604 });
5605 let cleared: SubagentUpdate = serde_json::from_value(cleared_wire.clone()).unwrap();
5606 assert!(cleared.capabilities.is_null());
5607 assert!(cleared.state.is_null());
5608 assert!(cleared.meta.is_null());
5609 assert_eq!(serde_json::to_value(cleared).unwrap(), cleared_wire);
5610
5611 let revoked: SubagentUpdate = serde_json::from_value(json!({
5612 "sessionId": "sess_child_1",
5613 "capabilities": {}
5614 }))
5615 .unwrap();
5616 assert_eq!(
5617 revoked.capabilities,
5618 MaybeUndefined::Value(SubagentSessionCapabilities::new())
5619 );
5620 assert!(
5621 matches!(revoked.capabilities, MaybeUndefined::Value(ref child) if child.cancel.is_none())
5622 );
5623
5624 assert!(
5625 serde_json::from_value::<SessionUpdate>(json!({
5626 "sessionUpdate": "subagent_update"
5627 }))
5628 .is_err()
5629 );
5630 }
5631
5632 #[test]
5633 fn subagent_cancel_capability_is_optional_object() {
5634 use serde_json::json;
5635
5636 for wire in [
5637 json!({}),
5638 json!({"cancel": null}),
5639 json!({"cancel": true}),
5640 json!({"cancel": false}),
5641 ] {
5642 let child: SubagentSessionCapabilities = serde_json::from_value(wire).unwrap();
5643 assert!(child.cancel.is_none());
5644 assert_eq!(serde_json::to_value(child).unwrap(), json!({}));
5645 }
5646 let enabled = SubagentSessionCapabilities::new().cancel(SessionCancelCapabilities::new());
5647 assert_eq!(
5648 serde_json::to_value(&enabled).unwrap(),
5649 json!({"cancel": {}})
5650 );
5651 assert_eq!(
5652 serde_json::from_value::<SubagentSessionCapabilities>(json!({"cancel": {}})).unwrap(),
5653 enabled
5654 );
5655 let meta: Meta = [("source".into(), json!("worker"))].into_iter().collect();
5656 let with_meta =
5657 SubagentSessionCapabilities::new().cancel(SessionCancelCapabilities::new().meta(meta));
5658 let wire = json!({"cancel": {"_meta": {"source": "worker"}}});
5659 assert_eq!(serde_json::to_value(&with_meta).unwrap(), wire);
5660 assert_eq!(
5661 serde_json::from_value::<SubagentSessionCapabilities>(wire).unwrap(),
5662 with_meta
5663 );
5664 assert!(enabled.cancel.is_some());
5665 assert!(enabled.cancel(None).cancel.is_none());
5666 let removed = SubagentUpdate::new("child").capabilities(SubagentSessionCapabilities::new());
5667 assert_eq!(
5668 serde_json::to_value(removed).unwrap(),
5669 json!({"sessionId": "child", "capabilities": {}})
5670 );
5671 }
5672
5673 #[test]
5674 fn subagent_display_metadata_uses_patch_semantics() {
5675 use serde_json::json;
5676
5677 let update = SubagentUpdate::new("child")
5678 .title("Test investigator".to_string())
5679 .description("Investigates platform-specific test failures.".to_string());
5680 let wire = json!({
5681 "sessionId": "child",
5682 "title": "Test investigator",
5683 "description": "Investigates platform-specific test failures."
5684 });
5685 assert_eq!(serde_json::to_value(&update).unwrap(), wire);
5686 assert_eq!(
5687 serde_json::from_value::<SubagentUpdate>(wire).unwrap(),
5688 update
5689 );
5690
5691 let minimal = SubagentUpdate::new("child");
5692 assert!(minimal.title.is_undefined());
5693 assert!(minimal.description.is_undefined());
5694 assert_eq!(
5695 serde_json::to_value(&minimal).unwrap(),
5696 json!({"sessionId": "child"})
5697 );
5698 let cleared_wire = json!({
5699 "sessionId": "child", "title": null, "description": null
5700 });
5701 let cleared: SubagentUpdate = serde_json::from_value(cleared_wire.clone()).unwrap();
5702 assert!(cleared.title.is_null());
5703 assert!(cleared.description.is_null());
5704 assert_eq!(serde_json::to_value(cleared).unwrap(), cleared_wire);
5705
5706 let title_only: SubagentUpdate = serde_json::from_value(json!({
5707 "sessionId": "child", "title": "Updated title"
5708 }))
5709 .unwrap();
5710 assert_eq!(
5711 title_only.title,
5712 MaybeUndefined::Value("Updated title".to_string())
5713 );
5714 assert!(title_only.description.is_undefined());
5715 let malformed: SubagentUpdate = serde_json::from_value(json!({
5716 "sessionId": "child", "title": false, "description": false
5717 }))
5718 .unwrap();
5719 assert_eq!(malformed, minimal);
5720 }
5721
5722 #[test]
5723 fn subagent_directories_use_strict_patch_semantics() {
5724 use serde_json::json;
5725
5726 let update = SubagentUpdate::new("child")
5727 .cwd("/home/user/project/.worktrees/investigator")
5728 .additional_directories(vec![]);
5729 let wire = json!({
5730 "sessionId": "child",
5731 "cwd": "/home/user/project/.worktrees/investigator",
5732 "additionalDirectories": []
5733 });
5734 assert_eq!(serde_json::to_value(&update).unwrap(), wire);
5735 assert_eq!(
5736 serde_json::from_value::<SubagentUpdate>(wire).unwrap(),
5737 update
5738 );
5739
5740 let inherited: SubagentUpdate =
5741 serde_json::from_value(json!({"sessionId": "child"})).unwrap();
5742 assert!(inherited.cwd.is_undefined());
5743 assert!(inherited.additional_directories.is_undefined());
5744
5745 let cleared_wire = json!({
5746 "sessionId": "child", "cwd": null, "additionalDirectories": null
5747 });
5748 let cleared: SubagentUpdate = serde_json::from_value(cleared_wire.clone()).unwrap();
5749 assert!(cleared.cwd.is_null());
5750 assert!(cleared.additional_directories.is_null());
5751 assert_eq!(serde_json::to_value(cleared).unwrap(), cleared_wire);
5752
5753 for malformed in [
5754 json!({"sessionId": "child", "cwd": false}),
5755 json!({"sessionId": "child", "additionalDirectories": "/tmp/wt"}),
5756 json!({"sessionId": "child", "additionalDirectories": ["/tmp/wt", false]}),
5757 ] {
5758 assert!(
5759 serde_json::from_value::<SubagentUpdate>(malformed.clone()).is_err(),
5760 "{malformed}"
5761 );
5762 }
5763 }
5764
5765 #[test]
5766 fn subagent_notification_keeps_parent_and_child_ids_nested() {
5767 use serde_json::json;
5768
5769 let notification = UpdateSessionNotification::new(
5770 "parent",
5771 SessionUpdate::SubagentUpdate(SubagentUpdate::new("child")),
5772 );
5773 let wire = json!({
5774 "sessionId": "parent",
5775 "update": {
5776 "sessionUpdate": "subagent_update",
5777 "sessionId": "child"
5778 }
5779 });
5780 assert_eq!(serde_json::to_value(¬ification).unwrap(), wire);
5781 assert_eq!(
5782 serde_json::from_value::<UpdateSessionNotification>(wire).unwrap(),
5783 notification
5784 );
5785 for malformed in [
5786 json!({"sessionId": "parent", "update": {"sessionUpdate": "subagent_update"}}),
5787 json!({"update": {"sessionUpdate": "subagent_update", "sessionId": "child"}}),
5788 ] {
5789 assert!(serde_json::from_value::<UpdateSessionNotification>(malformed).is_err());
5790 }
5791 }
5792
5793 #[test]
5794 fn subagent_mirrors_normal_child_state_notifications() {
5795 use serde_json::json;
5796
5797 let association = SubagentUpdate::new("sess_child");
5798 for state in [
5799 StateUpdate::Running(RunningStateUpdate::new()),
5800 StateUpdate::RequiresAction(RequiresActionStateUpdate::new()),
5801 StateUpdate::Unknown(UnknownStateUpdate::new()),
5802 StateUpdate::Running(RunningStateUpdate::new()),
5803 StateUpdate::Idle(IdleStateUpdate::new().stop_reason(StopReason::EndTurn)),
5804 StateUpdate::Running(RunningStateUpdate::new()),
5805 StateUpdate::Idle(IdleStateUpdate::new().stop_reason(StopReason::Cancelled)),
5806 ] {
5807 let child_notification = UpdateSessionNotification::new(
5808 association.session_id.clone(),
5809 SessionUpdate::StateUpdate(state.clone()),
5810 );
5811 let parent_notification = UpdateSessionNotification::new(
5812 "sess_parent",
5813 SessionUpdate::SubagentUpdate(association.clone().state(state)),
5814 );
5815 let child_wire = serde_json::to_value(&child_notification).unwrap();
5816 let parent_wire = serde_json::to_value(&parent_notification).unwrap();
5817 assert_eq!(child_wire["sessionId"], json!("sess_child"));
5818 assert_eq!(child_wire["update"]["sessionUpdate"], json!("state_update"));
5819 assert_eq!(parent_wire["sessionId"], json!("sess_parent"));
5820 assert_eq!(parent_wire["update"]["sessionId"], json!("sess_child"));
5821 let mut child_snapshot = child_wire["update"].clone();
5822 child_snapshot
5823 .as_object_mut()
5824 .unwrap()
5825 .remove("sessionUpdate");
5826 assert_eq!(parent_wire["update"]["state"], child_snapshot);
5827 assert_eq!(
5828 serde_json::from_value::<UpdateSessionNotification>(child_wire).unwrap(),
5829 child_notification
5830 );
5831 assert_eq!(
5832 serde_json::from_value::<UpdateSessionNotification>(parent_wire).unwrap(),
5833 parent_notification
5834 );
5835 }
5836 }
5837
5838 #[test]
5839 fn subagent_state_uses_whole_snapshot_patch_semantics() {
5840 use serde_json::json;
5841
5842 let minimal = SubagentUpdate::new("child");
5843 assert!(minimal.state.is_undefined());
5844 assert_eq!(
5845 serde_json::to_value(&minimal).unwrap(),
5846 json!({"sessionId": "child"})
5847 );
5848
5849 let cleared = minimal.clone().state(None::<StateUpdate>);
5850 assert!(cleared.state.is_null());
5851 assert_eq!(
5852 serde_json::to_value(&cleared).unwrap(),
5853 json!({"sessionId": "child", "state": null})
5854 );
5855 assert_eq!(
5856 serde_json::from_value::<SubagentUpdate>(json!({"sessionId": "child", "state": null}))
5857 .unwrap(),
5858 cleared
5859 );
5860
5861 for snapshot in [
5862 json!({"state": "running", "_meta": {"source": "worker"}}),
5863 json!({"state": "idle", "stopReason": "end_turn"}),
5864 json!({"state": "requires_action"}),
5865 json!({"state": "unknown"}),
5866 json!({"state": "_custom", "detail": {"phase": 2}}),
5867 ] {
5868 let state: StateUpdate = serde_json::from_value(snapshot.clone()).unwrap();
5869 let update = minimal.clone().state(state.clone());
5870 let wire = json!({"sessionId": "child", "state": snapshot});
5871 assert_eq!(serde_json::to_value(&update).unwrap(), wire);
5872 assert_eq!(
5873 serde_json::from_value::<SubagentUpdate>(wire).unwrap(),
5874 update
5875 );
5876 assert_eq!(update.state, MaybeUndefined::Value(state));
5877 }
5878
5879 let idle = SubagentUpdate::new("child").state(StateUpdate::Idle(
5882 IdleStateUpdate::new().stop_reason(StopReason::Cancelled),
5883 ));
5884 let running = idle.state(StateUpdate::Running(RunningStateUpdate::new()));
5885 assert_eq!(
5886 serde_json::to_value(running).unwrap(),
5887 json!({"sessionId": "child", "state": {"state": "running"}})
5888 );
5889 for invalid in [json!(false), json!(42), json!({}), json!({"state": 7})] {
5890 let parsed: SubagentUpdate =
5891 serde_json::from_value(json!({"sessionId": "child", "state": invalid})).unwrap();
5892 assert_eq!(parsed, minimal);
5893 }
5894 }
5895
5896 #[test]
5897 fn unknown_activity_is_a_known_state_update() {
5898 use serde_json::json;
5899
5900 let update = SessionUpdate::StateUpdate(StateUpdate::Unknown(
5901 UnknownStateUpdate::new().meta(
5902 [("source".into(), json!("worker"))]
5903 .into_iter()
5904 .collect::<Meta>(),
5905 ),
5906 ));
5907 let wire = json!({
5908 "sessionUpdate": "state_update",
5909 "state": "unknown",
5910 "_meta": { "source": "worker" }
5911 });
5912 assert_eq!(serde_json::to_value(&update).unwrap(), wire);
5913 assert_eq!(
5914 serde_json::from_value::<SessionUpdate>(wire).unwrap(),
5915 update
5916 );
5917
5918 for meta in [json!(null), json!(false)] {
5919 let state: StateUpdate = serde_json::from_value(json!({
5920 "state": "unknown",
5921 "_meta": meta
5922 }))
5923 .unwrap();
5924 assert_eq!(state, StateUpdate::Unknown(UnknownStateUpdate::new()));
5925 assert_eq!(
5926 serde_json::to_value(state).unwrap(),
5927 json!({"state": "unknown"})
5928 );
5929 }
5930 assert!(serde_json::from_value::<OtherStateUpdate>(json!({"state": "unknown"})).is_err());
5931 }
5932
5933 #[cfg(feature = "schemars")]
5934 #[test]
5935 fn subagent_schema_carries_optional_nullable_state_snapshot() {
5936 use serde_json::json;
5937
5938 let schema = serde_json::to_value(schemars::schema_for!(SubagentUpdate)).unwrap();
5939 let properties = schema["properties"].as_object().unwrap();
5940 assert!(properties.contains_key("sessionId"));
5941 assert!(properties.contains_key("title"));
5942 assert!(properties.contains_key("description"));
5943 assert!(properties.contains_key("capabilities"));
5944 assert!(properties.contains_key("state"));
5945 assert!(properties.contains_key("_meta"));
5946 assert!(!properties.contains_key("name"));
5947 assert!(!properties.contains_key("task"));
5948 assert_eq!(schema["required"], json!(["sessionId"]));
5949 assert_eq!(
5950 properties["state"]["x-deserialize-default-on-error"],
5951 json!(true)
5952 );
5953 let state_variants = properties["state"]["anyOf"].as_array().unwrap();
5954 assert!(state_variants.contains(&json!({"type": "null"})));
5955 assert!(
5956 state_variants
5957 .iter()
5958 .any(|variant| variant["$ref"] == "#/$defs/StateUpdate")
5959 );
5960 let child =
5961 serde_json::to_value(schemars::schema_for!(SubagentSessionCapabilities)).unwrap();
5962 let variants = child["properties"]["cancel"]["anyOf"]
5963 .as_array()
5964 .expect("cancel must allow the capability object or null");
5965 assert!(variants.contains(&json!({"type": "null"})));
5966 assert!(
5967 variants
5968 .iter()
5969 .any(|variant| variant["type"] == "object" || variant.get("$ref").is_some())
5970 );
5971 assert!(!variants.iter().any(|variant| variant["type"] == "boolean"));
5972 let cancel =
5973 serde_json::to_value(schemars::schema_for!(SessionCancelCapabilities)).unwrap();
5974 assert_eq!(cancel["type"], "object");
5975 assert!(
5976 !child["required"]
5977 .as_array()
5978 .is_some_and(|required| required.contains(&json!("cancel")))
5979 );
5980 }
5981
5982 #[test]
5983 fn notice_preserves_wire_shape_nullable_fields_and_open_severity() {
5984 use serde_json::json;
5985
5986 let mut meta = Meta::new();
5987 meta.insert("source".into(), json!("fallback"));
5988 let v2_notice = SessionUpdate::Notice(
5989 Notice::new(NoticeSeverity::Error, "Provider degraded")
5990 .description("Requests may take longer than usual.")
5991 .meta(meta.clone()),
5992 );
5993 let expected = json!({
5994 "sessionUpdate": "notice",
5995 "severity": "error",
5996 "title": "Provider degraded",
5997 "description": "Requests may take longer than usual.",
5998 "_meta": { "source": "fallback" }
5999 });
6000 assert_eq!(serde_json::to_value(&v2_notice).unwrap(), expected);
6001
6002 let v1_notice = crate::v1::SessionUpdate::Notice(
6003 crate::v1::Notice::new(crate::v1::NoticeSeverity::Error, "Provider degraded")
6004 .description("Requests may take longer than usual.")
6005 .meta(meta),
6006 );
6007 assert_eq!(
6008 serde_json::to_value(v2_notice).unwrap(),
6009 serde_json::to_value(v1_notice).unwrap()
6010 );
6011
6012 let SessionUpdate::Notice(notice) = serde_json::from_value(json!({
6013 "sessionUpdate": "notice",
6014 "severity": "critical",
6015 "title": "Provider degraded",
6016 "description": null,
6017 "_meta": null
6018 }))
6019 .unwrap() else {
6020 panic!("expected notice");
6021 };
6022
6023 assert_eq!(
6024 notice.severity,
6025 NoticeSeverity::Other("critical".to_string())
6026 );
6027 assert_eq!(notice.description, None);
6028 assert_eq!(notice.meta, None);
6029 assert_eq!(
6030 serde_json::to_value(SessionUpdate::Notice(notice)).unwrap(),
6031 json!({
6032 "sessionUpdate": "notice",
6033 "severity": "critical",
6034 "title": "Provider degraded"
6035 })
6036 );
6037 }
6038
6039 #[test]
6040 fn malformed_known_notice_is_not_hidden_as_unknown() {
6041 use serde_json::json;
6042
6043 for malformed in [
6044 json!({
6045 "sessionUpdate": "notice",
6046 "severity": "warning",
6047 "title": 42
6048 }),
6049 json!({
6050 "sessionUpdate": "notice",
6051 "severity": 42,
6052 "title": "MCP server unavailable"
6053 }),
6054 json!({
6055 "sessionUpdate": "notice",
6056 "severity": "warning"
6057 }),
6058 json!({
6059 "sessionUpdate": "notice",
6060 "severity": "warning",
6061 "title": null
6062 }),
6063 json!({
6064 "sessionUpdate": "notice",
6065 "title": "MCP server unavailable"
6066 }),
6067 json!({
6068 "sessionUpdate": "notice",
6069 "severity": null,
6070 "title": "MCP server unavailable"
6071 }),
6072 ] {
6073 assert!(serde_json::from_str::<SessionUpdate>(&malformed.to_string()).is_err());
6074 assert!(serde_json::from_value::<SessionUpdate>(malformed).is_err());
6075 }
6076 }
6077
6078 #[test]
6079 fn notice_tolerates_invalid_optional_display_fields_and_custom_severity() {
6080 use serde_json::json;
6081
6082 let wire = json!({
6083 "sessionUpdate": "notice",
6084 "severity": "_custom",
6085 "title": "Provider degraded",
6086 "description": 42,
6087 "_meta": false
6088 });
6089 let SessionUpdate::Notice(notice) = serde_json::from_value(wire.clone()).unwrap() else {
6090 panic!("expected notice");
6091 };
6092 assert_eq!(
6093 serde_json::from_str::<SessionUpdate>(&wire.to_string()).unwrap(),
6094 SessionUpdate::Notice(notice.clone())
6095 );
6096 assert_eq!(notice.severity, NoticeSeverity::Other("_custom".into()));
6097 assert_eq!(notice.description, None);
6098 assert_eq!(notice.meta, None);
6099 assert_eq!(
6100 serde_json::to_value(notice).unwrap(),
6101 json!({"severity": "_custom", "title": "Provider degraded"})
6102 );
6103 }
6104
6105 #[cfg(feature = "schemars")]
6106 #[test]
6107 fn notice_schema_preserves_required_fields_and_excludes_unknown_fallback() {
6108 use serde_json::json;
6109
6110 let schema = serde_json::to_value(schemars::schema_for!(Notice)).unwrap();
6111 assert_eq!(schema["required"], json!(["severity", "title"]));
6112 assert_eq!(schema["properties"]["title"]["minLength"], 1);
6113 for field in ["description", "_meta"] {
6114 assert!(
6115 schema["properties"][field]["type"]
6116 .as_array()
6117 .unwrap()
6118 .contains(&json!("null"))
6119 );
6120 }
6121 let fallback = serde_json::to_value(schemars::schema_for!(OtherSessionUpdate)).unwrap();
6122 assert!(
6123 fallback["not"]["anyOf"]
6124 .as_array()
6125 .unwrap()
6126 .iter()
6127 .any(|variant| variant["properties"]["sessionUpdate"]["const"] == "notice")
6128 );
6129 }
6130
6131 #[test]
6132 fn replay_complete_round_trips_with_and_without_meta() {
6133 use serde_json::json;
6134
6135 let bare = json!({ "sessionUpdate": "replay_complete" });
6136 assert_eq!(
6137 serde_json::to_value(SessionUpdate::ReplayComplete(ReplayComplete::new())).unwrap(),
6138 bare
6139 );
6140 assert_eq!(
6141 serde_json::from_value::<SessionUpdate>(bare).unwrap(),
6142 SessionUpdate::ReplayComplete(ReplayComplete::new())
6143 );
6144
6145 let mut meta = Meta::new();
6146 meta.insert("source".into(), json!("transcript"));
6147 let with_meta = json!({
6148 "sessionUpdate": "replay_complete",
6149 "_meta": { "source": "transcript" }
6150 });
6151 let update = SessionUpdate::ReplayComplete(ReplayComplete::new().meta(meta));
6152 assert_eq!(serde_json::to_value(&update).unwrap(), with_meta);
6153 assert_eq!(
6154 serde_json::from_value::<SessionUpdate>(with_meta).unwrap(),
6155 update
6156 );
6157 }
6158
6159 #[test]
6160 fn replay_complete_is_never_preserved_as_an_unknown_update() {
6161 use serde_json::json;
6162
6163 for wire in [
6167 json!({ "sessionUpdate": "replay_complete", "_meta": null }),
6168 json!({ "sessionUpdate": "replay_complete", "_meta": false }),
6169 json!({ "sessionUpdate": "replay_complete", "futureField": 1 }),
6170 ] {
6171 assert_eq!(
6172 serde_json::from_str::<SessionUpdate>(&wire.to_string()).unwrap(),
6173 SessionUpdate::ReplayComplete(ReplayComplete::new())
6174 );
6175 assert_eq!(
6176 serde_json::from_value::<SessionUpdate>(wire).unwrap(),
6177 SessionUpdate::ReplayComplete(ReplayComplete::new())
6178 );
6179 }
6180
6181 assert!(
6182 serde_json::from_value::<OtherSessionUpdate>(
6183 json!({ "sessionUpdate": "replay_complete" })
6184 )
6185 .is_err()
6186 );
6187 }
6188
6189 #[cfg(feature = "schemars")]
6190 #[test]
6191 fn replay_complete_schema_has_only_optional_meta_and_excludes_unknown_fallback() {
6192 use serde_json::json;
6193
6194 let schema = serde_json::to_value(schemars::schema_for!(ReplayComplete)).unwrap();
6195 assert!(schema.get("required").is_none());
6196 assert_eq!(
6197 schema["properties"]
6198 .as_object()
6199 .unwrap()
6200 .keys()
6201 .collect::<Vec<_>>(),
6202 ["_meta"]
6203 );
6204 assert_eq!(
6205 schema["properties"]["_meta"]["type"],
6206 json!(["object", "null"])
6207 );
6208 let fallback = serde_json::to_value(schemars::schema_for!(OtherSessionUpdate)).unwrap();
6209 assert!(
6210 fallback["not"]["anyOf"]
6211 .as_array()
6212 .unwrap()
6213 .iter()
6214 .any(|variant| variant["properties"]["sessionUpdate"]["const"]
6215 == "replay_complete")
6216 );
6217 }
6218
6219 #[cfg(feature = "unstable_prompt_suggestions")]
6220 #[test]
6221 fn prompt_suggestions_update_round_trips_prompt_content_and_meta() {
6222 use super::{ContentBlock, Meta, PromptSuggestion, PromptSuggestionsUpdate, SessionUpdate};
6223 use crate::v2::{ResourceLink, TextContent};
6224 use serde_json::json;
6225
6226 let mut meta = Meta::new();
6227 meta.insert("rank".into(), json!(1));
6228 let update = SessionUpdate::PromptSuggestionsUpdate(PromptSuggestionsUpdate::new(vec![
6229 PromptSuggestion::new(vec![ContentBlock::Text(TextContent::new(
6230 "Run the test suite and fix what breaks",
6231 ))])
6232 .meta(meta),
6233 PromptSuggestion::new(vec![
6234 ContentBlock::Text(TextContent::new("Add tests for ")),
6235 ContentBlock::ResourceLink(ResourceLink::new(
6236 "parser.rs",
6237 "file:///home/user/project/src/parser.rs",
6238 )),
6239 ]),
6240 ]));
6241 let wire = json!({
6242 "sessionUpdate": "prompt_suggestions_update",
6243 "suggestions": [
6244 {
6245 "prompt": [
6246 { "type": "text", "text": "Run the test suite and fix what breaks" }
6247 ],
6248 "_meta": { "rank": 1 }
6249 },
6250 {
6251 "prompt": [
6252 { "type": "text", "text": "Add tests for " },
6253 {
6254 "type": "resource_link",
6255 "name": "parser.rs",
6256 "uri": "file:///home/user/project/src/parser.rs"
6257 }
6258 ]
6259 }
6260 ]
6261 });
6262 assert_eq!(serde_json::to_value(&update).unwrap(), wire);
6263 assert_eq!(
6264 serde_json::from_value::<SessionUpdate>(wire).unwrap(),
6265 update
6266 );
6267 }
6268
6269 #[cfg(feature = "unstable_prompt_suggestions")]
6270 #[test]
6271 fn prompt_suggestions_update_with_an_empty_list_withdraws_suggestions() {
6272 use super::{PromptSuggestionsUpdate, SessionUpdate};
6273 use serde_json::json;
6274
6275 let update = SessionUpdate::PromptSuggestionsUpdate(PromptSuggestionsUpdate::new(vec![]));
6276 let wire = json!({
6277 "sessionUpdate": "prompt_suggestions_update",
6278 "suggestions": []
6279 });
6280 assert_eq!(serde_json::to_value(&update).unwrap(), wire);
6281 assert_eq!(
6282 serde_json::from_value::<SessionUpdate>(wire).unwrap(),
6283 update
6284 );
6285 }
6286
6287 #[cfg(feature = "unstable_prompt_suggestions")]
6288 #[test]
6289 fn prompt_suggestions_update_is_never_preserved_as_an_unknown_update() {
6290 use super::{OtherSessionUpdate, SessionUpdate};
6291 use serde_json::json;
6292
6293 for wire in [
6296 json!({ "sessionUpdate": "prompt_suggestions_update" }),
6297 json!({ "sessionUpdate": "prompt_suggestions_update", "suggestions": null }),
6298 json!({ "sessionUpdate": "prompt_suggestions_update", "suggestions": "none" }),
6299 json!({ "sessionUpdate": "prompt_suggestions_update", "suggestions": { "prompt": [] } }),
6300 ] {
6301 assert!(serde_json::from_str::<SessionUpdate>(&wire.to_string()).is_err());
6302 assert!(serde_json::from_value::<SessionUpdate>(wire).is_err());
6303 }
6304
6305 assert!(
6306 serde_json::from_value::<OtherSessionUpdate>(json!({
6307 "sessionUpdate": "prompt_suggestions_update",
6308 "suggestions": []
6309 }))
6310 .is_err()
6311 );
6312 }
6313
6314 #[cfg(feature = "unstable_prompt_suggestions")]
6315 #[test]
6316 fn prompt_suggestions_update_skips_whole_suggestions_it_cannot_parse() {
6317 use super::{ContentBlock, PromptSuggestion, PromptSuggestionsUpdate, SessionUpdate};
6318 use crate::v2::TextContent;
6319 use serde_json::json;
6320
6321 let text =
6322 |text: &str| PromptSuggestion::new(vec![ContentBlock::Text(TextContent::new(text))]);
6323
6324 let update: SessionUpdate = serde_json::from_value(json!({
6327 "sessionUpdate": "prompt_suggestions_update",
6328 "suggestions": [
6329 { "prompt": [{ "type": "text", "text": "Keep the first" }] },
6330 { "text": "A suggestion without a prompt" },
6331 { "prompt": "Not a list" },
6332 { "prompt": [{ "type": "text", "text": "Open " }, { "type": "text" }] },
6333 "not an object",
6334 { "prompt": [{ "type": "text", "text": "Keep the last" }], "_meta": false }
6335 ]
6336 }))
6337 .unwrap();
6338
6339 assert_eq!(
6340 update,
6341 SessionUpdate::PromptSuggestionsUpdate(PromptSuggestionsUpdate::new(vec![
6342 text("Keep the first"),
6343 text("Keep the last"),
6344 ]))
6345 );
6346 }
6347
6348 #[cfg(feature = "unstable_prompt_suggestions")]
6349 #[test]
6350 fn prompt_suggestions_update_preserves_custom_and_future_content_blocks() {
6351 use super::{ContentBlock, SessionUpdate};
6352 use serde_json::json;
6353
6354 let wire = json!({
6357 "sessionUpdate": "prompt_suggestions_update",
6358 "suggestions": [
6359 { "prompt": [{ "type": "_hologram", "data": "AAAA" }] }
6360 ]
6361 });
6362 let update: SessionUpdate = serde_json::from_value(wire.clone()).unwrap();
6363 let SessionUpdate::PromptSuggestionsUpdate(suggestions) = &update else {
6364 panic!("expected prompt_suggestions_update, got {update:?}");
6365 };
6366 assert!(matches!(
6367 suggestions.suggestions[0].prompt.as_slice(),
6368 [ContentBlock::Other(_)]
6369 ));
6370 assert_eq!(serde_json::to_value(&update).unwrap(), wire);
6371 }
6372
6373 #[cfg(feature = "unstable_prompt_suggestions")]
6374 #[test]
6375 fn prompt_suggestions_capability_advertises_support_and_content_types() {
6376 use super::{
6377 ClientCapabilities, ClientSessionCapabilities, PromptSuggestionsAudioCapabilities,
6378 PromptSuggestionsCapabilities, PromptSuggestionsEmbeddedContextCapabilities,
6379 PromptSuggestionsImageCapabilities,
6380 };
6381 use serde_json::json;
6382
6383 let capabilities = ClientCapabilities::new().session(
6384 ClientSessionCapabilities::new()
6385 .prompt_suggestions(PromptSuggestionsCapabilities::new()),
6386 );
6387 let value = serde_json::to_value(&capabilities).unwrap();
6388 assert_eq!(value, json!({ "session": { "promptSuggestions": {} } }));
6389 assert_eq!(
6390 serde_json::from_value::<ClientCapabilities>(value).unwrap(),
6391 capabilities
6392 );
6393
6394 let content_types = PromptSuggestionsCapabilities::new()
6395 .image(PromptSuggestionsImageCapabilities::new())
6396 .audio(PromptSuggestionsAudioCapabilities::new())
6397 .embedded_context(PromptSuggestionsEmbeddedContextCapabilities::new());
6398 let wire = json!({ "image": {}, "audio": {}, "embeddedContext": {} });
6399 assert_eq!(serde_json::to_value(&content_types).unwrap(), wire);
6400 assert_eq!(
6401 serde_json::from_value::<PromptSuggestionsCapabilities>(wire).unwrap(),
6402 content_types
6403 );
6404
6405 for unsupported in [
6407 json!({}),
6408 json!({ "session": null }),
6409 json!({ "session": {} }),
6410 json!({ "session": { "promptSuggestions": null } }),
6411 json!({ "session": { "promptSuggestions": false } }),
6412 json!({ "session": { "promptSuggestions": true } }),
6413 json!({ "session": { "promptSuggestions": "supported" } }),
6414 ] {
6415 let capabilities: ClientCapabilities = serde_json::from_value(unsupported).unwrap();
6416 assert!(
6417 capabilities
6418 .session
6419 .and_then(|session| session.prompt_suggestions)
6420 .is_none()
6421 );
6422 }
6423
6424 assert_eq!(
6427 serde_json::from_value::<PromptSuggestionsCapabilities>(json!({
6428 "image": true,
6429 "audio": null,
6430 "embeddedContext": {}
6431 }))
6432 .unwrap(),
6433 PromptSuggestionsCapabilities::new()
6434 .embedded_context(PromptSuggestionsEmbeddedContextCapabilities::new())
6435 );
6436 }
6437
6438 #[cfg(all(feature = "schemars", feature = "unstable_prompt_suggestions"))]
6439 #[test]
6440 fn prompt_suggestions_schema_requires_the_list_and_excludes_unknown_fallback() {
6441 use super::{
6442 ClientCapabilities, ClientSessionCapabilities, OtherSessionUpdate, PromptSuggestion,
6443 PromptSuggestionsCapabilities, PromptSuggestionsUpdate,
6444 };
6445 use serde_json::json;
6446
6447 let update = serde_json::to_value(schemars::schema_for!(PromptSuggestionsUpdate)).unwrap();
6448 assert_eq!(update["required"], json!(["suggestions"]));
6449 assert_eq!(update["properties"]["suggestions"]["type"], "array");
6450
6451 let suggestion = serde_json::to_value(schemars::schema_for!(PromptSuggestion)).unwrap();
6452 assert_eq!(suggestion["required"], json!(["prompt"]));
6453 assert_eq!(suggestion["properties"]["prompt"]["type"], "array");
6454 assert_eq!(suggestion["properties"]["prompt"]["minItems"], 1);
6455
6456 let fallback = serde_json::to_value(schemars::schema_for!(OtherSessionUpdate)).unwrap();
6457 assert!(
6458 fallback["not"]["anyOf"]
6459 .as_array()
6460 .unwrap()
6461 .iter()
6462 .any(|variant| variant["properties"]["sessionUpdate"]["const"]
6463 == "prompt_suggestions_update")
6464 );
6465
6466 for (schema, field) in [
6467 (
6468 serde_json::to_value(schemars::schema_for!(ClientCapabilities)).unwrap(),
6469 "session",
6470 ),
6471 (
6472 serde_json::to_value(schemars::schema_for!(ClientSessionCapabilities)).unwrap(),
6473 "promptSuggestions",
6474 ),
6475 ] {
6476 assert!(
6477 schema["properties"][field]["anyOf"]
6478 .as_array()
6479 .unwrap()
6480 .contains(&json!({"type": "null"}))
6481 );
6482 assert!(
6483 !schema["required"]
6484 .as_array()
6485 .is_some_and(|required| required.contains(&json!(field)))
6486 );
6487 }
6488
6489 let content_types =
6490 serde_json::to_value(schemars::schema_for!(PromptSuggestionsCapabilities)).unwrap();
6491 assert!(content_types.get("required").is_none());
6492 for field in ["image", "audio", "embeddedContext"] {
6493 assert!(
6494 content_types["properties"][field]["anyOf"]
6495 .as_array()
6496 .unwrap()
6497 .contains(&json!({"type": "null"}))
6498 );
6499 }
6500 }
6501
6502 #[test]
6503 fn compaction_updates_preserve_patch_and_open_status_semantics() {
6504 use serde_json::json;
6505
6506 assert_eq!(
6507 serde_json::to_value(SessionUpdate::CompactionUpdate(
6508 CompactionUpdate::new("cmp_001")
6509 .status(CompactionStatus::Completed)
6510 .summary(vec![ContentBlock::Text(crate::v2::TextContent::new(
6511 "retained",
6512 ))]),
6513 ))
6514 .unwrap(),
6515 json!({
6516 "sessionUpdate": "compaction_update",
6517 "compactionId": "cmp_001",
6518 "status": "completed",
6519 "summary": [{ "type": "text", "text": "retained" }]
6520 })
6521 );
6522
6523 let SessionUpdate::CompactionUpdate(update) = serde_json::from_value(json!({
6524 "sessionUpdate": "compaction_update",
6525 "compactionId": "cmp_001",
6526 "status": "paused",
6527 "summary": null
6528 }))
6529 .unwrap() else {
6530 panic!("expected compaction update");
6531 };
6532 assert_eq!(
6533 update.status,
6534 MaybeUndefined::Value(CompactionStatus::Other("paused".into()))
6535 );
6536 assert!(update.summary.is_null());
6537 assert!(update.error.is_undefined());
6538
6539 let SessionUpdate::CompactionUpdate(patch) = serde_json::from_value(json!({
6541 "sessionUpdate": "compaction_update",
6542 "compactionId": "cmp_001",
6543 "summary": []
6544 }))
6545 .unwrap() else {
6546 panic!("expected compaction update");
6547 };
6548 assert!(patch.status.is_undefined());
6549 assert_eq!(
6550 serde_json::to_value(CompactionUpdate::new("cmp_001")).unwrap(),
6551 json!({ "compactionId": "cmp_001" })
6552 );
6553 let reset: CompactionUpdate =
6554 serde_json::from_value(json!({ "compactionId": "cmp_001", "status": null })).unwrap();
6555 assert!(reset.status.is_null());
6556 }
6557
6558 #[test]
6559 fn malformed_known_compaction_update_is_not_hidden_as_unknown() {
6560 use serde_json::json;
6561
6562 assert!(
6563 serde_json::from_value::<SessionUpdate>(json!({
6564 "sessionUpdate": "compaction_update",
6565 "status": "completed"
6566 }))
6567 .is_err()
6568 );
6569 assert!(
6570 serde_json::from_value::<SessionUpdate>(json!({
6571 "sessionUpdate": "compaction_summary_chunk",
6572 "compactionId": "cmp_001"
6573 }))
6574 .is_err()
6575 );
6576 }
6577
6578 #[test]
6579 fn test_elicitation_capability_semantics() {
6580 use serde_json::json;
6581
6582 let unsupported: ClientCapabilities = serde_json::from_value(json!({})).unwrap();
6583 assert!(unsupported.elicitation.is_none());
6584
6585 let null: ClientCapabilities =
6586 serde_json::from_value(json!({ "elicitation": null })).unwrap();
6587 assert!(null.elicitation.is_none());
6588
6589 let malformed: ClientCapabilities =
6590 serde_json::from_value(json!({ "elicitation": false })).unwrap();
6591 assert!(malformed.elicitation.is_none());
6592
6593 let empty: ClientCapabilities =
6594 serde_json::from_value(json!({ "elicitation": {} })).unwrap();
6595 let empty = empty.elicitation.expect("present capability");
6596 assert!(!empty.supports_form());
6597 assert!(!empty.supports_url());
6598
6599 let form_only: ClientCapabilities = serde_json::from_value(json!({
6600 "elicitation": { "form": {} }
6601 }))
6602 .unwrap();
6603 let form_only = form_only.elicitation.expect("advertised capability");
6604 assert!(form_only.supports_form());
6605 assert!(!form_only.supports_url());
6606
6607 let url_only: ClientCapabilities = serde_json::from_value(json!({
6608 "elicitation": { "url": {} }
6609 }))
6610 .unwrap();
6611 let url_only = url_only.elicitation.expect("advertised capability");
6612 assert!(!url_only.supports_form());
6613 assert!(url_only.supports_url());
6614
6615 let both: ClientCapabilities = serde_json::from_value(json!({
6616 "elicitation": { "form": {}, "url": {} }
6617 }))
6618 .unwrap();
6619 let both = both.elicitation.expect("advertised capability");
6620 assert!(both.supports_form());
6621 assert!(both.supports_url());
6622 }
6623
6624 #[test]
6625 fn test_elicitation_method_routing_and_envelopes() {
6626 use serde_json::json;
6627
6628 assert_eq!(CLIENT_METHOD_NAMES.elicitation_create, "elicitation/create");
6629 assert_eq!(
6630 CLIENT_METHOD_NAMES.elicitation_complete,
6631 "elicitation/complete"
6632 );
6633
6634 let request =
6635 AgentRequest::CreateElicitationRequest(Box::new(CreateElicitationRequest::new(
6636 crate::v2::ElicitationFormMode::new(
6637 crate::v2::ElicitationSessionScope::new("sess_1"),
6638 crate::v2::ElicitationSchema::new(),
6639 ),
6640 "Choose a value",
6641 )));
6642 assert_eq!(request.method(), "elicitation/create");
6643 let method = Arc::from(request.method());
6644 let request = crate::v2::JsonRpcMessage::wrap(crate::v2::Request {
6645 id: crate::v2::RequestId::Number(7),
6646 method,
6647 params: Some(request),
6648 });
6649 assert_eq!(
6650 serde_json::to_value(request).unwrap(),
6651 json!({
6652 "jsonrpc": "2.0",
6653 "id": 7,
6654 "method": "elicitation/create",
6655 "params": {
6656 "mode": "form",
6657 "sessionId": "sess_1",
6658 "message": "Choose a value",
6659 "requestedSchema": { "type": "object", "properties": {} }
6660 }
6661 })
6662 );
6663
6664 let notification = AgentNotification::CompleteElicitationNotification(Box::new(
6665 CompleteElicitationNotification::new("elic_1"),
6666 ));
6667 assert_eq!(notification.method(), "elicitation/complete");
6668 let method = Arc::from(notification.method());
6669 let notification = crate::v2::JsonRpcMessage::wrap(crate::v2::Notification {
6670 method,
6671 params: Some(notification),
6672 });
6673 assert_eq!(
6674 serde_json::to_value(notification).unwrap(),
6675 json!({
6676 "jsonrpc": "2.0",
6677 "method": "elicitation/complete",
6678 "params": { "elicitationId": "elic_1" }
6679 })
6680 );
6681 }
6682
6683 #[test]
6684 fn test_client_capabilities_auth_defaults_on_malformed_value() {
6685 use serde_json::json;
6686
6687 let capabilities: ClientCapabilities = serde_json::from_value(json!({
6688 "auth": false
6689 }))
6690 .unwrap();
6691
6692 assert_eq!(capabilities.auth, None);
6693 }
6694
6695 #[test]
6696 fn test_serialization_behavior() {
6697 use serde_json::json;
6698
6699 assert_eq!(
6700 serde_json::from_value::<SessionInfoUpdate>(json!({})).unwrap(),
6701 SessionInfoUpdate {
6702 title: MaybeUndefined::Undefined,
6703 updated_at: MaybeUndefined::Undefined,
6704 meta: MaybeUndefined::Undefined
6705 }
6706 );
6707 assert_eq!(
6708 serde_json::from_value::<SessionInfoUpdate>(json!({"title": null, "updatedAt": null}))
6709 .unwrap(),
6710 SessionInfoUpdate {
6711 title: MaybeUndefined::Null,
6712 updated_at: MaybeUndefined::Null,
6713 meta: MaybeUndefined::Undefined
6714 }
6715 );
6716 assert_eq!(
6717 serde_json::from_value::<SessionInfoUpdate>(
6718 json!({"title": "title", "updatedAt": "timestamp"})
6719 )
6720 .unwrap(),
6721 SessionInfoUpdate {
6722 title: MaybeUndefined::Value("title".to_string()),
6723 updated_at: MaybeUndefined::Value("timestamp".to_string()),
6724 meta: MaybeUndefined::Undefined
6725 }
6726 );
6727
6728 let clear_meta =
6729 serde_json::from_value::<SessionInfoUpdate>(json!({"_meta": null})).unwrap();
6730 assert_eq!(clear_meta.meta, MaybeUndefined::Null);
6731
6732 let mut meta = Meta::new();
6733 meta.insert("source".to_string(), json!("session-info"));
6734
6735 assert_eq!(
6736 serde_json::from_value::<SessionInfoUpdate>(json!({"_meta": {
6737 "source": "session-info"
6738 }}))
6739 .unwrap()
6740 .meta,
6741 MaybeUndefined::Value(meta.clone())
6742 );
6743
6744 assert_eq!(
6745 serde_json::to_value(SessionInfoUpdate::new()).unwrap(),
6746 json!({})
6747 );
6748
6749 assert_eq!(
6750 serde_json::to_value(SessionInfoUpdate::new().meta(None::<Meta>)).unwrap(),
6751 json!({"_meta": null})
6752 );
6753
6754 assert_eq!(
6755 serde_json::to_value(SessionInfoUpdate::new().meta(meta)).unwrap(),
6756 json!({"_meta": {
6757 "source": "session-info"
6758 }})
6759 );
6760 assert_eq!(
6761 serde_json::to_value(SessionInfoUpdate::new().title("title")).unwrap(),
6762 json!({"title": "title"})
6763 );
6764 assert_eq!(
6765 serde_json::to_value(SessionInfoUpdate::new().title(None)).unwrap(),
6766 json!({"title": null})
6767 );
6768 assert_eq!(
6769 serde_json::to_value(
6770 SessionInfoUpdate::new()
6771 .title("title")
6772 .title(MaybeUndefined::Undefined)
6773 )
6774 .unwrap(),
6775 json!({})
6776 );
6777 }
6778
6779 #[test]
6780 fn test_content_chunk_message_id_serialization() {
6781 use serde_json::json;
6782
6783 assert_eq!(
6784 serde_json::to_value(SessionUpdate::AgentMessageChunk(ContentChunk::new(
6785 ContentBlock::Text(crate::v2::TextContent::new("Hello")),
6786 "msg_agent_c42b9",
6787 )))
6788 .unwrap(),
6789 json!({
6790 "sessionUpdate": "agent_message_chunk",
6791 "messageId": "msg_agent_c42b9",
6792 "content": {
6793 "type": "text",
6794 "text": "Hello"
6795 }
6796 })
6797 );
6798
6799 let err = serde_json::from_value::<ContentChunk>(json!({
6800 "content": {
6801 "type": "text",
6802 "text": "Hello"
6803 }
6804 }))
6805 .unwrap_err();
6806
6807 assert!(err.to_string().contains("messageId"), "{err}");
6808 }
6809
6810 #[test]
6811 fn test_tool_call_content_chunk_serialization() {
6812 use serde_json::json;
6813
6814 assert_eq!(
6815 serde_json::to_value(SessionUpdate::ToolCallContentChunk(
6816 ToolCallContentChunk::new(
6817 "call_001",
6818 crate::v2::ContentBlock::Text(crate::v2::TextContent::new("partial output")),
6819 )
6820 ))
6821 .unwrap(),
6822 json!({
6823 "sessionUpdate": "tool_call_content_chunk",
6824 "toolCallId": "call_001",
6825 "content": {
6826 "type": "content",
6827 "content": {
6828 "type": "text",
6829 "text": "partial output"
6830 }
6831 }
6832 })
6833 );
6834
6835 let err = serde_json::from_value::<ToolCallContentChunk>(json!({
6836 "content": {
6837 "type": "content",
6838 "content": {
6839 "type": "text",
6840 "text": "partial output"
6841 }
6842 }
6843 }))
6844 .unwrap_err();
6845
6846 assert!(err.to_string().contains("toolCallId"), "{err}");
6847 }
6848
6849 #[test]
6850 fn test_full_message_serialization() {
6851 use serde_json::json;
6852
6853 assert_eq!(
6854 serde_json::to_value(SessionUpdate::UserMessage(
6855 UserMessage::new("msg_user_8f7a1").content(vec![ContentBlock::Text(
6856 crate::v2::TextContent::new("Hello")
6857 )])
6858 ))
6859 .unwrap(),
6860 json!({
6861 "sessionUpdate": "user_message",
6862 "messageId": "msg_user_8f7a1",
6863 "content": [
6864 {
6865 "type": "text",
6866 "text": "Hello"
6867 }
6868 ]
6869 })
6870 );
6871
6872 assert_eq!(
6873 serde_json::to_value(SessionUpdate::AgentMessage(
6874 AgentMessage::new("msg_agent_c42b9").content(vec![ContentBlock::Text(
6875 crate::v2::TextContent::new("Hello")
6876 )])
6877 ))
6878 .unwrap(),
6879 json!({
6880 "sessionUpdate": "agent_message",
6881 "messageId": "msg_agent_c42b9",
6882 "content": [
6883 {
6884 "type": "text",
6885 "text": "Hello"
6886 }
6887 ]
6888 })
6889 );
6890
6891 assert_eq!(
6892 serde_json::to_value(SessionUpdate::AgentThought(
6893 AgentThought::new("msg_thought_a12").content(vec![ContentBlock::Text(
6894 crate::v2::TextContent::new("Need to inspect the call sites first.")
6895 )])
6896 ))
6897 .unwrap(),
6898 json!({
6899 "sessionUpdate": "agent_thought",
6900 "messageId": "msg_thought_a12",
6901 "content": [
6902 {
6903 "type": "text",
6904 "text": "Need to inspect the call sites first."
6905 }
6906 ]
6907 })
6908 );
6909 }
6910
6911 #[test]
6912 fn test_message_upsert_serialization() {
6913 use serde_json::json;
6914
6915 assert_eq!(
6916 serde_json::to_value(SessionUpdate::UserMessage(
6917 UserMessage::new("msg_empty").content(Vec::<ContentBlock>::new())
6918 ))
6919 .unwrap(),
6920 json!({
6921 "sessionUpdate": "user_message",
6922 "messageId": "msg_empty",
6923 "content": []
6924 })
6925 );
6926
6927 let empty = serde_json::from_value::<UserMessage>(json!({
6928 "messageId": "msg_empty",
6929 "content": []
6930 }))
6931 .unwrap();
6932 assert!(matches!(
6933 empty.content,
6934 MaybeUndefined::Value(ref content) if content.is_empty()
6935 ));
6936
6937 let patch = serde_json::from_value::<AgentMessage>(json!({
6938 "messageId": "msg_agent_c42b9"
6939 }))
6940 .unwrap();
6941 assert_eq!(patch.content, MaybeUndefined::Undefined);
6942 assert_eq!(patch.meta, MaybeUndefined::Undefined);
6943
6944 let malformed_meta = serde_json::from_value::<AgentMessage>(json!({
6945 "messageId": "msg_agent_c42b9",
6946 "_meta": false
6947 }))
6948 .unwrap();
6949 assert_eq!(malformed_meta.meta, MaybeUndefined::Undefined);
6950
6951 let patch = serde_json::from_value::<AgentThought>(json!({
6952 "messageId": "msg_thought_a12"
6953 }))
6954 .unwrap();
6955 assert_eq!(patch.content, MaybeUndefined::Undefined);
6956
6957 let clear = serde_json::from_value::<UserMessage>(json!({
6958 "messageId": "msg_user_8f7a1",
6959 "content": null
6960 }))
6961 .unwrap();
6962 assert_eq!(clear.content, MaybeUndefined::Null);
6963
6964 let clear_meta = serde_json::from_value::<UserMessage>(json!({
6965 "messageId": "msg_user_8f7a1",
6966 "_meta": null
6967 }))
6968 .unwrap();
6969 assert_eq!(clear_meta.meta, MaybeUndefined::Null);
6970
6971 let mut meta = Meta::new();
6972 meta.insert("source".to_string(), json!("replay"));
6973
6974 assert_eq!(
6975 serde_json::to_value(SessionUpdate::UserMessage(
6976 UserMessage::new("msg_user_8f7a1").meta(meta)
6977 ))
6978 .unwrap(),
6979 json!({
6980 "sessionUpdate": "user_message",
6981 "messageId": "msg_user_8f7a1",
6982 "_meta": {
6983 "source": "replay"
6984 }
6985 })
6986 );
6987
6988 assert_eq!(
6989 serde_json::to_value(SessionUpdate::UserMessage(
6990 UserMessage::new("msg_user_8f7a1").meta(None::<Meta>)
6991 ))
6992 .unwrap(),
6993 json!({
6994 "sessionUpdate": "user_message",
6995 "messageId": "msg_user_8f7a1",
6996 "_meta": null
6997 })
6998 );
6999 }
7000
7001 #[test]
7002 fn test_usage_update_serialization() {
7003 use serde_json::json;
7004
7005 assert_eq!(
7006 serde_json::to_value(SessionUpdate::UsageUpdate(UsageUpdate::new(
7007 53_000, 200_000
7008 )))
7009 .unwrap(),
7010 json!({
7011 "sessionUpdate": "usage_update",
7012 "used": 53000,
7013 "size": 200_000
7014 })
7015 );
7016
7017 assert_eq!(
7018 serde_json::to_value(SessionUpdate::UsageUpdate(
7019 UsageUpdate::new(53_000, 200_000).cost(Cost::new(0.045, "USD"))
7020 ))
7021 .unwrap(),
7022 json!({
7023 "sessionUpdate": "usage_update",
7024 "used": 53000,
7025 "size": 200_000,
7026 "cost": {
7027 "amount": 0.045,
7028 "currency": "USD"
7029 }
7030 })
7031 );
7032
7033 let SessionUpdate::UsageUpdate(update) = serde_json::from_value(json!({
7034 "sessionUpdate": "usage_update",
7035 "used": 53000,
7036 "size": 200_000,
7037 "cost": null
7038 }))
7039 .unwrap() else {
7040 panic!("expected usage update");
7041 };
7042
7043 assert_eq!(update.cost, MaybeUndefined::Null);
7044
7045 let SessionUpdate::UsageUpdate(update) = serde_json::from_value(json!({
7046 "sessionUpdate": "usage_update",
7047 "used": 53000,
7048 "size": 200_000
7049 }))
7050 .unwrap() else {
7051 panic!("expected usage update");
7052 };
7053
7054 assert_eq!(update.cost, MaybeUndefined::Undefined);
7055 }
7056
7057 #[test]
7058 fn usage_update_meta_is_a_patch() {
7059 use serde_json::json;
7060
7061 let wire = |meta: Option<serde_json::Value>| {
7062 let mut wire = json!({"sessionUpdate": "usage_update", "used": 1, "size": 2});
7063 if let Some(meta) = meta {
7064 wire["_meta"] = meta;
7065 }
7066 wire
7067 };
7068 let patch = json!({"com.example/a": 1, "com.example/b": null});
7069 for (meta, expected) in [
7070 (None, MaybeUndefined::Undefined),
7071 (Some(json!(null)), MaybeUndefined::Null),
7072 (
7073 Some(patch.clone()),
7074 MaybeUndefined::Value(patch.as_object().unwrap().clone()),
7075 ),
7076 ] {
7077 let SessionUpdate::UsageUpdate(update) =
7078 serde_json::from_value(wire(meta.clone())).unwrap()
7079 else {
7080 panic!("expected usage update");
7081 };
7082 assert_eq!(update.meta, expected);
7083 assert_eq!(
7084 serde_json::to_value(SessionUpdate::UsageUpdate(update)).unwrap(),
7085 wire(meta)
7086 );
7087 }
7088 }
7089
7090 #[test]
7091 fn error_stop_reason_carries_failure_beside_discriminator() {
7092 use crate::v2::{Error, ErrorStopReason};
7093 use serde_json::json;
7094
7095 let update =
7096 SessionUpdate::StateUpdate(StateUpdate::Idle(IdleStateUpdate::new().stop_reason(
7097 StopReason::from(ErrorStopReason::new().error(Error::auth_required())),
7098 )));
7099 let wire = json!({
7100 "sessionUpdate": "state_update",
7101 "state": "idle",
7102 "stopReason": "error",
7103 "error": { "code": -32000, "message": "Authentication required" }
7104 });
7105 assert_eq!(serde_json::to_value(&update).unwrap(), wire);
7106 assert_eq!(
7107 serde_json::from_value::<SessionUpdate>(wire).unwrap(),
7108 update
7109 );
7110
7111 let with_data =
7112 StateUpdate::Idle(IdleStateUpdate::new().stop_reason(StopReason::from(
7113 ErrorStopReason::new().error(
7114 Error::new(-32099, "Provider unavailable").data(json!({ "status": 503 })),
7115 ),
7116 )));
7117 let wire = json!({
7118 "state": "idle",
7119 "stopReason": "error",
7120 "error": {
7121 "code": -32099,
7122 "message": "Provider unavailable",
7123 "data": { "status": 503 }
7124 }
7125 });
7126 assert_eq!(serde_json::to_value(&with_data).unwrap(), wire);
7127 assert_eq!(
7128 serde_json::from_value::<StateUpdate>(wire).unwrap(),
7129 with_data
7130 );
7131
7132 let without_details = StateUpdate::Idle(
7135 IdleStateUpdate::new().stop_reason(StopReason::from(ErrorStopReason::new())),
7136 );
7137 for error in [
7138 None,
7139 Some(json!(null)),
7140 Some(json!("failed")),
7141 Some(json!({ "message": "missing code" })),
7142 ] {
7143 let mut wire = json!({ "state": "idle", "stopReason": "error" });
7144 if let Some(error) = error {
7145 wire["error"] = error;
7146 }
7147 assert_eq!(
7148 serde_json::from_value::<StateUpdate>(wire).unwrap(),
7149 without_details
7150 );
7151 }
7152 assert_eq!(
7153 serde_json::to_value(&without_details).unwrap(),
7154 json!({ "state": "idle", "stopReason": "error" })
7155 );
7156
7157 let parsed: StateUpdate = serde_json::from_value(json!({
7161 "state": "idle",
7162 "stopReason": "end_turn",
7163 "error": { "code": -32603, "message": "Internal error" }
7164 }))
7165 .unwrap();
7166 assert_eq!(
7167 parsed,
7168 StateUpdate::Idle(IdleStateUpdate::new().stop_reason(StopReason::EndTurn))
7169 );
7170 }
7171
7172 #[test]
7173 fn flattened_stop_reason_keeps_open_enum_tolerance() {
7174 use crate::v2::OtherStopReason;
7175 use serde_json::json;
7176
7177 let meta: Meta = [("source".into(), json!("test"))].into_iter().collect();
7178
7179 for stop_reason in [None, Some(json!(null)), Some(json!(true)), Some(json!({}))] {
7182 let mut wire = json!({ "state": "idle", "_meta": { "source": "test" } });
7183 if let Some(stop_reason) = stop_reason {
7184 wire["stopReason"] = stop_reason;
7185 }
7186 let StateUpdate::Idle(idle) = serde_json::from_value(wire).unwrap() else {
7187 panic!("expected idle state update");
7188 };
7189 assert_eq!(idle.stop_reason, None);
7190 assert_eq!(idle.meta, Some(meta.clone()));
7191 }
7192
7193 let wire = json!({
7196 "state": "idle",
7197 "stopReason": "_paused",
7198 "resumeAfter": 30,
7199 "_meta": { "source": "test" }
7200 });
7201 let parsed: StateUpdate = serde_json::from_value(wire.clone()).unwrap();
7202 let expected = StateUpdate::Idle(
7203 IdleStateUpdate::new()
7204 .stop_reason(StopReason::Other(OtherStopReason::new(
7205 "_paused",
7206 [("resumeAfter".into(), json!(30))].into_iter().collect(),
7207 )))
7208 .meta(meta),
7209 );
7210 assert_eq!(parsed, expected);
7211 assert_eq!(serde_json::to_value(&parsed).unwrap(), wire);
7212 }
7213
7214 #[test]
7215 fn known_stop_reasons_are_never_read_as_other() {
7216 use crate::v2::{ErrorStopReason, OtherStopReason};
7217 use serde_json::json;
7218
7219 let known = [
7220 StopReason::EndTurn,
7221 StopReason::MaxTokens,
7222 StopReason::MaxTurnRequests,
7223 StopReason::Refusal,
7224 StopReason::Cancelled,
7225 StopReason::Error(ErrorStopReason::new()),
7226 ];
7227 for stop_reason in &known {
7229 match stop_reason {
7230 StopReason::EndTurn
7231 | StopReason::MaxTokens
7232 | StopReason::MaxTurnRequests
7233 | StopReason::Refusal
7234 | StopReason::Cancelled
7235 | StopReason::Error(_)
7236 | StopReason::Other(_) => {}
7237 }
7238 }
7239
7240 for stop_reason in known {
7241 let update = StateUpdate::Idle(IdleStateUpdate::new().stop_reason(stop_reason));
7242 let wire = serde_json::to_value(&update).unwrap();
7243 assert_eq!(
7244 serde_json::from_value::<StateUpdate>(wire.clone()).unwrap(),
7245 update
7246 );
7247 assert!(
7248 serde_json::from_value::<OtherStopReason>(
7249 json!({ "stopReason": wire["stopReason"] })
7250 )
7251 .is_err(),
7252 "{} must not be accepted as a custom stop reason",
7253 wire["stopReason"]
7254 );
7255 }
7256 }
7257
7258 #[test]
7259 fn unknown_stop_reason_leaves_usage_on_the_idle_update() {
7260 use serde_json::json;
7261
7262 let usage = json!({ "totalTokens": 10, "inputTokens": 6, "outputTokens": 4 });
7263 let wire = json!({ "state": "idle", "stopReason": "_paused", "usage": usage });
7264 let StateUpdate::Idle(idle) = serde_json::from_value(wire.clone()).unwrap() else {
7265 panic!("expected idle state update");
7266 };
7267 let Some(StopReason::Other(other)) = &idle.stop_reason else {
7268 panic!("expected a custom stop reason");
7269 };
7270 assert!(other.fields.is_empty());
7271
7272 #[cfg(feature = "unstable_end_turn_token_usage")]
7273 {
7274 assert!(idle.usage.is_some());
7275 assert_eq!(serde_json::to_value(&idle).unwrap()["usage"], usage);
7276 }
7277 #[cfg(not(feature = "unstable_end_turn_token_usage"))]
7280 assert!(serde_json::to_value(&idle).unwrap().get("usage").is_none());
7281 }
7282
7283 #[test]
7284 fn test_state_update_serialization() {
7285 use serde_json::json;
7286
7287 assert_eq!(
7288 serde_json::to_value(SessionUpdate::StateUpdate(StateUpdate::Running(
7289 RunningStateUpdate::new()
7290 )))
7291 .unwrap(),
7292 json!({
7293 "sessionUpdate": "state_update",
7294 "state": "running"
7295 })
7296 );
7297
7298 assert_eq!(
7299 serde_json::to_value(SessionUpdate::StateUpdate(StateUpdate::Idle(
7300 IdleStateUpdate::new().stop_reason(StopReason::EndTurn)
7301 )))
7302 .unwrap(),
7303 json!({
7304 "sessionUpdate": "state_update",
7305 "state": "idle",
7306 "stopReason": "end_turn"
7307 })
7308 );
7309
7310 let SessionUpdate::StateUpdate(update) = serde_json::from_value(json!({
7311 "sessionUpdate": "state_update",
7312 "state": "requires_action"
7313 }))
7314 .unwrap() else {
7315 panic!("expected state update");
7316 };
7317
7318 assert!(matches!(update, StateUpdate::RequiresAction(_)));
7319
7320 let SessionUpdate::StateUpdate(StateUpdate::Idle(update)) = serde_json::from_value(json!({
7321 "sessionUpdate": "state_update",
7322 "state": "idle",
7323 "stopReason": null
7324 }))
7325 .unwrap() else {
7326 panic!("expected idle state update");
7327 };
7328
7329 assert_eq!(update.stop_reason, None);
7330
7331 let SessionUpdate::StateUpdate(StateUpdate::Other(update)) =
7332 serde_json::from_value(json!({
7333 "sessionUpdate": "state_update",
7334 "state": "_paused",
7335 "label": "Paused"
7336 }))
7337 .unwrap()
7338 else {
7339 panic!("expected unknown state update");
7340 };
7341
7342 assert_eq!(update.state, "_paused");
7343 assert_eq!(update.fields["label"], json!("Paused"));
7344 }
7345
7346 #[test]
7347 fn session_update_preserves_unknown_variant() {
7348 use serde_json::json;
7349
7350 let update: SessionUpdate = serde_json::from_value(json!({
7351 "sessionUpdate": "_status_badge",
7352 "label": "Indexing",
7353 "progress": 0.5
7354 }))
7355 .unwrap();
7356
7357 let SessionUpdate::Other(unknown) = update else {
7358 panic!("expected unknown session update");
7359 };
7360
7361 assert_eq!(unknown.session_update, "_status_badge");
7362 assert_eq!(unknown.fields.get("label"), Some(&json!("Indexing")));
7363 assert_eq!(unknown.fields.get("progress"), Some(&json!(0.5)));
7364
7365 assert_eq!(
7366 serde_json::to_value(SessionUpdate::Other(unknown)).unwrap(),
7367 json!({
7368 "sessionUpdate": "_status_badge",
7369 "label": "Indexing",
7370 "progress": 0.5
7371 })
7372 );
7373 }
7374
7375 #[test]
7376 fn terminal_session_updates_use_known_discriminators() {
7377 use serde_json::json;
7378
7379 assert_eq!(
7380 serde_json::to_value(SessionUpdate::TerminalUpdate(
7381 TerminalUpdate::new("term_1").command("cargo test")
7382 ))
7383 .unwrap(),
7384 json!({
7385 "sessionUpdate": "terminal_update",
7386 "terminalId": "term_1",
7387 "command": "cargo test"
7388 })
7389 );
7390 assert_eq!(
7391 serde_json::to_value(SessionUpdate::TerminalOutputChunk(
7392 TerminalOutputChunk::new("term_1", "dGVzdAo=")
7393 ))
7394 .unwrap(),
7395 json!({
7396 "sessionUpdate": "terminal_output_chunk",
7397 "terminalId": "term_1",
7398 "data": "dGVzdAo="
7399 })
7400 );
7401 }
7402
7403 #[test]
7404 fn session_update_does_not_hide_malformed_known_terminal_variants() {
7405 use serde_json::json;
7406
7407 assert!(
7408 serde_json::from_value::<SessionUpdate>(json!({
7409 "sessionUpdate": "terminal_update"
7410 }))
7411 .is_err()
7412 );
7413 assert!(
7414 serde_json::from_value::<SessionUpdate>(json!({
7415 "sessionUpdate": "terminal_output_chunk",
7416 "terminalId": "term_1"
7417 }))
7418 .is_err()
7419 );
7420 }
7421
7422 #[test]
7423 fn test_plan_update_serialization() {
7424 use serde_json::json;
7425
7426 let plan_update =
7427 SessionUpdate::PlanUpdate(PlanUpdate::new(crate::v2::PlanUpdateContent::items(
7428 "plan-1",
7429 vec![crate::v2::PlanEntry::new(
7430 "Step 1",
7431 crate::v2::PlanEntryPriority::High,
7432 crate::v2::PlanEntryStatus::Pending,
7433 )],
7434 )));
7435
7436 assert_eq!(
7437 serde_json::to_value(plan_update).unwrap(),
7438 json!({
7439 "sessionUpdate": "plan_update",
7440 "plan": {
7441 "type": "items",
7442 "planId": "plan-1",
7443 "entries": [
7444 {
7445 "content": "Step 1",
7446 "priority": "high",
7447 "status": "pending"
7448 }
7449 ]
7450 }
7451 })
7452 );
7453 }
7454
7455 #[test]
7456 fn plan_operations_round_trip_as_known_session_updates() {
7457 use serde_json::json;
7458
7459 let markdown = crate::v2::PlanUpdateContent::markdown("plan-1", "# Next steps");
7460 for (wire, expected) in [
7461 (
7462 json!({"sessionUpdate": "plan_update", "plan": {
7463 "type": "markdown", "planId": "plan-1", "content": "# Next steps"
7464 }}),
7465 SessionUpdate::PlanUpdate(PlanUpdate::new(markdown)),
7466 ),
7467 (
7468 json!({"sessionUpdate": "plan_removed", "planId": "plan-1"}),
7469 SessionUpdate::PlanRemoved(PlanRemoved::new("plan-1")),
7470 ),
7471 ] {
7472 assert_eq!(
7473 serde_json::from_value::<SessionUpdate>(wire.clone()).unwrap(),
7474 expected
7475 );
7476 assert_eq!(serde_json::to_value(expected).unwrap(), wire);
7477 }
7478 }
7479
7480 #[test]
7481 fn available_command_uses_type_discriminator() {
7482 use serde_json::json;
7483
7484 let command = AvailableCommand::Command(
7485 Command::new("web", "Search the web")
7486 .input(AvailableCommandInput::Text(TextCommandInput::new("Query"))),
7487 );
7488
7489 let json = serde_json::to_value(&command).unwrap();
7490 assert_eq!(
7491 json,
7492 json!({
7493 "type": "command",
7494 "name": "web",
7495 "description": "Search the web",
7496 "input": { "type": "text", "hint": "Query" }
7497 })
7498 );
7499
7500 let roundtripped: AvailableCommand = serde_json::from_value(json).unwrap();
7501 assert_eq!(roundtripped, command);
7502 assert_eq!(roundtripped.name(), "web");
7503 assert_eq!(roundtripped.description(), "Search the web");
7504 }
7505
7506 #[test]
7507 fn available_command_preserves_unknown_typed_variant() {
7508 use serde_json::json;
7509
7510 let payload = json!({
7511 "type": "_skill",
7512 "name": "pdf-processing",
7513 "description": "Extract text from PDFs",
7514 "uri": "skill://pdf-processing/SKILL.md",
7515 "_meta": { "example.com/source": "mcp" }
7516 });
7517 let command: AvailableCommand = serde_json::from_value(payload.clone()).unwrap();
7518
7519 assert_eq!(command.name(), "pdf-processing");
7520 assert_eq!(command.description(), "Extract text from PDFs");
7521 assert!(command.meta().is_some());
7522
7523 let AvailableCommand::Other(unknown) = &command else {
7524 panic!("expected unknown command");
7525 };
7526 assert_eq!(unknown.type_, "_skill");
7527 assert_eq!(
7528 unknown.fields.get("uri"),
7529 Some(&json!("skill://pdf-processing/SKILL.md"))
7530 );
7531 assert_eq!(serde_json::to_value(&command).unwrap(), payload);
7532 }
7533
7534 #[test]
7535 fn available_command_unknown_tolerates_invalid_meta() {
7536 use serde_json::json;
7537
7538 let command: AvailableCommand = serde_json::from_value(json!({
7539 "type": "_skill",
7540 "name": "pdf-processing",
7541 "description": "Extract text from PDFs",
7542 "_meta": "oops"
7543 }))
7544 .unwrap();
7545
7546 assert!(matches!(command, AvailableCommand::Other(_)));
7547 assert!(command.meta().is_none());
7548 }
7549
7550 #[test]
7551 fn available_command_unknown_does_not_hide_malformed_command_variant() {
7552 use serde_json::json;
7553
7554 assert!(
7556 serde_json::from_value::<AvailableCommand>(json!({
7557 "name": "test",
7558 "description": "Run project tests"
7559 }))
7560 .is_err()
7561 );
7562 assert!(
7563 serde_json::from_value::<AvailableCommand>(json!({
7564 "type": "command",
7565 "name": "test"
7566 }))
7567 .is_err()
7568 );
7569 assert!(
7570 serde_json::from_value::<OtherAvailableCommand>(json!({
7571 "type": "command",
7572 "name": "test",
7573 "description": "Run project tests"
7574 }))
7575 .is_err()
7576 );
7577 assert!(
7578 serde_json::from_value::<AvailableCommand>(json!({
7579 "type": "_skill",
7580 "name": "pdf-processing"
7581 }))
7582 .is_err()
7583 );
7584 }
7585
7586 #[cfg(feature = "unstable_agent_skills")]
7587 #[test]
7588 fn skill_command_uses_type_discriminator() {
7589 use serde_json::json;
7590
7591 let skill = AvailableCommand::Skill(
7592 Skill::new("pdf-processing", "Extract text and tables from PDF files").path(
7593 AbsolutePath::new("/home/alice/.agents/skills/pdf-processing/SKILL.md"),
7594 ),
7595 );
7596
7597 let wire = json!({
7598 "type": "skill",
7599 "name": "pdf-processing",
7600 "description": "Extract text and tables from PDF files",
7601 "path": "/home/alice/.agents/skills/pdf-processing/SKILL.md"
7602 });
7603 assert_eq!(serde_json::to_value(&skill).unwrap(), wire);
7604
7605 let roundtripped: AvailableCommand = serde_json::from_value(wire).unwrap();
7606 assert_eq!(roundtripped, skill);
7607 assert_eq!(roundtripped.name(), "pdf-processing");
7608 assert_eq!(
7609 roundtripped.description(),
7610 "Extract text and tables from PDF files"
7611 );
7612 assert!(roundtripped.meta().is_none());
7613
7614 assert_eq!(
7616 serde_json::to_value(AvailableCommand::Skill(Skill::new(
7617 "simplify",
7618 "Simplify the changed code"
7619 )))
7620 .unwrap(),
7621 json!({
7622 "type": "skill",
7623 "name": "simplify",
7624 "description": "Simplify the changed code"
7625 })
7626 );
7627 }
7628
7629 #[cfg(feature = "unstable_agent_skills")]
7630 #[test]
7631 fn skill_command_treats_invalid_display_fields_as_absent() {
7632 use serde_json::json;
7633
7634 let expected = AvailableCommand::Skill(Skill::new("pdf-processing", "Extract text"));
7635 for (field, value) in [
7636 ("path", json!(null)),
7637 ("path", json!(7)),
7638 ("path", json!({ "uri": "file:///SKILL.md" })),
7639 ("_meta", json!(null)),
7640 ("_meta", json!("oops")),
7641 ] {
7642 let mut wire = json!({
7643 "type": "skill",
7644 "name": "pdf-processing",
7645 "description": "Extract text"
7646 });
7647 wire[field] = value;
7648 assert_eq!(
7649 serde_json::from_value::<AvailableCommand>(wire).unwrap(),
7650 expected,
7651 "{field}"
7652 );
7653 }
7654 }
7655
7656 #[cfg(feature = "unstable_agent_skills")]
7657 #[test]
7658 fn skill_command_has_no_input_specification() {
7659 use serde_json::json;
7660
7661 let skill: AvailableCommand = serde_json::from_value(json!({
7663 "type": "skill",
7664 "name": "pdf-processing",
7665 "description": "Extract text",
7666 "input": { "type": "text", "hint": "file or instructions" }
7667 }))
7668 .unwrap();
7669 assert_eq!(
7670 skill,
7671 AvailableCommand::Skill(Skill::new("pdf-processing", "Extract text"))
7672 );
7673 assert!(serde_json::to_value(&skill).unwrap().get("input").is_none());
7674 }
7675
7676 #[cfg(feature = "unstable_agent_skills")]
7677 #[test]
7678 fn malformed_skill_command_is_skipped_and_never_preserved_as_unknown() {
7679 use serde_json::json;
7680
7681 for malformed in [
7682 json!({ "type": "skill", "name": "pdf-processing" }),
7683 json!({ "type": "skill", "description": "Extract text" }),
7684 json!({ "type": "skill", "name": 1, "description": "Extract text" }),
7685 ] {
7686 assert!(serde_json::from_value::<AvailableCommand>(malformed.clone()).is_err());
7687 assert!(serde_json::from_value::<OtherAvailableCommand>(malformed).is_err());
7688 }
7689
7690 let update: AvailableCommandsUpdate = serde_json::from_value(json!({
7692 "availableCommands": [
7693 { "type": "skill", "name": "pdf-processing", "description": "Extract text" },
7694 { "type": "skill", "name": "broken" },
7695 { "type": "command", "name": "test", "description": "Run project tests" }
7696 ]
7697 }))
7698 .unwrap();
7699 assert_eq!(
7700 update.available_commands,
7701 vec![
7702 AvailableCommand::Skill(Skill::new("pdf-processing", "Extract text")),
7703 AvailableCommand::Command(Command::new("test", "Run project tests")),
7704 ]
7705 );
7706 }
7707
7708 #[cfg(feature = "unstable_agent_skills")]
7709 #[test]
7710 fn skill_commands_capability_is_advertised_only_by_an_object() {
7711 use serde_json::json;
7712
7713 let capabilities = ClientCapabilities::new().session(
7714 ClientSessionCapabilities::new()
7715 .commands(CommandsCapabilities::new().skill(CommandsSkillCapabilities::new())),
7716 );
7717 let wire = json!({ "session": { "commands": { "skill": {} } } });
7718 assert_eq!(serde_json::to_value(&capabilities).unwrap(), wire);
7719 assert_eq!(
7720 serde_json::from_value::<ClientCapabilities>(wire).unwrap(),
7721 capabilities
7722 );
7723
7724 for unsupported in [
7726 json!({}),
7727 json!({ "session": null }),
7728 json!({ "session": {} }),
7729 json!({ "session": { "commands": null } }),
7730 json!({ "session": { "commands": {} } }),
7731 json!({ "session": { "commands": true } }),
7732 json!({ "session": { "commands": { "skill": null } } }),
7733 json!({ "session": { "commands": { "skill": true } } }),
7734 json!({ "session": { "commands": { "skill": "supported" } } }),
7735 ] {
7736 let capabilities: ClientCapabilities = serde_json::from_value(unsupported).unwrap();
7737 assert!(
7738 capabilities
7739 .session
7740 .and_then(|session| session.commands)
7741 .and_then(|commands| commands.skill)
7742 .is_none()
7743 );
7744 }
7745 }
7746
7747 #[cfg(all(
7748 feature = "unstable_agent_skills",
7749 feature = "unstable_prompt_suggestions"
7750 ))]
7751 #[test]
7752 fn client_session_capabilities_are_independent_of_each_other() {
7753 use serde_json::json;
7754
7755 let capabilities: ClientCapabilities = serde_json::from_value(json!({
7757 "session": {
7758 "promptSuggestions": true,
7759 "commands": { "skill": {} }
7760 }
7761 }))
7762 .unwrap();
7763 let session = capabilities.session.unwrap();
7764 assert!(session.prompt_suggestions.is_none());
7765 assert!(session.commands.unwrap().skill.is_some());
7766 }
7767
7768 #[cfg(all(feature = "schemars", feature = "unstable_agent_skills"))]
7769 #[test]
7770 fn skill_schemas_keep_acted_on_fields_strict() {
7771 use serde_json::json;
7772
7773 let skill = serde_json::to_value(schemars::schema_for!(Skill)).unwrap();
7774 assert_eq!(skill["required"], json!(["name", "description"]));
7775 for lenient in ["path", "_meta"] {
7776 assert_eq!(
7777 skill["properties"][lenient]["x-deserialize-default-on-error"], true,
7778 "{lenient}"
7779 );
7780 }
7781
7782 let reference =
7784 serde_json::to_value(schemars::schema_for!(crate::v2::SkillReference)).unwrap();
7785 assert_eq!(reference["required"], json!(["name"]));
7786 assert!(
7787 reference["properties"]["name"]
7788 .get("x-deserialize-default-on-error")
7789 .is_none()
7790 );
7791 }
7792
7793 #[test]
7794 fn available_command_input_preserves_unknown_typed_variant() {
7795 use serde_json::json;
7796
7797 let input: AvailableCommandInput = serde_json::from_value(json!({
7798 "type": "_choices",
7799 "hint": "Pick one",
7800 "options": ["fast", "careful"]
7801 }))
7802 .unwrap();
7803
7804 let AvailableCommandInput::Other(unknown) = input else {
7805 panic!("expected unknown command input");
7806 };
7807
7808 assert_eq!(unknown.type_, "_choices");
7809 assert_eq!(unknown.fields.get("hint"), Some(&json!("Pick one")));
7810 assert_eq!(
7811 unknown.fields.get("options"),
7812 Some(&json!(["fast", "careful"]))
7813 );
7814 assert_eq!(
7815 serde_json::to_value(AvailableCommandInput::Other(unknown)).unwrap(),
7816 json!({
7817 "type": "_choices",
7818 "hint": "Pick one",
7819 "options": ["fast", "careful"]
7820 })
7821 );
7822 }
7823
7824 #[test]
7825 fn available_command_input_text_uses_type_discriminator() {
7826 use serde_json::json;
7827
7828 let input = AvailableCommandInput::Text(TextCommandInput::new("Describe changes"));
7829
7830 let json = serde_json::to_value(&input).unwrap();
7831 assert_eq!(
7832 json,
7833 json!({
7834 "type": "text",
7835 "hint": "Describe changes"
7836 })
7837 );
7838
7839 let roundtripped: AvailableCommandInput = serde_json::from_value(json).unwrap();
7840 assert!(matches!(roundtripped, AvailableCommandInput::Text(_)));
7841 }
7842
7843 #[test]
7844 fn request_permission_subject_tool_call_uses_type_discriminator() {
7845 use serde_json::json;
7846
7847 let subject = RequestPermissionSubject::from(ToolCallUpdate::new("call_001"));
7848
7849 let json = serde_json::to_value(&subject).unwrap();
7850 assert_eq!(
7851 json,
7852 json!({
7853 "type": "tool_call",
7854 "toolCall": {
7855 "toolCallId": "call_001"
7856 }
7857 })
7858 );
7859
7860 let roundtripped: RequestPermissionSubject = serde_json::from_value(json).unwrap();
7861 assert!(matches!(
7862 roundtripped,
7863 RequestPermissionSubject::ToolCall(_)
7864 ));
7865 }
7866
7867 #[test]
7868 fn request_permission_subject_command_uses_type_discriminator() {
7869 use serde_json::json;
7870
7871 let mut meta = Meta::new();
7872 meta.insert("source".to_string(), json!("shell"));
7873 let subject = RequestPermissionSubject::from(
7874 CommandPermissionSubject::new("cargo test", "/workspace/project")
7875 .tool_call_id("call_001")
7876 .terminal_id("term_1")
7877 .meta(meta),
7878 );
7879
7880 let json = serde_json::to_value(&subject).unwrap();
7881 assert_eq!(
7882 json,
7883 json!({
7884 "type": "command",
7885 "command": "cargo test",
7886 "cwd": "/workspace/project",
7887 "toolCallId": "call_001",
7888 "terminalId": "term_1",
7889 "_meta": {
7890 "source": "shell"
7891 }
7892 })
7893 );
7894
7895 let roundtripped: RequestPermissionSubject = serde_json::from_value(json).unwrap();
7896 assert!(matches!(roundtripped, RequestPermissionSubject::Command(_)));
7897 }
7898
7899 #[test]
7900 fn command_permission_subject_treats_optional_association_nulls_as_omitted() {
7901 use serde_json::json;
7902
7903 let subject: RequestPermissionSubject = serde_json::from_value(json!({
7904 "type": "command",
7905 "command": "cargo test",
7906 "cwd": "/workspace/project",
7907 "toolCallId": null,
7908 "terminalId": null,
7909 "_meta": null
7910 }))
7911 .unwrap();
7912
7913 let RequestPermissionSubject::Command(subject) = subject else {
7914 panic!("expected command permission subject");
7915 };
7916 assert_eq!(subject.cwd, AbsolutePath::new("/workspace/project"));
7917 assert_eq!(subject.tool_call_id, None);
7918 assert_eq!(subject.terminal_id, None);
7919 assert_eq!(subject.meta, None);
7920 assert_eq!(
7921 serde_json::to_value(RequestPermissionSubject::Command(subject)).unwrap(),
7922 json!({
7923 "type": "command",
7924 "command": "cargo test",
7925 "cwd": "/workspace/project"
7926 })
7927 );
7928 }
7929
7930 #[test]
7931 fn request_permission_subject_preserves_unknown_variant() {
7932 use serde_json::json;
7933
7934 let subject: RequestPermissionSubject = serde_json::from_value(json!({
7935 "type": "_review",
7936 "reason": "needs-review",
7937 "retryAfterSeconds": 30
7938 }))
7939 .unwrap();
7940
7941 let RequestPermissionSubject::Other(unknown) = subject else {
7942 panic!("expected unknown permission subject");
7943 };
7944
7945 assert_eq!(unknown.type_, "_review");
7946 assert_eq!(unknown.fields.get("reason"), Some(&json!("needs-review")));
7947 assert_eq!(unknown.fields.get("retryAfterSeconds"), Some(&json!(30)));
7948 assert_eq!(
7949 serde_json::to_value(RequestPermissionSubject::Other(unknown)).unwrap(),
7950 json!({
7951 "type": "_review",
7952 "reason": "needs-review",
7953 "retryAfterSeconds": 30
7954 })
7955 );
7956 }
7957
7958 #[test]
7959 fn request_permission_subject_unknown_does_not_hide_malformed_known_variant() {
7960 use serde_json::json;
7961
7962 assert!(
7963 serde_json::from_value::<RequestPermissionSubject>(json!({
7964 "type": "tool_call"
7965 }))
7966 .is_err()
7967 );
7968 assert!(
7969 serde_json::from_value::<RequestPermissionSubject>(json!({
7970 "type": 1
7971 }))
7972 .is_err()
7973 );
7974 assert!(
7975 serde_json::from_value::<RequestPermissionSubject>(json!({
7976 "type": "command",
7977 "cwd": "/workspace/project"
7978 }))
7979 .is_err()
7980 );
7981 assert!(
7982 serde_json::from_value::<RequestPermissionSubject>(json!({
7983 "type": "command",
7984 "command": "cargo test"
7985 }))
7986 .is_err()
7987 );
7988 assert!(
7989 serde_json::from_value::<RequestPermissionSubject>(json!({
7990 "type": "command",
7991 "command": "cargo test",
7992 "cwd": null
7993 }))
7994 .is_err()
7995 );
7996 }
7997
7998 #[test]
7999 fn request_permission_title_and_description_are_separate_from_tool_call_content() {
8000 use serde_json::json;
8001
8002 let request =
8003 RequestPermissionRequest::new("sess_abc123def456", "Approve file edit?", Vec::new())
8004 .description("Allow this tool to edit src/main.rs?")
8005 .subject(RequestPermissionSubject::from(ToolCallUpdate::new(
8006 "call_001",
8007 )));
8008
8009 assert_eq!(
8010 serde_json::to_value(request).unwrap(),
8011 json!({
8012 "sessionId": "sess_abc123def456",
8013 "title": "Approve file edit?",
8014 "description": "Allow this tool to edit src/main.rs?",
8015 "subject": {
8016 "type": "tool_call",
8017 "toolCall": {
8018 "toolCallId": "call_001"
8019 }
8020 },
8021 "options": []
8022 })
8023 );
8024 }
8025
8026 #[test]
8027 fn request_permission_requires_title_and_allows_missing_subject() {
8028 use serde_json::json;
8029
8030 let request = RequestPermissionRequest::new(
8031 "sess_abc123def456",
8032 "Approve elevated permissions?",
8033 Vec::new(),
8034 );
8035
8036 assert_eq!(
8037 serde_json::to_value(request).unwrap(),
8038 json!({
8039 "sessionId": "sess_abc123def456",
8040 "title": "Approve elevated permissions?",
8041 "options": []
8042 })
8043 );
8044
8045 let options = json!([{ "optionId": "allow", "name": "Allow", "kind": "allow_once" }]);
8046 let missing_subject: RequestPermissionRequest = serde_json::from_value(json!({
8047 "sessionId": "sess_abc123def456",
8048 "title": "Approve elevated permissions?",
8049 "options": options
8050 }))
8051 .unwrap();
8052 assert!(missing_subject.subject.is_none());
8053
8054 let null_subject: RequestPermissionRequest = serde_json::from_value(json!({
8055 "sessionId": "sess_abc123def456",
8056 "title": "Approve elevated permissions?",
8057 "subject": null,
8058 "options": options
8059 }))
8060 .unwrap();
8061 assert!(null_subject.subject.is_none());
8062
8063 assert!(
8064 serde_json::from_value::<RequestPermissionRequest>(json!({
8065 "sessionId": "sess_abc123def456",
8066 "options": options
8067 }))
8068 .is_err()
8069 );
8070 }
8071
8072 #[test]
8073 fn request_permission_outcome_preserves_unknown_variant() {
8074 use serde_json::json;
8075
8076 let outcome: RequestPermissionOutcome = serde_json::from_value(json!({
8077 "outcome": "_defer",
8078 "reason": "needs-review",
8079 "retryAfterSeconds": 30
8080 }))
8081 .unwrap();
8082
8083 let RequestPermissionOutcome::Other(unknown) = outcome else {
8084 panic!("expected unknown permission outcome");
8085 };
8086
8087 assert_eq!(unknown.outcome, "_defer");
8088 assert_eq!(unknown.fields.get("reason"), Some(&json!("needs-review")));
8089 assert_eq!(unknown.fields.get("retryAfterSeconds"), Some(&json!(30)));
8090 assert_eq!(
8091 serde_json::to_value(RequestPermissionOutcome::Other(unknown)).unwrap(),
8092 json!({
8093 "outcome": "_defer",
8094 "reason": "needs-review",
8095 "retryAfterSeconds": 30
8096 })
8097 );
8098 }
8099
8100 #[test]
8101 fn request_permission_outcome_unknown_does_not_hide_malformed_known_variant() {
8102 use serde_json::json;
8103
8104 assert!(
8105 serde_json::from_value::<RequestPermissionOutcome>(json!({
8106 "outcome": "selected"
8107 }))
8108 .is_err()
8109 );
8110 assert!(
8111 serde_json::from_value::<RequestPermissionOutcome>(json!({
8112 "outcome": 1
8113 }))
8114 .is_err()
8115 );
8116 }
8117
8118 #[test]
8119 fn available_command_input_unknown_does_not_hide_malformed_text_variant() {
8120 use serde_json::json;
8121
8122 assert!(serde_json::from_value::<AvailableCommandInput>(json!({})).is_err());
8123 assert!(
8124 serde_json::from_value::<AvailableCommandInput>(json!({
8125 "hint": "Pick one"
8126 }))
8127 .is_err()
8128 );
8129 assert!(
8130 serde_json::from_value::<AvailableCommandInput>(json!({
8131 "type": 1,
8132 "hint": "Pick one"
8133 }))
8134 .is_err()
8135 );
8136 assert!(
8137 serde_json::from_value::<OtherAvailableCommandInput>(json!({
8138 "type": "text",
8139 "hint": "Pick one"
8140 }))
8141 .is_err()
8142 );
8143 }
8144
8145 #[cfg(feature = "unstable_mcp_over_acp")]
8146 #[test]
8147 fn test_agent_mcp_request_method_names() {
8148 use serde_json::json;
8149
8150 let params: serde_json::Map<String, serde_json::Value> =
8151 [("cursor".to_string(), json!("abc"))].into_iter().collect();
8152
8153 assert_eq!(CLIENT_METHOD_NAMES.mcp_message, "mcp/message");
8154 assert_eq!(
8155 AgentRequest::MessageMcpRequest(Box::new(MessageMcpRequest::new(
8156 "server-1",
8157 "req-1",
8158 "tools/list"
8159 )))
8160 .method(),
8161 "mcp/message"
8162 );
8163 assert_eq!(
8164 serde_json::to_value(
8165 MessageMcpRequest::new("server-1", "req-1", "tools/list").params(params)
8166 )
8167 .unwrap(),
8168 json!({
8169 "serverId": "server-1",
8170 "requestId": "req-1",
8171 "method": "tools/list",
8172 "params": { "cursor": "abc" }
8173 })
8174 );
8175
8176 let request_with_null_params: MessageMcpRequest = serde_json::from_value(json!({
8177 "serverId": "server-1",
8178 "requestId": "req-1",
8179 "method": "tools/list",
8180 "params": null,
8181 "_meta": null
8182 }))
8183 .unwrap();
8184 assert_eq!(request_with_null_params.params, None);
8185 assert_eq!(request_with_null_params.meta, None);
8186 for key in ["serverId", "requestId", "method"] {
8187 let mut value =
8188 json!({"serverId":"server-1", "requestId":"req-1", "method":"tools/list"});
8189 value.as_object_mut().unwrap().remove(key);
8190 assert!(serde_json::from_value::<MessageMcpRequest>(value).is_err());
8191 }
8192 for key in ["serverId", "requestId", "method"] {
8193 let mut value =
8194 json!({"serverId":"server-1", "requestId":"req-1", "method":"tools/list"});
8195 value[key] = serde_json::Value::Null;
8196 assert!(serde_json::from_value::<MessageMcpRequest>(value).is_err());
8197 }
8198 }
8199
8200 #[test]
8201 fn test_auth_capabilities_serialize_terminal_support_as_object() {
8202 use serde_json::json;
8203
8204 let capabilities = ClientAuthCapabilities::new().terminal(TerminalAuthCapabilities::new());
8205
8206 assert_eq!(
8207 serde_json::to_value(&capabilities).unwrap(),
8208 json!({
8209 "terminal": {}
8210 })
8211 );
8212
8213 let deserialized: ClientAuthCapabilities = serde_json::from_value(json!({
8214 "terminal": false
8215 }))
8216 .unwrap();
8217 assert!(deserialized.terminal.is_none());
8218 }
8219
8220 #[test]
8221 fn request_permission_request_rejects_malformed_options() {
8222 use serde_json::json;
8223
8224 assert!(
8225 serde_json::from_value::<RequestPermissionRequest>(json!({
8226 "sessionId": "sess-1",
8227 "title": "Run tool?",
8228 "options": "not-an-array"
8229 }))
8230 .is_err()
8231 );
8232 assert!(
8233 serde_json::from_value::<RequestPermissionRequest>(json!({
8234 "sessionId": "sess-1",
8235 "title": "Run tool?",
8236 "options": [{"optionId": "allow"}]
8237 }))
8238 .is_err()
8239 );
8240 assert!(
8242 serde_json::from_value::<RequestPermissionRequest>(json!({
8243 "sessionId": "sess-1",
8244 "title": "Run tool?",
8245 "options": []
8246 }))
8247 .is_err()
8248 );
8249 }
8250
8251 #[test]
8252 fn malformed_plan_removed_is_not_hidden_as_unknown_update() {
8253 use serde_json::json;
8254
8255 assert!(
8256 serde_json::from_value::<SessionUpdate>(json!({
8257 "sessionUpdate": "plan_removed"
8258 }))
8259 .is_err()
8260 );
8261 }
8262
8263 #[cfg(feature = "unstable_session_cursors")]
8264 #[test]
8265 fn cursor_updates_round_trip_and_patch_capabilities() {
8266 use serde_json::json;
8267
8268 let update = SessionUpdate::CursorUpdate(
8269 CursorUpdate::new("cur_1")
8270 .capabilities(CursorCapabilities::new())
8271 .anchor(CursorAnchor::UserMessage(CursorMessageAnchor::new(
8272 "msg_user_2",
8273 CursorAnchorPosition::Before,
8274 ))),
8275 );
8276 let wire = json!({
8277 "sessionUpdate": "cursor_update",
8278 "cursorId": "cur_1",
8279 "capabilities": {},
8280 "anchor": { "type": "user_message", "messageId": "msg_user_2", "position": "before" }
8281 });
8282 assert_eq!(serde_json::to_value(&update).unwrap(), wire);
8283 assert_eq!(
8284 serde_json::from_value::<SessionUpdate>(wire).unwrap(),
8285 update
8286 );
8287
8288 let SessionUpdate::CursorUpdate(omitted) = serde_json::from_value(json!({
8290 "sessionUpdate": "cursor_update",
8291 "cursorId": "cur_1"
8292 }))
8293 .unwrap() else {
8294 panic!("expected cursor update");
8295 };
8296 assert!(omitted.capabilities.is_undefined());
8297 assert_eq!(omitted.anchor, None);
8298 assert!(omitted.meta.is_undefined());
8299 assert_eq!(
8300 serde_json::to_value(SessionUpdate::CursorUpdate(CursorUpdate::new("cur_1"))).unwrap(),
8301 json!({ "sessionUpdate": "cursor_update", "cursorId": "cur_1" })
8302 );
8303
8304 let SessionUpdate::CursorUpdate(cleared) = serde_json::from_value(json!({
8306 "sessionUpdate": "cursor_update",
8307 "cursorId": "cur_1",
8308 "capabilities": null,
8309 "anchor": null
8310 }))
8311 .unwrap() else {
8312 panic!("expected cursor update");
8313 };
8314 assert!(cleared.capabilities.is_null());
8315 assert_eq!(cleared.anchor, None);
8316 assert_eq!(
8317 serde_json::to_value(SessionUpdate::CursorUpdate(
8318 CursorUpdate::new("cur_1").capabilities(None)
8319 ))
8320 .unwrap(),
8321 json!({ "sessionUpdate": "cursor_update", "cursorId": "cur_1", "capabilities": null })
8322 );
8323 }
8324
8325 #[cfg(feature = "unstable_session_cursors")]
8326 #[test]
8327 fn cursor_anchors_cover_each_entity_type_and_preserve_unknown_ones() {
8328 use serde_json::json;
8329
8330 for (anchor, wire) in [
8331 (
8332 CursorAnchor::AgentMessage(CursorMessageAnchor::new(
8333 "msg_agent_1",
8334 CursorAnchorPosition::After,
8335 )),
8336 json!({ "type": "agent_message", "messageId": "msg_agent_1", "position": "after" }),
8337 ),
8338 (
8339 CursorAnchor::AgentThought(CursorMessageAnchor::new(
8340 "msg_agent_1",
8341 CursorAnchorPosition::After,
8342 )),
8343 json!({ "type": "agent_thought", "messageId": "msg_agent_1", "position": "after" }),
8344 ),
8345 (
8346 CursorAnchor::SessionMessage(CursorMessageAnchor::new(
8347 "msg_session_1",
8348 CursorAnchorPosition::Before,
8349 )),
8350 json!({ "type": "session_message", "messageId": "msg_session_1", "position": "before" }),
8351 ),
8352 (
8353 CursorAnchor::ToolCall(CursorToolCallAnchor::new(
8354 "call_1",
8355 CursorAnchorPosition::After,
8356 )),
8357 json!({ "type": "tool_call", "toolCallId": "call_1", "position": "after" }),
8358 ),
8359 (
8360 CursorAnchor::Compaction(CursorCompactionAnchor::new(
8361 "cmp_1",
8362 CursorAnchorPosition::Before,
8363 )),
8364 json!({ "type": "compaction", "compactionId": "cmp_1", "position": "before" }),
8365 ),
8366 ] {
8367 assert_eq!(serde_json::to_value(&anchor).unwrap(), wire);
8368 assert_eq!(
8369 serde_json::from_value::<CursorAnchor>(wire).unwrap(),
8370 anchor
8371 );
8372 }
8373
8374 let wire = json!({ "type": "_acme_marker", "markerId": "mk_1", "position": "after" });
8376 let other = serde_json::from_value::<CursorAnchor>(wire.clone()).unwrap();
8377 assert!(matches!(other, CursorAnchor::Other(_)));
8378 assert_eq!(serde_json::to_value(&other).unwrap(), wire);
8379
8380 let wire =
8382 json!({ "type": "user_message", "messageId": "msg_user_2", "position": "inside" });
8383 let future = serde_json::from_value::<CursorAnchor>(wire.clone()).unwrap();
8384 assert_eq!(
8385 future,
8386 CursorAnchor::UserMessage(CursorMessageAnchor::new(
8387 "msg_user_2",
8388 CursorAnchorPosition::Other("inside".into()),
8389 ))
8390 );
8391 assert_eq!(serde_json::to_value(&future).unwrap(), wire);
8392 }
8393
8394 #[cfg(feature = "unstable_session_cursors")]
8395 #[test]
8396 fn malformed_cursor_anchor_fails_the_update() {
8397 use serde_json::json;
8398
8399 for anchor in [
8401 json!({ "type": "user_message", "position": "before" }),
8402 json!({ "type": "tool_call", "toolCallId": 7, "position": "after" }),
8403 json!({ "type": "compaction", "compactionId": "cmp_1" }),
8404 json!({ "messageId": "msg_user_2", "position": "before" }),
8405 json!("before"),
8406 ] {
8407 assert!(
8408 serde_json::from_value::<SessionUpdate>(json!({
8409 "sessionUpdate": "cursor_update",
8410 "cursorId": "cur_1",
8411 "anchor": anchor
8412 }))
8413 .is_err(),
8414 "{anchor}"
8415 );
8416 }
8417 assert!(
8419 serde_json::from_value::<SessionUpdate>(json!({ "sessionUpdate": "cursor_update" }))
8420 .is_err()
8421 );
8422 }
8423
8424 #[cfg(feature = "unstable_session_cursors")]
8425 #[test]
8426 fn malformed_cursor_capabilities_are_not_advertised() {
8427 use serde_json::json;
8428
8429 let SessionUpdate::CursorUpdate(update) = serde_json::from_value(json!({
8431 "sessionUpdate": "cursor_update",
8432 "cursorId": "cur_1",
8433 "capabilities": "fork"
8434 }))
8435 .unwrap() else {
8436 panic!("expected cursor update");
8437 };
8438 assert!(update.capabilities.is_undefined());
8439
8440 assert_eq!(
8442 serde_json::from_value::<CursorCapabilities>(json!({ "futureMethod": {} })).unwrap(),
8443 CursorCapabilities::new()
8444 );
8445
8446 #[cfg(feature = "unstable_session_fork")]
8447 {
8448 assert_eq!(
8449 serde_json::to_value(CursorCapabilities::new().fork(CursorForkCapabilities::new()))
8450 .unwrap(),
8451 json!({ "fork": {} })
8452 );
8453 assert_eq!(
8454 serde_json::from_value::<CursorCapabilities>(json!({ "fork": {} }))
8455 .unwrap()
8456 .fork,
8457 Some(CursorForkCapabilities::new())
8458 );
8459 for fork in [json!(null), json!(true), json!("yes")] {
8460 assert_eq!(
8461 serde_json::from_value::<CursorCapabilities>(json!({ "fork": fork }))
8462 .unwrap()
8463 .fork,
8464 None
8465 );
8466 }
8467 }
8468 }
8469}