Skip to main content

codex_sdk_rs/
types.rs

1use std::collections::BTreeMap;
2use std::fmt;
3
4use serde::de::Error as _;
5use serde::{Deserialize, Deserializer, Serialize, Serializer};
6use serde_json::{Map, Value, json};
7
8macro_rules! forward_compatible_string_enum {
9    (
10        $(#[$meta:meta])*
11        pub enum $name:ident {
12            $($variant:ident = $value:literal),+ $(,)?
13        }
14    ) => {
15        $(#[$meta])*
16        #[derive(Clone, Debug, Eq, Hash, PartialEq)]
17        pub enum $name {
18            $($variant),+,
19            Unknown(String),
20        }
21
22        impl $name {
23            pub fn as_str(&self) -> &str {
24                match self {
25                    $(Self::$variant => $value),+,
26                    Self::Unknown(value) => value,
27                }
28            }
29        }
30
31        impl Serialize for $name {
32            fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
33            where
34                S: Serializer,
35            {
36                serializer.serialize_str(self.as_str())
37            }
38        }
39
40        impl<'de> Deserialize<'de> for $name {
41            fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
42            where
43                D: Deserializer<'de>,
44            {
45                let value = String::deserialize(deserializer)?;
46                Ok(match value.as_str() {
47                    $($value => Self::$variant),+,
48                    _ => Self::Unknown(value),
49                })
50            }
51        }
52
53        impl fmt::Display for $name {
54            fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
55                formatter.write_str(self.as_str())
56            }
57        }
58    };
59}
60
61/// High-level approval behavior matching the Python SDK.
62#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
63pub enum ApprovalMode {
64    DenyAll,
65    #[default]
66    AutoReview,
67}
68
69/// Filesystem access preset used for threads and turns.
70#[derive(Clone, Copy, Debug, Eq, PartialEq)]
71pub enum Sandbox {
72    ReadOnly,
73    WorkspaceWrite,
74    FullAccess,
75}
76
77impl Sandbox {
78    pub(crate) fn mode(self) -> &'static str {
79        match self {
80            Self::ReadOnly => "read-only",
81            Self::WorkspaceWrite => "workspace-write",
82            Self::FullAccess => "danger-full-access",
83        }
84    }
85
86    pub(crate) fn policy(self) -> Value {
87        match self {
88            Self::ReadOnly => json!({
89                "networkAccess": false,
90                "type": "readOnly",
91            }),
92            Self::WorkspaceWrite => json!({
93                "excludeSlashTmp": false,
94                "excludeTmpdirEnvVar": false,
95                "networkAccess": false,
96                "type": "workspaceWrite",
97                "writableRoots": [],
98            }),
99            Self::FullAccess => json!({"type": "dangerFullAccess"}),
100        }
101    }
102}
103
104#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
105#[serde(rename_all = "snake_case")]
106pub enum ApprovalsReviewer {
107    User,
108    AutoReview,
109    GuardianSubagent,
110}
111
112#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
113pub enum AskForApprovalValue {
114    #[serde(rename = "untrusted")]
115    Untrusted,
116    #[serde(rename = "on-request")]
117    OnRequest,
118    #[serde(rename = "never")]
119    Never,
120}
121
122/// App-server approval policy, including future granular policy objects.
123#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
124#[serde(untagged)]
125pub enum AskForApproval {
126    Preset(AskForApprovalValue),
127    Granular(Value),
128}
129
130forward_compatible_string_enum! {
131    /// Model reasoning effort. Unknown strings are retained for protocol forward compatibility.
132    pub enum ReasoningEffort {
133        None = "none",
134        Minimal = "minimal",
135        Low = "low",
136        Medium = "medium",
137        High = "high",
138        XHigh = "xhigh",
139        Max = "max",
140        Ultra = "ultra"
141    }
142}
143
144forward_compatible_string_enum! {
145    pub enum PlanType {
146        Free = "free",
147        Go = "go",
148        Plus = "plus",
149        Pro = "pro",
150        Prolite = "prolite",
151        Team = "team",
152        SelfServeBusinessUsageBased = "self_serve_business_usage_based",
153        Business = "business",
154        EnterpriseCbpUsageBased = "enterprise_cbp_usage_based",
155        Enterprise = "enterprise",
156        Edu = "edu",
157        UnknownPlan = "unknown"
158    }
159}
160
161forward_compatible_string_enum! {
162    pub enum ThreadSource {
163        User = "user",
164        Subagent = "subagent",
165        MemoryConsolidation = "memory_consolidation"
166    }
167}
168
169forward_compatible_string_enum! {
170    pub enum MessagePhase {
171        Commentary = "commentary",
172        FinalAnswer = "final_answer"
173    }
174}
175
176#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
177#[serde(rename_all = "lowercase")]
178pub enum Personality {
179    None,
180    Friendly,
181    Pragmatic,
182}
183
184#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
185#[serde(rename_all = "lowercase")]
186pub enum ReasoningSummary {
187    Auto,
188    Concise,
189    Detailed,
190    None,
191}
192
193#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
194pub enum SandboxMode {
195    #[serde(rename = "read-only")]
196    ReadOnly,
197    #[serde(rename = "workspace-write")]
198    WorkspaceWrite,
199    #[serde(rename = "danger-full-access")]
200    DangerFullAccess,
201}
202
203/// Raw sandbox policy returned by the runtime.
204#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
205#[serde(transparent)]
206pub struct SandboxPolicy(pub Value);
207
208#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
209#[serde(rename_all = "lowercase")]
210pub enum SortDirection {
211    Asc,
212    Desc,
213}
214
215#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
216pub enum ThreadSortKey {
217    #[serde(rename = "created_at")]
218    CreatedAt,
219    #[serde(rename = "updated_at")]
220    UpdatedAt,
221    #[serde(rename = "recency_at")]
222    RecencyAt,
223}
224
225#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
226pub enum ThreadSourceKind {
227    #[serde(rename = "cli")]
228    Cli,
229    #[serde(rename = "vscode")]
230    Vscode,
231    #[serde(rename = "exec")]
232    Exec,
233    #[serde(rename = "appServer")]
234    AppServer,
235    #[serde(rename = "subAgent")]
236    SubAgent,
237    #[serde(rename = "subAgentReview")]
238    SubAgentReview,
239    #[serde(rename = "subAgentCompact")]
240    SubAgentCompact,
241    #[serde(rename = "subAgentThreadSpawn")]
242    SubAgentThreadSpawn,
243    #[serde(rename = "subAgentOther")]
244    SubAgentOther,
245    #[serde(rename = "unknown")]
246    Unknown,
247}
248
249#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
250#[serde(rename_all = "lowercase")]
251pub enum ThreadStartSource {
252    Startup,
253    Clear,
254}
255
256#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
257#[serde(untagged)]
258pub enum ThreadListCwdFilter {
259    One(String),
260    Many(Vec<String>),
261}
262
263#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
264pub enum TurnStatus {
265    #[serde(rename = "completed")]
266    Completed,
267    #[serde(rename = "interrupted")]
268    Interrupted,
269    #[serde(rename = "failed")]
270    Failed,
271    #[serde(rename = "inProgress")]
272    InProgress,
273}
274
275/// One item accepted by a turn or steering request.
276#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
277#[serde(tag = "type")]
278pub enum InputItem {
279    #[serde(rename = "text")]
280    Text { text: String },
281    #[serde(rename = "image")]
282    Image { url: String },
283    #[serde(rename = "localImage")]
284    LocalImage { path: String },
285    #[serde(rename = "skill")]
286    Skill { name: String, path: String },
287    #[serde(rename = "mention")]
288    Mention { name: String, path: String },
289}
290
291#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
292pub struct TextInput {
293    pub text: String,
294}
295
296#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
297pub struct ImageInput {
298    pub url: String,
299}
300
301#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
302pub struct LocalImageInput {
303    pub path: String,
304}
305
306#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
307pub struct SkillInput {
308    pub name: String,
309    pub path: String,
310}
311
312#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
313pub struct MentionInput {
314    pub name: String,
315    pub path: String,
316}
317
318impl InputItem {
319    pub fn text(text: impl Into<String>) -> Self {
320        Self::Text { text: text.into() }
321    }
322
323    pub fn image(url: impl Into<String>) -> Self {
324        Self::Image { url: url.into() }
325    }
326
327    pub fn local_image(path: impl Into<String>) -> Self {
328        Self::LocalImage { path: path.into() }
329    }
330
331    pub fn skill(name: impl Into<String>, path: impl Into<String>) -> Self {
332        Self::Skill {
333            name: name.into(),
334            path: path.into(),
335        }
336    }
337
338    pub fn mention(name: impl Into<String>, path: impl Into<String>) -> Self {
339        Self::Mention {
340            name: name.into(),
341            path: path.into(),
342        }
343    }
344}
345
346impl From<TextInput> for InputItem {
347    fn from(input: TextInput) -> Self {
348        Self::Text { text: input.text }
349    }
350}
351
352impl From<ImageInput> for InputItem {
353    fn from(input: ImageInput) -> Self {
354        Self::Image { url: input.url }
355    }
356}
357
358impl From<LocalImageInput> for InputItem {
359    fn from(input: LocalImageInput) -> Self {
360        Self::LocalImage { path: input.path }
361    }
362}
363
364impl From<SkillInput> for InputItem {
365    fn from(input: SkillInput) -> Self {
366        Self::Skill {
367            name: input.name,
368            path: input.path,
369        }
370    }
371}
372
373impl From<MentionInput> for InputItem {
374    fn from(input: MentionInput) -> Self {
375        Self::Mention {
376            name: input.name,
377            path: input.path,
378        }
379    }
380}
381
382/// Normalized turn input.
383#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
384#[serde(transparent)]
385pub struct Input(pub Vec<InputItem>);
386
387impl From<Vec<InputItem>> for Input {
388    fn from(items: Vec<InputItem>) -> Self {
389        Self(items)
390    }
391}
392
393impl From<String> for Input {
394    fn from(text: String) -> Self {
395        Self(vec![InputItem::text(text)])
396    }
397}
398
399impl From<&str> for Input {
400    fn from(text: &str) -> Self {
401        Self::from(text.to_owned())
402    }
403}
404
405impl<T> From<T> for Input
406where
407    T: Into<InputItem>,
408{
409    fn from(item: T) -> Self {
410        Self(vec![item.into()])
411    }
412}
413
414pub type RunInput = Input;
415
416#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
417#[serde(rename_all = "camelCase")]
418pub struct ServerInfo {
419    pub name: Option<String>,
420    pub version: Option<String>,
421}
422
423#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
424#[serde(rename_all = "camelCase")]
425pub struct InitializeResponse {
426    pub server_info: Option<ServerInfo>,
427    pub user_agent: Option<String>,
428    pub platform_family: Option<String>,
429    pub platform_os: Option<String>,
430    #[serde(flatten)]
431    pub extra: Map<String, Value>,
432}
433
434#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
435#[serde(rename_all = "camelCase")]
436pub struct TurnError {
437    pub message: String,
438    pub additional_details: Option<String>,
439    pub codex_error_info: Option<Value>,
440    #[serde(flatten)]
441    pub extra: Map<String, Value>,
442}
443
444#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
445#[serde(rename_all = "camelCase")]
446pub struct TokenUsageBreakdown {
447    pub cached_input_tokens: u64,
448    pub input_tokens: u64,
449    pub output_tokens: u64,
450    pub reasoning_output_tokens: u64,
451    pub total_tokens: u64,
452}
453
454#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
455#[serde(rename_all = "camelCase")]
456pub struct ThreadTokenUsage {
457    pub last: TokenUsageBreakdown,
458    pub model_context_window: Option<u64>,
459    pub total: TokenUsageBreakdown,
460}
461
462#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
463#[serde(rename_all = "camelCase")]
464pub struct AgentMessageThreadItem {
465    pub id: String,
466    pub text: String,
467    pub phase: Option<MessagePhase>,
468    pub memory_citation: Option<Value>,
469    #[serde(flatten)]
470    pub extra: Map<String, Value>,
471}
472
473/// Lossless representation for thread item variants not modeled directly.
474#[derive(Clone, Debug, PartialEq)]
475pub struct RawThreadItem {
476    pub fields: Map<String, Value>,
477}
478
479impl RawThreadItem {
480    pub fn kind(&self) -> Option<&str> {
481        self.fields.get("type").and_then(Value::as_str)
482    }
483
484    pub fn id(&self) -> Option<&str> {
485        self.fields.get("id").and_then(Value::as_str)
486    }
487}
488
489/// Thread item with a typed assistant-message variant and lossless fallback.
490#[derive(Clone, Debug, PartialEq)]
491pub enum ThreadItem {
492    AgentMessage(AgentMessageThreadItem),
493    Other(RawThreadItem),
494}
495
496impl ThreadItem {
497    pub fn id(&self) -> Option<&str> {
498        match self {
499            Self::AgentMessage(item) => Some(&item.id),
500            Self::Other(item) => item.id(),
501        }
502    }
503
504    pub fn kind(&self) -> Option<&str> {
505        match self {
506            Self::AgentMessage(_) => Some("agentMessage"),
507            Self::Other(item) => item.kind(),
508        }
509    }
510
511    pub fn as_agent_message(&self) -> Option<&AgentMessageThreadItem> {
512        match self {
513            Self::AgentMessage(item) => Some(item),
514            Self::Other(_) => None,
515        }
516    }
517
518    fn into_value(self) -> Value {
519        match self {
520            Self::AgentMessage(item) => {
521                let mut value =
522                    serde_json::to_value(item).expect("serializing ThreadItem cannot fail");
523                value
524                    .as_object_mut()
525                    .expect("AgentMessageThreadItem serializes as an object")
526                    .insert("type".into(), Value::String("agentMessage".into()));
527                value
528            }
529            Self::Other(item) => Value::Object(item.fields),
530        }
531    }
532}
533
534impl Serialize for ThreadItem {
535    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
536    where
537        S: Serializer,
538    {
539        self.clone().into_value().serialize(serializer)
540    }
541}
542
543impl<'de> Deserialize<'de> for ThreadItem {
544    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
545    where
546        D: Deserializer<'de>,
547    {
548        let Value::Object(mut fields) = Value::deserialize(deserializer)? else {
549            return Err(D::Error::custom("thread item must be an object"));
550        };
551        if fields.get("type").and_then(Value::as_str) == Some("agentMessage") {
552            fields.remove("type");
553            let candidate = serde_json::from_value(Value::Object(fields.clone()));
554            if let Ok(item) = candidate {
555                return Ok(Self::AgentMessage(item));
556            }
557            fields.insert("type".into(), Value::String("agentMessage".into()));
558        }
559        Ok(Self::Other(RawThreadItem { fields }))
560    }
561}
562
563#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
564#[serde(rename_all = "camelCase")]
565pub struct Turn {
566    pub completed_at: Option<i64>,
567    pub duration_ms: Option<i64>,
568    pub error: Option<TurnError>,
569    pub id: String,
570    pub items: Vec<ThreadItem>,
571    pub items_view: Option<String>,
572    pub started_at: Option<i64>,
573    pub status: TurnStatus,
574    #[serde(flatten)]
575    pub extra: Map<String, Value>,
576}
577
578#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
579#[serde(rename_all = "camelCase")]
580pub struct ThreadData {
581    pub agent_nickname: Option<String>,
582    pub agent_role: Option<String>,
583    pub cli_version: String,
584    pub created_at: i64,
585    pub cwd: String,
586    pub ephemeral: bool,
587    pub forked_from_id: Option<String>,
588    pub git_info: Option<Value>,
589    pub id: String,
590    pub model_provider: String,
591    pub name: Option<String>,
592    pub parent_thread_id: Option<String>,
593    pub path: Option<String>,
594    pub preview: String,
595    pub recency_at: Option<i64>,
596    pub session_id: String,
597    pub source: Value,
598    pub status: Value,
599    pub thread_source: Option<ThreadSource>,
600    pub turns: Vec<Turn>,
601    pub updated_at: i64,
602    #[serde(flatten)]
603    pub extra: Map<String, Value>,
604}
605
606/// Public alias matching the protocol's `Thread` model without colliding with the SDK handle.
607pub type ThreadRecord = ThreadData;
608
609#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
610#[serde(rename_all = "camelCase")]
611pub struct ThreadListResponse {
612    pub backwards_cursor: Option<String>,
613    pub data: Vec<ThreadData>,
614    pub next_cursor: Option<String>,
615}
616
617#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
618pub struct ThreadReadResponse {
619    pub thread: ThreadData,
620}
621
622macro_rules! empty_response {
623    ($($name:ident),+ $(,)?) => {
624        $(
625            #[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
626            pub struct $name {
627                #[serde(flatten)]
628                pub extra: Map<String, Value>,
629            }
630        )+
631    };
632}
633
634empty_response!(
635    ThreadArchiveResponse,
636    ThreadCompactStartResponse,
637    ThreadSetNameResponse,
638    TurnInterruptResponse,
639);
640
641#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
642#[serde(rename_all = "camelCase")]
643pub struct TurnSteerResponse {
644    pub turn_id: String,
645}
646
647#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
648#[serde(tag = "type")]
649pub enum Account {
650    #[serde(rename = "apiKey")]
651    ApiKey,
652    #[serde(rename = "chatgpt")]
653    Chatgpt {
654        email: Option<String>,
655        #[serde(rename = "planType")]
656        plan_type: PlanType,
657    },
658    #[serde(rename = "amazonBedrock")]
659    AmazonBedrock {
660        #[serde(rename = "credentialSource")]
661        credential_source: Option<String>,
662    },
663}
664
665#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
666#[serde(rename_all = "camelCase")]
667pub struct GetAccountResponse {
668    pub account: Option<Account>,
669    pub requires_openai_auth: bool,
670}
671
672#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
673pub enum CancelLoginAccountStatus {
674    #[serde(rename = "canceled")]
675    Canceled,
676    #[serde(rename = "notFound")]
677    NotFound,
678}
679
680#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
681pub struct CancelLoginAccountResponse {
682    pub status: CancelLoginAccountStatus,
683}
684
685#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
686#[serde(rename_all = "camelCase")]
687pub struct Model {
688    #[serde(default = "default_additional_speed_tiers")]
689    pub additional_speed_tiers: Option<Vec<String>>,
690    pub availability_nux: Option<Value>,
691    pub default_reasoning_effort: ReasoningEffort,
692    pub default_service_tier: Option<String>,
693    pub description: String,
694    pub display_name: String,
695    pub hidden: bool,
696    pub id: String,
697    #[serde(default = "default_input_modalities")]
698    pub input_modalities: Option<Vec<String>>,
699    pub is_default: bool,
700    pub model: String,
701    #[serde(default = "default_service_tiers")]
702    pub service_tiers: Option<Vec<Value>>,
703    pub supported_reasoning_efforts: Vec<ReasoningEffortOption>,
704    #[serde(default = "default_supports_personality")]
705    pub supports_personality: Option<bool>,
706    pub upgrade: Option<String>,
707    pub upgrade_info: Option<Value>,
708    #[serde(flatten)]
709    pub extra: Map<String, Value>,
710}
711
712#[allow(clippy::unnecessary_wraps)]
713fn default_additional_speed_tiers() -> Option<Vec<String>> {
714    Some(Vec::new())
715}
716
717#[allow(clippy::unnecessary_wraps)]
718fn default_input_modalities() -> Option<Vec<String>> {
719    Some(vec!["text".into(), "image".into()])
720}
721
722#[allow(clippy::unnecessary_wraps)]
723fn default_service_tiers() -> Option<Vec<Value>> {
724    Some(Vec::new())
725}
726
727#[allow(clippy::unnecessary_wraps)]
728fn default_supports_personality() -> Option<bool> {
729    Some(false)
730}
731
732#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
733#[serde(rename_all = "camelCase")]
734pub struct ReasoningEffortOption {
735    pub description: String,
736    pub reasoning_effort: ReasoningEffort,
737}
738
739#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
740#[serde(rename_all = "camelCase")]
741pub struct ModelListResponse {
742    pub data: Vec<Model>,
743    pub next_cursor: Option<String>,
744}
745
746#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
747#[serde(rename_all = "camelCase")]
748pub struct AccountLoginCompletedNotification {
749    pub error: Option<String>,
750    pub login_id: Option<String>,
751    pub success: bool,
752}
753
754#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
755#[serde(rename_all = "camelCase")]
756pub struct AgentMessageDeltaNotification {
757    pub delta: String,
758    pub item_id: String,
759    pub thread_id: String,
760    pub turn_id: String,
761}
762
763#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
764#[serde(rename_all = "camelCase")]
765pub struct ItemCompletedNotification {
766    pub completed_at_ms: i64,
767    pub item: ThreadItem,
768    pub thread_id: String,
769    pub turn_id: String,
770}
771
772#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
773#[serde(rename_all = "camelCase")]
774pub struct ItemStartedNotification {
775    pub item: ThreadItem,
776    pub started_at_ms: i64,
777    pub thread_id: String,
778    pub turn_id: String,
779}
780
781#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
782#[serde(rename_all = "camelCase")]
783pub struct TurnCompletedNotification {
784    pub thread_id: String,
785    pub turn: Turn,
786}
787
788#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
789#[serde(rename_all = "camelCase")]
790pub struct TurnStartedNotification {
791    pub thread_id: String,
792    pub turn: Turn,
793}
794
795#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
796#[serde(rename_all = "camelCase")]
797pub struct ThreadTokenUsageUpdatedNotification {
798    pub thread_id: String,
799    pub token_usage: ThreadTokenUsage,
800    pub turn_id: String,
801}
802
803/// Lossless payload for an unmodeled or invalid notification.
804#[derive(Clone, Debug, Default, PartialEq)]
805pub struct RawNotification {
806    pub params: Map<String, Value>,
807}
808
809pub type UnknownNotification = RawNotification;
810
811#[derive(Clone, Debug, PartialEq)]
812pub enum NotificationPayload {
813    AccountLoginCompleted(AccountLoginCompletedNotification),
814    AgentMessageDelta(AgentMessageDeltaNotification),
815    ItemCompleted(ItemCompletedNotification),
816    ItemStarted(ItemStartedNotification),
817    ThreadTokenUsageUpdated(ThreadTokenUsageUpdatedNotification),
818    TurnCompleted(TurnCompletedNotification),
819    TurnStarted(TurnStartedNotification),
820    Known(RawNotification),
821    Unknown(UnknownNotification),
822}
823
824impl NotificationPayload {
825    pub fn params(&self) -> Value {
826        match self {
827            Self::AccountLoginCompleted(value) => serde_json::to_value(value),
828            Self::AgentMessageDelta(value) => serde_json::to_value(value),
829            Self::ItemCompleted(value) => serde_json::to_value(value),
830            Self::ItemStarted(value) => serde_json::to_value(value),
831            Self::ThreadTokenUsageUpdated(value) => serde_json::to_value(value),
832            Self::TurnCompleted(value) => serde_json::to_value(value),
833            Self::TurnStarted(value) => serde_json::to_value(value),
834            Self::Known(value) | Self::Unknown(value) => Ok(Value::Object(value.params.clone())),
835        }
836        .unwrap_or(Value::Null)
837    }
838}
839
840#[derive(Clone, Debug, PartialEq)]
841pub struct Notification {
842    pub method: String,
843    pub payload: NotificationPayload,
844}
845
846impl Notification {
847    pub fn turn_id(&self) -> Option<&str> {
848        match &self.payload {
849            NotificationPayload::AgentMessageDelta(value) => Some(&value.turn_id),
850            NotificationPayload::ItemCompleted(value) => Some(&value.turn_id),
851            NotificationPayload::ItemStarted(value) => Some(&value.turn_id),
852            NotificationPayload::ThreadTokenUsageUpdated(value) => Some(&value.turn_id),
853            NotificationPayload::TurnCompleted(value) => Some(&value.turn.id),
854            NotificationPayload::TurnStarted(value) => Some(&value.turn.id),
855            NotificationPayload::Known(value) | NotificationPayload::Unknown(value) => value
856                .params
857                .get("turnId")
858                .and_then(Value::as_str)
859                .or_else(|| value.params.get("turn")?.get("id")?.as_str()),
860            NotificationPayload::AccountLoginCompleted(_) => None,
861        }
862    }
863
864    pub fn thread_id(&self) -> Option<&str> {
865        match &self.payload {
866            NotificationPayload::AgentMessageDelta(value) => Some(&value.thread_id),
867            NotificationPayload::ItemCompleted(value) => Some(&value.thread_id),
868            NotificationPayload::ItemStarted(value) => Some(&value.thread_id),
869            NotificationPayload::ThreadTokenUsageUpdated(value) => Some(&value.thread_id),
870            NotificationPayload::TurnCompleted(value) => Some(&value.thread_id),
871            NotificationPayload::TurnStarted(value) => Some(&value.thread_id),
872            NotificationPayload::Known(value) | NotificationPayload::Unknown(value) => {
873                value.params.get("threadId").and_then(Value::as_str)
874            }
875            NotificationPayload::AccountLoginCompleted(_) => None,
876        }
877    }
878
879    pub fn login_id(&self) -> Option<&str> {
880        match &self.payload {
881            NotificationPayload::AccountLoginCompleted(value) => value.login_id.as_deref(),
882            NotificationPayload::Known(value) | NotificationPayload::Unknown(value)
883                if self.method == "account/login/completed" =>
884            {
885                value.params.get("loginId").and_then(Value::as_str)
886            }
887            _ => None,
888        }
889    }
890
891    pub(crate) fn from_wire(method: String, params: Value) -> Self {
892        let params = match params {
893            Value::Object(params) => params,
894            _ => Map::new(),
895        };
896        let payload = parse_notification_payload(&method, &params);
897        Self { method, payload }
898    }
899}
900
901fn parse_notification_payload(method: &str, params: &Map<String, Value>) -> NotificationPayload {
902    let value = Value::Object(params.clone());
903    macro_rules! parse {
904        ($type:ty, $variant:ident) => {
905            serde_json::from_value::<$type>(value)
906                .map(NotificationPayload::$variant)
907                .unwrap_or_else(|_| {
908                    NotificationPayload::Unknown(RawNotification {
909                        params: params.clone(),
910                    })
911                })
912        };
913    }
914
915    match method {
916        "account/login/completed" => {
917            parse!(AccountLoginCompletedNotification, AccountLoginCompleted)
918        }
919        "item/agentMessage/delta" => {
920            parse!(AgentMessageDeltaNotification, AgentMessageDelta)
921        }
922        "item/completed" => parse!(ItemCompletedNotification, ItemCompleted),
923        "item/started" => parse!(ItemStartedNotification, ItemStarted),
924        "thread/tokenUsage/updated" => {
925            parse!(ThreadTokenUsageUpdatedNotification, ThreadTokenUsageUpdated)
926        }
927        "turn/completed" => parse!(TurnCompletedNotification, TurnCompleted),
928        "turn/started" => parse!(TurnStartedNotification, TurnStarted),
929        method if KNOWN_NOTIFICATION_METHODS.contains(&method) => {
930            NotificationPayload::Known(RawNotification {
931                params: params.clone(),
932            })
933        }
934        _ => NotificationPayload::Unknown(RawNotification {
935            params: params.clone(),
936        }),
937    }
938}
939
940pub(crate) const KNOWN_NOTIFICATION_METHODS: &[&str] = &[
941    "account/rateLimits/updated",
942    "account/updated",
943    "app/list/updated",
944    "command/exec/outputDelta",
945    "configWarning",
946    "deprecationNotice",
947    "error",
948    "externalAgentConfig/import/completed",
949    "externalAgentConfig/import/progress",
950    "fs/changed",
951    "fuzzyFileSearch/sessionCompleted",
952    "fuzzyFileSearch/sessionUpdated",
953    "guardianWarning",
954    "hook/completed",
955    "hook/started",
956    "item/autoApprovalReview/completed",
957    "item/autoApprovalReview/started",
958    "item/commandExecution/outputDelta",
959    "item/commandExecution/terminalInteraction",
960    "item/fileChange/outputDelta",
961    "item/fileChange/patchUpdated",
962    "item/mcpToolCall/progress",
963    "item/plan/delta",
964    "item/reasoning/summaryPartAdded",
965    "item/reasoning/summaryTextDelta",
966    "item/reasoning/textDelta",
967    "mcpServer/oauthLogin/completed",
968    "mcpServer/startupStatus/updated",
969    "model/rerouted",
970    "model/safetyBuffering/updated",
971    "model/verification",
972    "process/exited",
973    "process/outputDelta",
974    "remoteControl/status/changed",
975    "serverRequest/resolved",
976    "skills/changed",
977    "thread/archived",
978    "thread/closed",
979    "thread/compacted",
980    "thread/deleted",
981    "thread/goal/cleared",
982    "thread/goal/updated",
983    "thread/name/updated",
984    "thread/realtime/closed",
985    "thread/realtime/error",
986    "thread/realtime/itemAdded",
987    "thread/realtime/outputAudio/delta",
988    "thread/realtime/sdp",
989    "thread/realtime/started",
990    "thread/realtime/transcript/delta",
991    "thread/realtime/transcript/done",
992    "thread/settings/updated",
993    "thread/started",
994    "thread/status/changed",
995    "thread/unarchived",
996    "turn/diff/updated",
997    "turn/moderationMetadata",
998    "turn/plan/updated",
999    "warning",
1000    "windows/worldWritableWarning",
1001    "windowsSandbox/setupCompleted",
1002];
1003
1004/// Collected result returned after a turn completes.
1005#[derive(Clone, Debug, PartialEq)]
1006pub struct TurnResult {
1007    pub id: String,
1008    pub status: TurnStatus,
1009    pub error: Option<TurnError>,
1010    pub started_at: Option<i64>,
1011    pub completed_at: Option<i64>,
1012    pub duration_ms: Option<i64>,
1013    pub final_response: Option<String>,
1014    pub items: Vec<ThreadItem>,
1015    pub usage: Option<ThreadTokenUsage>,
1016}
1017
1018impl TurnResult {
1019    pub(crate) fn from_events(
1020        turn_id: &str,
1021        events: impl IntoIterator<Item = Notification>,
1022    ) -> crate::Result<Self> {
1023        let mut completed = None;
1024        let mut items = Vec::new();
1025        let mut usage = None;
1026
1027        for event in events {
1028            match event.payload {
1029                NotificationPayload::ItemCompleted(value) if value.turn_id == turn_id => {
1030                    items.push(value.item);
1031                }
1032                NotificationPayload::ThreadTokenUsageUpdated(value) if value.turn_id == turn_id => {
1033                    usage = Some(value.token_usage);
1034                }
1035                NotificationPayload::TurnCompleted(value) if value.turn.id == turn_id => {
1036                    completed = Some(value.turn);
1037                }
1038                _ => {}
1039            }
1040        }
1041
1042        let turn = completed.ok_or(crate::Error::MissingTurnCompletion)?;
1043        if turn.status == TurnStatus::Failed {
1044            return Err(crate::Error::TurnFailed(turn.error.as_ref().map_or_else(
1045                || "turn failed with status failed".into(),
1046                |error| error.message.clone(),
1047            )));
1048        }
1049
1050        let final_response = items
1051            .iter()
1052            .rev()
1053            .find_map(|item| {
1054                let message = item.as_agent_message()?;
1055                (message.phase == Some(MessagePhase::FinalAnswer)).then(|| message.text.clone())
1056            })
1057            .or_else(|| {
1058                items.iter().rev().find_map(|item| {
1059                    let message = item.as_agent_message()?;
1060                    message.phase.is_none().then(|| message.text.clone())
1061                })
1062            });
1063
1064        Ok(Self {
1065            id: turn.id,
1066            status: turn.status,
1067            error: turn.error,
1068            started_at: turn.started_at,
1069            completed_at: turn.completed_at,
1070            duration_ms: turn.duration_ms,
1071            final_response,
1072            items,
1073            usage,
1074        })
1075    }
1076}
1077
1078/// Retry policy matching `retry_on_overload` in the Python SDK.
1079#[derive(Clone, Copy, Debug, PartialEq)]
1080pub struct RetryPolicy {
1081    pub max_attempts: u32,
1082    pub initial_delay: std::time::Duration,
1083    pub max_delay: std::time::Duration,
1084    pub jitter_ratio: f64,
1085}
1086
1087impl Default for RetryPolicy {
1088    fn default() -> Self {
1089        Self {
1090            max_attempts: 3,
1091            initial_delay: std::time::Duration::from_millis(250),
1092            max_delay: std::time::Duration::from_secs(2),
1093            jitter_ratio: 0.2,
1094        }
1095    }
1096}
1097
1098/// Key/value view useful when consuming unmodeled protocol objects.
1099pub type JsonObject = Map<String, Value>;
1100pub type JsonValue = Value;
1101pub type OrderedJsonObject = BTreeMap<String, Value>;
1102
1103#[cfg(test)]
1104mod tests {
1105    use super::*;
1106
1107    fn turn(status: TurnStatus, error: Option<TurnError>) -> Turn {
1108        Turn {
1109            completed_at: Some(2),
1110            duration_ms: Some(1_000),
1111            error,
1112            id: "turn-1".into(),
1113            items: vec![],
1114            items_view: Some("full".into()),
1115            started_at: Some(1),
1116            status,
1117            extra: Map::new(),
1118        }
1119    }
1120
1121    #[test]
1122    fn preserves_future_string_enum_values() {
1123        let effort: ReasoningEffort = serde_json::from_str("\"future\"").unwrap();
1124        assert_eq!(effort, ReasoningEffort::Unknown("future".into()));
1125        assert_eq!(serde_json::to_string(&effort).unwrap(), "\"future\"");
1126        assert_eq!(effort.to_string(), "future");
1127        assert_eq!(ReasoningEffort::High.as_str(), "high");
1128    }
1129
1130    #[test]
1131    fn input_constructors_and_conversions_preserve_every_public_shape() {
1132        let expected = vec![
1133            InputItem::text("text"),
1134            InputItem::image("https://example.test/image.png"),
1135            InputItem::local_image("/tmp/image.png"),
1136            InputItem::skill("review", "/tmp/SKILL.md"),
1137            InputItem::mention("src", "/tmp/src"),
1138        ];
1139        assert_eq!(
1140            Input::from(vec![
1141                TextInput {
1142                    text: "text".into()
1143                }
1144                .into(),
1145                ImageInput {
1146                    url: "https://example.test/image.png".into()
1147                }
1148                .into(),
1149                LocalImageInput {
1150                    path: "/tmp/image.png".into()
1151                }
1152                .into(),
1153                SkillInput {
1154                    name: "review".into(),
1155                    path: "/tmp/SKILL.md".into()
1156                }
1157                .into(),
1158                MentionInput {
1159                    name: "src".into(),
1160                    path: "/tmp/src".into()
1161                }
1162                .into(),
1163            ]),
1164            Input(expected)
1165        );
1166        assert_eq!(Input::from("borrowed").0, [InputItem::text("borrowed")]);
1167        assert_eq!(
1168            Input::from("owned".to_owned()).0,
1169            [InputItem::text("owned")]
1170        );
1171        assert_eq!(
1172            Input::from(TextInput {
1173                text: "single".into()
1174            })
1175            .0,
1176            [InputItem::text("single")]
1177        );
1178
1179        assert_eq!(Sandbox::ReadOnly.mode(), "read-only");
1180        assert_eq!(Sandbox::WorkspaceWrite.mode(), "workspace-write");
1181        assert_eq!(Sandbox::FullAccess.mode(), "danger-full-access");
1182        assert_eq!(Sandbox::ReadOnly.policy()["type"], "readOnly");
1183        assert_eq!(Sandbox::WorkspaceWrite.policy()["type"], "workspaceWrite");
1184        assert_eq!(Sandbox::FullAccess.policy()["type"], "dangerFullAccess");
1185    }
1186
1187    #[test]
1188    fn thread_item_uses_typed_agent_messages_and_lossless_fallback() {
1189        let item: ThreadItem = serde_json::from_value(json!({
1190            "id": "item-1",
1191            "phase": "final_answer",
1192            "text": "",
1193            "type": "agentMessage",
1194            "newField": 1
1195        }))
1196        .unwrap();
1197        assert_eq!(item.kind(), Some("agentMessage"));
1198        assert_eq!(item.id(), Some("item-1"));
1199        assert_eq!(item.as_agent_message().unwrap().text, "");
1200        assert_eq!(serde_json::to_value(&item).unwrap()["newField"], 1);
1201
1202        let unknown: ThreadItem =
1203            serde_json::from_value(json!({"id": "x", "type": "futureItem", "x": true})).unwrap();
1204        assert_eq!(unknown.kind(), Some("futureItem"));
1205        assert_eq!(unknown.id(), Some("x"));
1206        assert!(unknown.as_agent_message().is_none());
1207        assert_eq!(serde_json::to_value(unknown).unwrap()["x"], true);
1208
1209        assert!(serde_json::from_value::<ThreadItem>(json!("invalid")).is_err());
1210        let malformed: ThreadItem = serde_json::from_value(json!({
1211            "id": 1,
1212            "text": false,
1213            "type": "agentMessage"
1214        }))
1215        .unwrap();
1216        assert_eq!(malformed.kind(), Some("agentMessage"));
1217        assert_eq!(malformed.id(), None);
1218    }
1219
1220    #[test]
1221    fn notification_coercion_is_typed_or_lossless() {
1222        let typed = Notification::from_wire(
1223            "item/agentMessage/delta".into(),
1224            json!({"delta":"x","itemId":"i","threadId":"th","turnId":"tu"}),
1225        );
1226        assert_eq!(typed.turn_id(), Some("tu"));
1227        assert_eq!(typed.thread_id(), Some("th"));
1228        assert!(matches!(
1229            typed.payload,
1230            NotificationPayload::AgentMessageDelta(_)
1231        ));
1232
1233        let invalid =
1234            Notification::from_wire("item/agentMessage/delta".into(), json!({"turnId": "tu"}));
1235        assert!(matches!(invalid.payload, NotificationPayload::Unknown(_)));
1236
1237        let unknown = Notification::from_wire("future/event".into(), json!({"turn": {"id": "tu"}}));
1238        assert_eq!(unknown.turn_id(), Some("tu"));
1239        assert!(matches!(unknown.payload, NotificationPayload::Unknown(_)));
1240    }
1241
1242    #[test]
1243    fn every_typed_notification_exposes_params_and_route_identifiers() {
1244        let cases = [
1245            (
1246                "item/agentMessage/delta",
1247                json!({
1248                    "delta":"x",
1249                    "itemId":"item-1",
1250                    "threadId":"thread-1",
1251                    "turnId":"turn-1"
1252                }),
1253            ),
1254            (
1255                "account/login/completed",
1256                json!({"error":null,"loginId":"login-1","success":true}),
1257            ),
1258            (
1259                "item/started",
1260                json!({
1261                    "item":{"id":"item-1","text":"x","type":"agentMessage"},
1262                    "startedAtMs":1,
1263                    "threadId":"thread-1",
1264                    "turnId":"turn-1"
1265                }),
1266            ),
1267            (
1268                "item/completed",
1269                json!({
1270                    "completedAtMs":2,
1271                    "item":{"id":"item-1","text":"x","type":"agentMessage"},
1272                    "threadId":"thread-1",
1273                    "turnId":"turn-1"
1274                }),
1275            ),
1276            (
1277                "thread/tokenUsage/updated",
1278                json!({
1279                    "threadId":"thread-1",
1280                    "tokenUsage":{
1281                        "last": token_usage_value(),
1282                        "modelContextWindow":200_000,
1283                        "total":token_usage_value()
1284                    },
1285                    "turnId":"turn-1"
1286                }),
1287            ),
1288            (
1289                "turn/started",
1290                json!({"threadId":"thread-1","turn":turn_value("inProgress")}),
1291            ),
1292            (
1293                "turn/completed",
1294                json!({"threadId":"thread-1","turn":turn_value("completed")}),
1295            ),
1296        ];
1297
1298        for (method, params) in cases {
1299            let notification = Notification::from_wire(method.into(), params);
1300            assert!(notification.payload.params().is_object());
1301            if method == "account/login/completed" {
1302                assert_eq!(notification.login_id(), Some("login-1"));
1303                assert_eq!(notification.turn_id(), None);
1304                assert_eq!(notification.thread_id(), None);
1305            } else {
1306                assert_eq!(notification.turn_id(), Some("turn-1"));
1307                assert_eq!(notification.thread_id(), Some("thread-1"));
1308            }
1309        }
1310
1311        let known = Notification::from_wire("warning".into(), json!({"threadId":"thread-2"}));
1312        assert_eq!(known.payload.params()["threadId"], "thread-2");
1313        assert_eq!(known.thread_id(), Some("thread-2"));
1314        assert_eq!(known.login_id(), None);
1315
1316        let raw_login = Notification {
1317            method: "account/login/completed".into(),
1318            payload: NotificationPayload::Unknown(RawNotification {
1319                params: json!({"loginId":"login-2"}).as_object().unwrap().clone(),
1320            }),
1321        };
1322        assert_eq!(raw_login.login_id(), Some("login-2"));
1323
1324        let empty = Notification::from_wire("future/event".into(), Value::Bool(true));
1325        assert_eq!(empty.payload.params(), json!({}));
1326    }
1327
1328    fn token_usage_value() -> Value {
1329        json!({
1330            "cachedInputTokens":1,
1331            "inputTokens":2,
1332            "outputTokens":3,
1333            "reasoningOutputTokens":4,
1334            "totalTokens":10
1335        })
1336    }
1337
1338    fn turn_value(status: &str) -> Value {
1339        json!({
1340            "completedAt":2,
1341            "durationMs":1,
1342            "error":null,
1343            "id":"turn-1",
1344            "items":[],
1345            "itemsView":"full",
1346            "startedAt":1,
1347            "status":status
1348        })
1349    }
1350
1351    #[test]
1352    fn model_optional_fields_match_python_defaults_and_accept_null() {
1353        let base = json!({
1354            "availabilityNux":null,
1355            "defaultReasoningEffort":"medium",
1356            "defaultServiceTier":null,
1357            "description":"model",
1358            "displayName":"Model",
1359            "hidden":false,
1360            "id":"model",
1361            "isDefault":true,
1362            "model":"model",
1363            "supportedReasoningEfforts":[],
1364            "upgrade":null,
1365            "upgradeInfo":null
1366        });
1367        let model: Model = serde_json::from_value(base.clone()).unwrap();
1368        assert_eq!(model.additional_speed_tiers, Some(vec![]));
1369        assert_eq!(
1370            model.input_modalities,
1371            Some(vec!["text".into(), "image".into()])
1372        );
1373        assert_eq!(model.service_tiers, Some(vec![]));
1374        assert_eq!(model.supports_personality, Some(false));
1375
1376        let mut nullable = base;
1377        let object = nullable.as_object_mut().unwrap();
1378        object.insert("additionalSpeedTiers".into(), Value::Null);
1379        object.insert("inputModalities".into(), Value::Null);
1380        object.insert("serviceTiers".into(), Value::Null);
1381        object.insert("supportsPersonality".into(), Value::Null);
1382        let model: Model = serde_json::from_value(nullable).unwrap();
1383        assert_eq!(model.additional_speed_tiers, None);
1384        assert_eq!(model.input_modalities, None);
1385        assert_eq!(model.service_tiers, None);
1386        assert_eq!(model.supports_personality, None);
1387    }
1388
1389    #[test]
1390    fn turn_result_prefers_final_answer_and_preserves_empty_text() {
1391        let events = vec![
1392            Notification::from_wire(
1393                "item/completed".into(),
1394                json!({
1395                    "completedAtMs": 1,
1396                    "item": {"id":"a","phase":null,"text":"fallback","type":"agentMessage"},
1397                    "threadId":"thread-1",
1398                    "turnId":"turn-1"
1399                }),
1400            ),
1401            Notification::from_wire(
1402                "item/completed".into(),
1403                json!({
1404                    "completedAtMs": 2,
1405                    "item": {"id":"b","phase":"final_answer","text":"","type":"agentMessage"},
1406                    "threadId":"thread-1",
1407                    "turnId":"turn-1"
1408                }),
1409            ),
1410            Notification {
1411                method: "turn/completed".into(),
1412                payload: NotificationPayload::TurnCompleted(TurnCompletedNotification {
1413                    thread_id: "thread-1".into(),
1414                    turn: turn(TurnStatus::Completed, None),
1415                }),
1416            },
1417        ];
1418
1419        assert_eq!(
1420            TurnResult::from_events("turn-1", events)
1421                .unwrap()
1422                .final_response,
1423            Some(String::new())
1424        );
1425    }
1426
1427    #[test]
1428    fn failed_and_incomplete_turns_return_errors() {
1429        let failure = Notification {
1430            method: "turn/completed".into(),
1431            payload: NotificationPayload::TurnCompleted(TurnCompletedNotification {
1432                thread_id: "thread-1".into(),
1433                turn: turn(
1434                    TurnStatus::Failed,
1435                    Some(TurnError {
1436                        message: "boom".into(),
1437                        additional_details: None,
1438                        codex_error_info: None,
1439                        extra: Map::new(),
1440                    }),
1441                ),
1442            }),
1443        };
1444        assert!(matches!(
1445            TurnResult::from_events("turn-1", [failure]),
1446            Err(crate::Error::TurnFailed(message)) if message == "boom"
1447        ));
1448        assert!(matches!(
1449            TurnResult::from_events("turn-1", []),
1450            Err(crate::Error::MissingTurnCompletion)
1451        ));
1452
1453        let failure_without_details = Notification {
1454            method: "turn/completed".into(),
1455            payload: NotificationPayload::TurnCompleted(TurnCompletedNotification {
1456                thread_id: "thread-1".into(),
1457                turn: turn(TurnStatus::Failed, None),
1458            }),
1459        };
1460        assert!(matches!(
1461            TurnResult::from_events("turn-1", [failure_without_details]),
1462            Err(crate::Error::TurnFailed(message))
1463                if message == "turn failed with status failed"
1464        ));
1465    }
1466
1467    #[test]
1468    fn retry_policy_defaults_match_python() {
1469        let policy = RetryPolicy::default();
1470        assert_eq!(policy.max_attempts, 3);
1471        assert_eq!(policy.initial_delay, std::time::Duration::from_millis(250));
1472        assert_eq!(policy.max_delay, std::time::Duration::from_secs(2));
1473        assert!((policy.jitter_ratio - 0.2).abs() < f64::EPSILON);
1474    }
1475
1476    #[test]
1477    fn notification_registry_and_revision_match_upstream_snapshot() {
1478        let snapshot: Value =
1479            serde_json::from_str(include_str!("../upstream/python-sdk-contract.json")).unwrap();
1480        assert_eq!(
1481            snapshot["upstream"]["revision"],
1482            crate::UPSTREAM_PYTHON_SDK_COMMIT
1483        );
1484
1485        let mut expected = snapshot["notification_models"]
1486            .as_object()
1487            .unwrap()
1488            .keys()
1489            .map(String::as_str)
1490            .collect::<Vec<_>>();
1491        let mut actual = KNOWN_NOTIFICATION_METHODS.to_vec();
1492        actual.extend([
1493            "account/login/completed",
1494            "item/agentMessage/delta",
1495            "item/completed",
1496            "item/started",
1497            "thread/tokenUsage/updated",
1498            "turn/completed",
1499            "turn/started",
1500        ]);
1501        expected.sort_unstable();
1502        actual.sort_unstable();
1503        assert_eq!(actual, expected);
1504    }
1505}