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