Skip to main content

maple_sdk/
types.rs

1use chrono::{DateTime, Utc};
2use serde::{Deserialize, Deserializer, Serialize, Serializer};
3use serde_json::Value;
4use uuid::Uuid;
5
6// Public attestation document types (`GET /attestation/{nonce}`). The client's
7// own sessions use Transport V2 and do not fetch this document.
8#[derive(Debug, Clone, Serialize, Deserialize)]
9pub struct AttestationRequest {
10    pub nonce: String,
11}
12
13#[derive(Debug, Clone, Serialize, Deserialize)]
14pub struct AttestationResponse {
15    pub attestation_document: String,
16}
17
18// Token Management Types
19#[derive(Debug, Clone)]
20pub struct TokenPair {
21    pub access_token: String,
22    pub refresh_token: Option<String>,
23}
24
25#[derive(Debug, Clone, Serialize, Deserialize)]
26pub struct RefreshRequest {
27    pub refresh_token: String,
28}
29
30#[derive(Debug, Clone, Serialize, Deserialize)]
31pub struct RefreshResponse {
32    pub access_token: String,
33    pub refresh_token: String,
34}
35
36#[derive(Debug, Clone, Serialize, Deserialize)]
37pub struct CredentialUpdateResponse {
38    #[serde(default)]
39    pub message: String,
40    pub access_token: Option<String>,
41    pub refresh_token: Option<String>,
42}
43
44// Auth Types
45#[derive(Debug, Clone, Serialize, Deserialize)]
46pub struct LoginCredentials {
47    #[serde(skip_serializing_if = "Option::is_none")]
48    pub email: Option<String>,
49    #[serde(skip_serializing_if = "Option::is_none")]
50    pub id: Option<Uuid>,
51    pub password: String,
52    pub client_id: Uuid,
53}
54
55#[derive(Debug, Clone, Serialize, Deserialize)]
56pub struct RegisterCredentials {
57    #[serde(skip_serializing_if = "Option::is_none")]
58    pub email: Option<String>,
59    #[serde(skip_serializing_if = "Option::is_none")]
60    pub name: Option<String>,
61    pub password: String,
62    pub client_id: Uuid,
63}
64
65#[derive(Debug, Clone, Serialize, Deserialize)]
66pub struct LoginResponse {
67    pub id: Uuid,
68    pub email: Option<String>,
69    pub access_token: String,
70    pub refresh_token: String,
71}
72
73#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
74pub struct LogoutRequest {
75    pub refresh_token: String,
76    #[serde(skip_serializing_if = "Option::is_none")]
77    pub push_device_id: Option<Uuid>,
78}
79
80#[derive(Debug, Clone, PartialEq, Eq, Default)]
81pub enum NullableField<T> {
82    #[default]
83    Missing,
84    Null,
85    Value(T),
86}
87
88impl<T> NullableField<T> {
89    pub fn is_missing(&self) -> bool {
90        matches!(self, Self::Missing)
91    }
92
93    pub fn null() -> Self {
94        Self::Null
95    }
96
97    pub fn value(value: T) -> Self {
98        Self::Value(value)
99    }
100}
101
102impl<T> Serialize for NullableField<T>
103where
104    T: Serialize,
105{
106    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
107    where
108        S: Serializer,
109    {
110        match self {
111            Self::Missing | Self::Null => serializer.serialize_none(),
112            Self::Value(value) => value.serialize(serializer),
113        }
114    }
115}
116
117impl<'de, T> Deserialize<'de> for NullableField<T>
118where
119    T: Deserialize<'de>,
120{
121    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
122    where
123        D: Deserializer<'de>,
124    {
125        Ok(match Option::<T>::deserialize(deserializer)? {
126            Some(value) => Self::Value(value),
127            None => Self::Null,
128        })
129    }
130}
131
132// OAuth Types
133#[derive(Debug, Clone, Serialize, Deserialize)]
134pub struct OAuthInitRequest {
135    pub client_id: Uuid,
136    #[serde(skip_serializing_if = "Option::is_none")]
137    pub invite_code: Option<String>,
138}
139
140#[derive(Debug, Clone, Serialize, Deserialize)]
141pub struct GithubAuthResponse {
142    pub auth_url: String,
143    #[serde(alias = "csrf_token")]
144    pub state: String,
145}
146
147#[derive(Debug, Clone, Serialize, Deserialize)]
148pub struct GoogleAuthResponse {
149    pub auth_url: String,
150    #[serde(alias = "csrf_token")]
151    pub state: String,
152}
153
154#[derive(Debug, Clone, Serialize, Deserialize)]
155pub struct AppleAuthResponse {
156    pub auth_url: String,
157    pub state: String,
158}
159
160#[derive(Debug, Clone, Serialize, Deserialize)]
161pub struct OAuthCallbackRequest {
162    pub code: String,
163    pub state: String,
164    pub invite_code: String,
165}
166
167#[derive(Debug, Clone, Serialize, Deserialize)]
168pub struct AppleNativeSignInRequest {
169    pub user_identifier: String,
170    pub identity_token: String,
171    pub client_id: Uuid,
172    #[serde(skip_serializing_if = "Option::is_none")]
173    pub email: Option<String>,
174    #[serde(skip_serializing_if = "Option::is_none")]
175    pub given_name: Option<String>,
176    #[serde(skip_serializing_if = "Option::is_none")]
177    pub family_name: Option<String>,
178    #[serde(skip_serializing_if = "Option::is_none")]
179    pub nonce: Option<String>,
180    #[serde(skip_serializing_if = "Option::is_none")]
181    pub invite_code: Option<String>,
182}
183
184// User Profile Types
185#[derive(Debug, Clone, Serialize, Deserialize)]
186#[serde(rename_all = "lowercase")]
187pub enum LoginMethod {
188    Email,
189    Github,
190    Google,
191    Apple,
192    Guest,
193}
194
195#[derive(Debug, Clone, Serialize, Deserialize)]
196pub struct AppUser {
197    pub id: Uuid,
198    pub name: Option<String>,
199    pub email: Option<String>,
200    pub email_verified: bool,
201    pub login_method: LoginMethod,
202    pub created_at: DateTime<Utc>,
203    pub updated_at: DateTime<Utc>,
204}
205
206#[derive(Debug, Clone, Serialize, Deserialize)]
207pub struct UserResponse {
208    pub user: AppUser,
209}
210
211// Push Notification Types
212#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
213#[serde(rename_all = "lowercase")]
214pub enum PushPlatform {
215    Ios,
216    Android,
217}
218
219impl PushPlatform {
220    pub fn provider(self) -> PushProvider {
221        match self {
222            Self::Ios => PushProvider::Apns,
223            Self::Android => PushProvider::Fcm,
224        }
225    }
226}
227
228#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
229#[serde(rename_all = "lowercase")]
230pub enum PushProvider {
231    Apns,
232    Fcm,
233}
234
235#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
236#[serde(rename_all = "lowercase")]
237pub enum PushEnvironment {
238    Dev,
239    #[default]
240    Prod,
241}
242
243#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
244#[serde(rename_all = "snake_case")]
245pub enum PushKeyAlgorithm {
246    P256EcdhV1,
247}
248
249#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
250pub struct RegisterPushDeviceRequest {
251    pub installation_id: Uuid,
252    pub platform: PushPlatform,
253    pub provider: PushProvider,
254    pub environment: PushEnvironment,
255    pub app_id: String,
256    pub push_token: String,
257    pub notification_public_key: String,
258    pub key_algorithm: PushKeyAlgorithm,
259    #[serde(default)]
260    pub supports_encrypted_preview: bool,
261    #[serde(default)]
262    pub supports_background_processing: bool,
263}
264
265impl RegisterPushDeviceRequest {
266    pub fn new(
267        installation_id: Uuid,
268        platform: PushPlatform,
269        environment: PushEnvironment,
270        app_id: impl Into<String>,
271        push_token: impl Into<String>,
272        notification_public_key: impl Into<String>,
273    ) -> Self {
274        Self {
275            installation_id,
276            platform,
277            provider: platform.provider(),
278            environment,
279            app_id: app_id.into(),
280            push_token: push_token.into(),
281            notification_public_key: notification_public_key.into(),
282            key_algorithm: PushKeyAlgorithm::P256EcdhV1,
283            supports_encrypted_preview: false,
284            supports_background_processing: false,
285        }
286    }
287
288    pub fn supports_encrypted_preview(mut self, supports_encrypted_preview: bool) -> Self {
289        self.supports_encrypted_preview = supports_encrypted_preview;
290        self
291    }
292
293    pub fn supports_background_processing(mut self, supports_background_processing: bool) -> Self {
294        self.supports_background_processing = supports_background_processing;
295        self
296    }
297}
298
299#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
300pub struct PushDevice {
301    pub id: Uuid,
302    pub object: String,
303    pub installation_id: Uuid,
304    pub platform: PushPlatform,
305    pub provider: PushProvider,
306    pub environment: PushEnvironment,
307    pub app_id: String,
308    pub key_algorithm: PushKeyAlgorithm,
309    pub supports_encrypted_preview: bool,
310    pub supports_background_processing: bool,
311    pub last_seen_at: DateTime<Utc>,
312    pub created_at: DateTime<Utc>,
313    pub updated_at: DateTime<Utc>,
314}
315
316#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
317pub struct PushDeviceListResponse {
318    pub object: String,
319    pub data: Vec<PushDevice>,
320}
321
322#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
323pub struct DeletedPushDeviceResponse {
324    pub id: Uuid,
325    pub object: String,
326    pub deleted: bool,
327}
328
329// Private Key Types
330#[derive(Debug, Clone, Serialize, Deserialize)]
331pub struct KeyOptions {
332    #[serde(skip_serializing_if = "Option::is_none")]
333    pub private_key_derivation_path: Option<String>,
334    #[serde(skip_serializing_if = "Option::is_none")]
335    pub seed_phrase_derivation_path: Option<String>,
336}
337
338#[derive(Debug, Clone, Serialize, Deserialize)]
339pub struct PrivateKeyResponse {
340    pub mnemonic: String,
341}
342
343#[derive(Debug, Clone, Serialize, Deserialize)]
344pub struct PrivateKeyBytesResponse {
345    pub private_key: String, // Hex encoded (64 characters for 32 bytes)
346}
347
348// Message Signing Types
349#[derive(Debug, Clone, Serialize, Deserialize)]
350#[serde(rename_all = "lowercase")]
351pub enum SigningAlgorithm {
352    Schnorr,
353    Ecdsa,
354}
355
356#[derive(Debug, Clone, Serialize, Deserialize)]
357pub struct SignMessageRequest {
358    pub message_base64: String,
359    pub algorithm: SigningAlgorithm,
360    #[serde(skip_serializing_if = "Option::is_none")]
361    pub key_options: Option<SigningKeyOptions>,
362}
363
364#[derive(Debug, Clone, Serialize, Deserialize)]
365pub struct SigningKeyOptions {
366    #[serde(skip_serializing_if = "Option::is_none")]
367    pub private_key_derivation_path: Option<String>,
368    #[serde(skip_serializing_if = "Option::is_none")]
369    pub seed_phrase_derivation_path: Option<String>,
370}
371
372#[derive(Debug, Clone, Serialize, Deserialize)]
373pub struct SignMessageResponse {
374    pub signature: String,    // Base64 encoded
375    pub message_hash: String, // Hex encoded
376}
377
378// Public Key Types
379#[derive(Debug, Clone, Serialize, Deserialize)]
380pub struct PublicKeyResponse {
381    pub public_key: String, // Hex encoded
382    pub algorithm: SigningAlgorithm,
383}
384
385// Third Party Token Types
386#[derive(Debug, Clone, Serialize, Deserialize)]
387pub struct ThirdPartyTokenRequest {
388    #[serde(skip_serializing_if = "Option::is_none")]
389    pub audience: Option<String>,
390}
391
392#[derive(Debug, Clone, Serialize, Deserialize)]
393pub struct ThirdPartyTokenResponse {
394    pub token: String,
395}
396
397// Encryption/Decryption Types
398#[derive(Debug, Clone, Serialize, Deserialize)]
399pub struct EncryptDataRequest {
400    pub data: String,
401    #[serde(skip_serializing_if = "Option::is_none")]
402    pub key_options: Option<EncryptionKeyOptions>,
403}
404
405#[derive(Debug, Clone, Serialize, Deserialize)]
406pub struct EncryptionKeyOptions {
407    #[serde(skip_serializing_if = "Option::is_none")]
408    pub private_key_derivation_path: Option<String>,
409    #[serde(skip_serializing_if = "Option::is_none")]
410    pub seed_phrase_derivation_path: Option<String>,
411}
412
413#[derive(Debug, Clone, Serialize, Deserialize)]
414pub struct EncryptDataResponse {
415    pub encrypted_data: String,
416}
417
418#[derive(Debug, Clone, Serialize, Deserialize)]
419pub struct DecryptDataRequest {
420    pub encrypted_data: String,
421    #[serde(skip_serializing_if = "Option::is_none")]
422    pub key_options: Option<EncryptionKeyOptions>,
423}
424
425// The decrypted response is just a string, handled directly
426
427// Account Management Types
428#[derive(Debug, Clone, Serialize, Deserialize)]
429pub struct ChangePasswordRequest {
430    pub current_password: String,
431    pub new_password: String,
432}
433
434#[derive(Debug, Clone, Serialize, Deserialize)]
435pub struct PasswordResetRequest {
436    pub email: String,
437    pub hashed_secret: String,
438    pub client_id: Uuid,
439}
440
441#[derive(Debug, Clone, Serialize, Deserialize)]
442pub struct PasswordResetConfirmRequest {
443    pub email: String,
444    pub alphanumeric_code: String,
445    pub plaintext_secret: String,
446    pub new_password: String,
447    pub client_id: Uuid,
448}
449
450#[derive(Debug, Clone, Serialize, Deserialize)]
451pub struct RequestVerificationCodeRequest {}
452
453#[derive(Debug, Clone, Serialize, Deserialize)]
454pub struct InitiateAccountDeletionRequest {
455    pub hashed_secret: String,
456}
457
458#[derive(Debug, Clone, Serialize, Deserialize)]
459pub struct ConfirmAccountDeletionRequest {
460    pub confirmation_code: String,
461    pub plaintext_secret: String,
462}
463
464/// The emailed reset code and client secret that prove a pending password
465/// reset, scoped to one project's account space.
466#[derive(Clone, Serialize, Deserialize)]
467pub struct PasswordResetProof {
468    pub email: String,
469    pub alphanumeric_code: String,
470    pub plaintext_secret: String,
471    pub client_id: Uuid,
472}
473
474impl std::fmt::Debug for PasswordResetProof {
475    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
476        f.debug_struct("PasswordResetProof")
477            .field("email", &self.email)
478            .field("alphanumeric_code", &"[REDACTED]")
479            .field("plaintext_secret", &"[REDACTED]")
480            .field("client_id", &self.client_id)
481            .finish()
482    }
483}
484
485#[derive(Debug, Clone, Serialize, Deserialize)]
486pub struct PasswordResetOptionsRequest {
487    pub proof: PasswordResetProof,
488}
489
490#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
491pub struct PasswordResetOptions {
492    pub recovery_enrolled: bool,
493    pub destructive_reset_available: bool,
494}
495
496/// How a V2 password reset completes.
497#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
498#[serde(rename_all = "snake_case")]
499pub enum PasswordResetCompletion {
500    /// Opens the enrolled seed with the recovery code and keeps all encrypted
501    /// data. A well-formed but wrong code consumes the reset request.
502    Preserve { recovery_code: String },
503    /// Replaces the seed and loses all encrypted data. The server rejects the
504    /// request unless `acknowledge_data_loss` is true.
505    Destructive { acknowledge_data_loss: bool },
506}
507
508impl std::fmt::Debug for PasswordResetCompletion {
509    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
510        match self {
511            Self::Preserve { .. } => f
512                .debug_struct("Preserve")
513                .field("recovery_code", &"[REDACTED]")
514                .finish(),
515            Self::Destructive {
516                acknowledge_data_loss,
517            } => f
518                .debug_struct("Destructive")
519                .field("acknowledge_data_loss", acknowledge_data_loss)
520                .finish(),
521        }
522    }
523}
524
525#[derive(Clone, Serialize, Deserialize)]
526pub struct CompletePasswordResetRequest {
527    pub proof: PasswordResetProof,
528    pub new_password: String,
529    pub mode: PasswordResetCompletion,
530}
531
532impl std::fmt::Debug for CompletePasswordResetRequest {
533    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
534        f.debug_struct("CompletePasswordResetRequest")
535            .field("proof", &self.proof)
536            .field("new_password", &"[REDACTED]")
537            .field("mode", &self.mode)
538            .finish()
539    }
540}
541
542#[derive(Clone, Serialize, Deserialize)]
543pub struct CompletePasswordResetResponse {
544    pub message: String,
545    pub access_token: String,
546    pub refresh_token: String,
547}
548
549impl std::fmt::Debug for CompletePasswordResetResponse {
550    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
551        f.debug_struct("CompletePasswordResetResponse")
552            .field("message", &self.message)
553            .field("access_token", &"[REDACTED]")
554            .field("refresh_token", &"[REDACTED]")
555            .finish()
556    }
557}
558
559// Recovery Code Types
560
561/// The current password, required as a step-up to enroll, rotate, or disable a
562/// recovery code.
563#[derive(Clone, Serialize, Deserialize)]
564pub struct RecoveryCodePasswordRequest {
565    pub current_password: String,
566}
567
568impl std::fmt::Debug for RecoveryCodePasswordRequest {
569    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
570        f.debug_struct("RecoveryCodePasswordRequest")
571            .field("current_password", &"[REDACTED]")
572            .finish()
573    }
574}
575
576#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
577pub struct RecoveryCodeStatus {
578    pub enrolled: bool,
579    /// When the current code was issued; replacement starts a new issuance.
580    pub issued_at: Option<DateTime<Utc>>,
581    /// Last seed-preserving password reset that used the enrolled code.
582    pub last_used_at: Option<DateTime<Utc>>,
583    pub use_count: i32,
584}
585
586/// A newly enrolled or rotated recovery code. The server returns it only once.
587#[derive(Clone, Serialize, Deserialize)]
588pub struct RecoveryCodeResponse {
589    pub recovery_code: String,
590}
591
592impl std::fmt::Debug for RecoveryCodeResponse {
593    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
594        f.debug_struct("RecoveryCodeResponse")
595            .field("recovery_code", &"[REDACTED]")
596            .finish()
597    }
598}
599
600// API Key Management Types
601#[derive(Debug, Clone, Serialize, Deserialize)]
602pub struct ApiKey {
603    pub name: String,
604    pub created_at: DateTime<Utc>,
605}
606
607#[derive(Debug, Clone, Serialize, Deserialize)]
608pub struct ApiKeyListResponse {
609    pub keys: Vec<ApiKey>,
610}
611
612#[derive(Debug, Clone, Serialize, Deserialize)]
613pub struct ApiKeyCreateRequest {
614    pub name: String,
615}
616
617#[derive(Debug, Clone, Serialize, Deserialize)]
618pub struct ApiKeyCreateResponse {
619    pub key: String, // UUID format with dashes, only returned on creation
620    pub name: String,
621    pub created_at: DateTime<Utc>,
622}
623
624#[derive(Debug, Clone, Serialize, Deserialize)]
625pub struct Conversation {
626    pub id: Uuid,
627    pub object: String,
628    #[serde(skip_serializing_if = "Option::is_none")]
629    pub metadata: Option<Value>,
630    #[serde(skip_serializing_if = "Option::is_none")]
631    pub project_id: Option<Uuid>,
632    pub pinned: bool,
633    pub created_at: i64,
634    pub last_activity_at: i64,
635}
636
637#[derive(Debug, Clone, Serialize, Deserialize, Default)]
638pub struct ConversationCreateRequest {
639    #[serde(skip_serializing_if = "Option::is_none")]
640    pub metadata: Option<Value>,
641    #[serde(skip_serializing_if = "Option::is_none")]
642    pub project_id: Option<Uuid>,
643    #[serde(skip_serializing_if = "Option::is_none")]
644    pub pinned: Option<bool>,
645}
646
647#[derive(Debug, Clone, Serialize, Deserialize, Default)]
648pub struct ConversationUpdateRequest {
649    #[serde(skip_serializing_if = "Option::is_none")]
650    pub metadata: Option<Value>,
651    #[serde(default, skip_serializing_if = "NullableField::is_missing")]
652    pub project_id: NullableField<Uuid>,
653    #[serde(skip_serializing_if = "Option::is_none")]
654    pub pinned: Option<bool>,
655}
656
657impl ConversationUpdateRequest {
658    pub fn is_empty(&self) -> bool {
659        self.metadata.is_none() && self.project_id.is_missing() && self.pinned.is_none()
660    }
661}
662
663#[derive(Debug, Clone, Serialize, Deserialize, Default)]
664pub struct ConversationsListParams {
665    #[serde(skip_serializing_if = "Option::is_none")]
666    pub limit: Option<i64>,
667    #[serde(skip_serializing_if = "Option::is_none")]
668    pub after: Option<Uuid>,
669    #[serde(skip_serializing_if = "Option::is_none")]
670    pub order: Option<String>,
671    #[serde(skip_serializing_if = "Option::is_none")]
672    pub project_id: Option<Uuid>,
673    #[serde(skip_serializing_if = "Option::is_none")]
674    pub unassigned_project: Option<bool>,
675    #[serde(skip_serializing_if = "Option::is_none")]
676    pub pinned: Option<bool>,
677}
678
679#[derive(Debug, Clone, Serialize, Deserialize)]
680pub struct ConversationsListResponse {
681    pub object: String,
682    pub data: Vec<Conversation>,
683    pub first_id: Option<Uuid>,
684    pub last_id: Option<Uuid>,
685    pub has_more: bool,
686}
687
688#[derive(Debug, Clone, Serialize, Deserialize)]
689pub struct ConversationsDeleteResponse {
690    pub object: String,
691    pub deleted: bool,
692}
693
694#[derive(Debug, Clone, Serialize, Deserialize)]
695pub struct BatchDeleteConversationsRequest {
696    pub ids: Vec<String>,
697}
698
699#[derive(Debug, Clone, Serialize, Deserialize)]
700pub struct BatchDeleteItemResult {
701    pub id: String,
702    pub object: String,
703    pub deleted: bool,
704    #[serde(skip_serializing_if = "Option::is_none")]
705    pub error: Option<String>,
706}
707
708#[derive(Debug, Clone, Serialize, Deserialize)]
709pub struct BatchDeleteConversationsResponse {
710    pub object: String,
711    pub data: Vec<BatchDeleteItemResult>,
712}
713
714#[derive(Debug, Clone, Serialize, Deserialize)]
715pub struct BatchUpdateConversationProjectRequest {
716    pub ids: Vec<Uuid>,
717    pub project_id: Option<Uuid>,
718}
719
720#[derive(Debug, Clone, Serialize, Deserialize)]
721pub struct BatchUpdateConversationProjectResponse {
722    pub success: bool,
723}
724
725#[derive(Debug, Clone, Serialize, Deserialize)]
726pub struct ConversationProject {
727    pub id: Uuid,
728    pub object: String,
729    pub name: String,
730    #[serde(skip_serializing_if = "Option::is_none")]
731    pub instructions: Option<String>,
732    pub created_at: i64,
733    pub updated_at: i64,
734}
735
736#[derive(Debug, Clone, Serialize, Deserialize)]
737pub struct ConversationProjectListItem {
738    pub id: Uuid,
739    pub object: String,
740    pub name: String,
741    pub created_at: i64,
742    pub updated_at: i64,
743}
744
745#[derive(Debug, Clone, Serialize, Deserialize)]
746pub struct ConversationProjectsListResponse {
747    pub object: String,
748    pub data: Vec<ConversationProjectListItem>,
749    pub first_id: Option<Uuid>,
750    pub last_id: Option<Uuid>,
751    pub has_more: bool,
752}
753
754#[derive(Debug, Clone, Serialize, Deserialize)]
755pub struct ConversationProjectCreateRequest {
756    pub name: String,
757}
758
759#[derive(Debug, Clone, Serialize, Deserialize, Default)]
760pub struct ConversationProjectUpdateRequest {
761    #[serde(skip_serializing_if = "Option::is_none")]
762    pub name: Option<String>,
763    #[serde(default, skip_serializing_if = "NullableField::is_missing")]
764    pub instructions: NullableField<String>,
765}
766
767impl ConversationProjectUpdateRequest {
768    pub fn is_empty(&self) -> bool {
769        self.name.is_none() && self.instructions.is_missing()
770    }
771}
772
773#[derive(Debug, Clone, Serialize, Deserialize, Default)]
774pub struct ConversationProjectListParams {
775    #[serde(skip_serializing_if = "Option::is_none")]
776    pub limit: Option<i64>,
777    #[serde(skip_serializing_if = "Option::is_none")]
778    pub after: Option<Uuid>,
779    #[serde(skip_serializing_if = "Option::is_none")]
780    pub order: Option<String>,
781}
782
783// AI/OpenAI API Types
784#[derive(Debug, Clone, Serialize, Deserialize)]
785pub struct Model {
786    pub id: String,
787    #[serde(default = "default_model_object")]
788    pub object: String,
789    #[serde(skip_serializing_if = "Option::is_none")]
790    pub created: Option<i64>,
791    #[serde(skip_serializing_if = "Option::is_none")]
792    pub owned_by: Option<String>,
793    /// Most output tokens a request can receive. Input and output share the
794    /// context window, so the effective limit is this less the prompt.
795    #[serde(default, skip_serializing_if = "Option::is_none")]
796    pub max_completion_tokens: Option<u64>,
797    /// How the model exposes reasoning effort; absent for models that never
798    /// reason.
799    #[serde(default, skip_serializing_if = "Option::is_none")]
800    pub reasoning: Option<ModelReasoning>,
801}
802
803/// The reasoning controls a model accepts, as published in the catalog
804/// `reasoning` object (the same shape OpenRouter publishes).
805///
806/// Send one of `supported_efforts` as `reasoning_effort` (Chat Completions)
807/// or `reasoning.effort` (Responses). `none` turns reasoning off and is only
808/// accepted when `mandatory` is false. A model without `supported_efforts`
809/// has no tiers: any effort other than `none` turns reasoning on.
810#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
811pub struct ModelReasoning {
812    /// Reasoning cannot be turned off; `none` is rejected.
813    #[serde(default)]
814    pub mandatory: bool,
815    /// The model reasons when a request names no effort.
816    #[serde(default)]
817    pub default_enabled: bool,
818    /// Accepted efforts, highest first.
819    #[serde(default, skip_serializing_if = "Option::is_none")]
820    pub supported_efforts: Option<Vec<String>>,
821    /// The effort used when a request names none.
822    #[serde(default, skip_serializing_if = "Option::is_none")]
823    pub default_effort: Option<String>,
824}
825
826impl ModelReasoning {
827    /// Whether a request may name this effort for the model.
828    pub fn accepts(&self, effort: &str) -> bool {
829        if effort == "none" {
830            return !self.mandatory;
831        }
832        self.supported_efforts
833            .as_ref()
834            .is_none_or(|efforts| efforts.iter().any(|accepted| accepted == effort))
835    }
836}
837
838/// A catalog entry: model identity plus context and capability metadata.
839#[derive(Debug, Clone, Serialize, Deserialize)]
840pub struct CatalogModel {
841    pub id: String,
842    #[serde(default, skip_serializing_if = "Option::is_none")]
843    pub display_name: Option<String>,
844    #[serde(default, skip_serializing_if = "Option::is_none")]
845    pub short_name: Option<String>,
846    #[serde(default = "default_model_object")]
847    pub object: String,
848    #[serde(skip_serializing_if = "Option::is_none")]
849    pub owned_by: Option<String>,
850    #[serde(default, skip_serializing_if = "Option::is_none")]
851    pub context_window: Option<u64>,
852    #[serde(default, skip_serializing_if = "Option::is_none")]
853    pub max_context_tokens: Option<u64>,
854    #[serde(default, skip_serializing_if = "Option::is_none")]
855    pub capabilities: Option<CatalogCapabilities>,
856    /// Most output tokens a request can receive; see [`Model::max_completion_tokens`].
857    #[serde(default, skip_serializing_if = "Option::is_none")]
858    pub max_completion_tokens: Option<u64>,
859    /// How the model exposes reasoning effort; absent for models that never
860    /// reason.
861    #[serde(default, skip_serializing_if = "Option::is_none")]
862    pub reasoning: Option<ModelReasoning>,
863    /// `false` while the server lists a model it does not serve.
864    #[serde(default, skip_serializing_if = "Option::is_none")]
865    pub enabled: Option<bool>,
866    #[serde(default, skip_serializing_if = "Option::is_none")]
867    pub deprecated: Option<bool>,
868    /// `false` for a model Maple Work does not offer for new tasks; absent on
869    /// servers that predate it.
870    #[serde(default, skip_serializing_if = "Option::is_none")]
871    pub available_in_agent: Option<bool>,
872    /// The id of the [`CatalogGroup`] the model lists under; absent for a
873    /// model without one and on servers that predate groups.
874    #[serde(default, skip_serializing_if = "Option::is_none")]
875    pub group: Option<String>,
876    /// Marks to show beside the model's name, such as `Popular`. The strings
877    /// are stable keys a client may translate.
878    #[serde(default, skip_serializing_if = "Vec::is_empty")]
879    pub badges: Vec<String>,
880}
881
882/// A section of the model picker. Clients translate the heading by `id` and
883/// show `label` for an id they have no translation for.
884#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
885pub struct CatalogGroup {
886    pub id: String,
887    /// The English heading.
888    pub label: String,
889}
890
891/// Capability flags a catalog entry advertises.
892///
893/// Mirrors the server and TypeScript SDK `ModelCapabilities` contract.
894#[derive(Debug, Clone, Default, Serialize, Deserialize)]
895pub struct CatalogCapabilities {
896    #[serde(default)]
897    pub chat: bool,
898    #[serde(default)]
899    pub vision: bool,
900    #[serde(default)]
901    pub reasoning: bool,
902    #[serde(default)]
903    pub tool_use: bool,
904}
905
906/// A catalog alias resolving to a concrete model id.
907#[derive(Debug, Clone, Serialize, Deserialize)]
908pub struct CatalogAlias {
909    pub id: String,
910    #[serde(default, skip_serializing_if = "Option::is_none")]
911    pub label: Option<String>,
912    #[serde(default, skip_serializing_if = "Option::is_none")]
913    pub short_name: Option<String>,
914    #[serde(default, skip_serializing_if = "Option::is_none")]
915    pub target_model: Option<String>,
916    #[serde(default, skip_serializing_if = "Option::is_none")]
917    pub capabilities: Option<CatalogCapabilities>,
918    #[serde(default, skip_serializing_if = "Option::is_none")]
919    pub context_window: Option<u64>,
920    #[serde(default, skip_serializing_if = "Option::is_none")]
921    pub max_completion_tokens: Option<u64>,
922    /// The reasoning controls every model the alias may resolve to accepts.
923    #[serde(default, skip_serializing_if = "Option::is_none")]
924    pub reasoning: Option<ModelReasoning>,
925}
926
927/// Default alias assignments from the catalog.
928#[derive(Debug, Clone, Default, Serialize, Deserialize)]
929pub struct CatalogDefaults {
930    #[serde(default, skip_serializing_if = "Option::is_none")]
931    pub quick: Option<String>,
932    #[serde(default, skip_serializing_if = "Option::is_none")]
933    pub powerful: Option<String>,
934    /// The concrete model Maple Work suggests for a new task; absent on
935    /// servers that predate it.
936    #[serde(default, skip_serializing_if = "Option::is_none")]
937    pub agent: Option<String>,
938}
939
940/// One voice endpoint the catalog advertises.
941#[derive(Debug, Clone, Serialize, Deserialize)]
942pub struct CatalogAudioEndpoint {
943    #[serde(default)]
944    pub available: bool,
945    pub model: String,
946    #[serde(default, skip_serializing_if = "Option::is_none")]
947    pub display_name: Option<String>,
948}
949
950/// The catalog's voice endpoints.
951#[derive(Debug, Clone, Default, Serialize, Deserialize)]
952pub struct CatalogAudio {
953    #[serde(default, skip_serializing_if = "Option::is_none")]
954    pub transcription: Option<CatalogAudioEndpoint>,
955    #[serde(default, skip_serializing_if = "Option::is_none")]
956    pub speech: Option<CatalogAudioEndpoint>,
957}
958
959/// The full model catalog from `/v1/models/catalog`.
960#[derive(Debug, Clone, Default, Serialize, Deserialize)]
961pub struct ModelCatalogResponse {
962    pub object: String,
963    pub data: Vec<CatalogModel>,
964    /// The picker's sections in display order; empty on servers that predate
965    /// groups.
966    #[serde(default, skip_serializing_if = "Vec::is_empty")]
967    pub groups: Vec<CatalogGroup>,
968    #[serde(default)]
969    pub aliases: Vec<CatalogAlias>,
970    #[serde(default)]
971    pub defaults: CatalogDefaults,
972    #[serde(default, skip_serializing_if = "Option::is_none")]
973    pub audio: Option<CatalogAudio>,
974}
975
976fn default_model_object() -> String {
977    "model".to_string()
978}
979
980#[derive(Debug, Clone, Serialize, Deserialize)]
981pub struct ModelsResponse {
982    pub object: String,
983    pub data: Vec<Model>,
984}
985
986// Tool Calling Types
987#[derive(Debug, Clone, Serialize, Deserialize)]
988pub struct Tool {
989    #[serde(rename = "type")]
990    pub tool_type: String,
991    pub function: Function,
992}
993
994#[derive(Debug, Clone, Serialize, Deserialize)]
995pub struct Function {
996    pub name: String,
997    #[serde(skip_serializing_if = "Option::is_none")]
998    pub description: Option<String>,
999    pub parameters: Value,
1000}
1001
1002#[derive(Debug, Clone, Serialize, Deserialize)]
1003pub struct ToolCall {
1004    pub id: String,
1005    #[serde(rename = "type")]
1006    pub tool_type: String,
1007    pub function: FunctionCall,
1008    #[serde(skip_serializing_if = "Option::is_none")]
1009    pub index: Option<i32>,
1010}
1011
1012#[derive(Debug, Clone, Serialize, Deserialize)]
1013pub struct FunctionCall {
1014    pub name: String,
1015    pub arguments: String,
1016}
1017
1018#[derive(Debug, Clone, Serialize, Deserialize)]
1019pub struct ChatMessage {
1020    pub role: String,
1021    #[serde(default)]
1022    pub content: Value, // Now accepts both string and array formats
1023    #[serde(skip_serializing_if = "Option::is_none")]
1024    pub tool_calls: Option<Vec<ToolCall>>,
1025    /// The model's reasoning. Maple returns it in this field on every route;
1026    /// replaying it on an assistant message is accepted by every model.
1027    #[serde(default, skip_serializing_if = "Option::is_none")]
1028    pub reasoning: Option<String>,
1029    /// The older spelling some OpenAI-compatible servers use. Maple never sends
1030    /// it; it stays readable and replayable for other servers and history
1031    /// recorded before `reasoning` existed.
1032    #[serde(skip_serializing_if = "Option::is_none")]
1033    pub reasoning_content: Option<String>,
1034}
1035
1036impl ChatMessage {
1037    /// The reasoning text, from whichever field is populated.
1038    pub fn reasoning_text(&self) -> Option<&str> {
1039        self.reasoning
1040            .as_deref()
1041            .or(self.reasoning_content.as_deref())
1042    }
1043}
1044
1045#[derive(Debug, Clone, Serialize, Deserialize)]
1046pub struct ChatCompletionRequest {
1047    pub model: String,
1048    pub messages: Vec<ChatMessage>,
1049    /// One of the model's catalog `reasoning.supported_efforts`, or `none`
1050    /// where reasoning is not mandatory. An unsupported value on an explicit
1051    /// model is rejected with OpenAI's `unsupported_value` error.
1052    #[serde(skip_serializing_if = "Option::is_none")]
1053    pub reasoning_effort: Option<String>,
1054    #[serde(skip_serializing_if = "Option::is_none")]
1055    pub temperature: Option<f32>,
1056    #[serde(skip_serializing_if = "Option::is_none")]
1057    pub max_tokens: Option<i32>,
1058    #[serde(skip_serializing_if = "Option::is_none")]
1059    pub stream: Option<bool>,
1060    #[serde(skip_serializing_if = "Option::is_none")]
1061    pub stream_options: Option<StreamOptions>,
1062    #[serde(skip_serializing_if = "Option::is_none")]
1063    pub tools: Option<Vec<Tool>>,
1064    #[serde(skip_serializing_if = "Option::is_none")]
1065    pub tool_choice: Option<Value>,
1066}
1067
1068#[derive(Debug, Clone, Serialize, Deserialize)]
1069pub struct StreamOptions {
1070    pub include_usage: bool,
1071}
1072
1073#[derive(Debug, Clone, Serialize, Deserialize)]
1074pub struct ChatCompletionResponse {
1075    pub id: String,
1076    pub object: String,
1077    pub created: i64,
1078    pub model: String,
1079    pub choices: Vec<ChatChoice>,
1080    #[serde(skip_serializing_if = "Option::is_none")]
1081    pub usage: Option<Usage>,
1082}
1083
1084#[derive(Debug, Clone, Serialize, Deserialize)]
1085pub struct ChatChoice {
1086    pub index: i32,
1087    pub message: ChatMessage,
1088    pub finish_reason: Option<String>,
1089}
1090
1091#[derive(Debug, Clone, Serialize, Deserialize)]
1092pub struct Usage {
1093    pub prompt_tokens: i32,
1094    pub completion_tokens: i32,
1095    pub total_tokens: i32,
1096}
1097
1098// Streaming types - transparent Value wrapper for full passthrough of any backend JSON.
1099// This avoids deserialization failures when LLMs send null fields in streaming tool_call
1100// deltas or introduce new fields the SDK doesn't know about yet.
1101#[derive(Debug, Clone, Serialize, Deserialize)]
1102#[serde(transparent)]
1103pub struct ChatCompletionChunk(pub Value);
1104
1105// Embeddings Types
1106#[derive(Debug, Clone, Serialize, Deserialize)]
1107pub struct EmbeddingRequest {
1108    pub input: EmbeddingInput,
1109    #[serde(default = "default_embedding_model")]
1110    pub model: String,
1111    #[serde(skip_serializing_if = "Option::is_none")]
1112    pub encoding_format: Option<String>,
1113    #[serde(skip_serializing_if = "Option::is_none")]
1114    pub dimensions: Option<i32>,
1115    #[serde(skip_serializing_if = "Option::is_none")]
1116    pub user: Option<String>,
1117}
1118
1119fn default_embedding_model() -> String {
1120    "nomic-embed-text".to_string()
1121}
1122
1123#[derive(Debug, Clone, Serialize, Deserialize)]
1124#[serde(untagged)]
1125pub enum EmbeddingInput {
1126    Single(String),
1127    Multiple(Vec<String>),
1128}
1129
1130impl From<String> for EmbeddingInput {
1131    fn from(s: String) -> Self {
1132        EmbeddingInput::Single(s)
1133    }
1134}
1135
1136impl From<&str> for EmbeddingInput {
1137    fn from(s: &str) -> Self {
1138        EmbeddingInput::Single(s.to_string())
1139    }
1140}
1141
1142impl From<Vec<String>> for EmbeddingInput {
1143    fn from(v: Vec<String>) -> Self {
1144        EmbeddingInput::Multiple(v)
1145    }
1146}
1147
1148#[derive(Debug, Clone, Serialize, Deserialize)]
1149pub struct EmbeddingResponse {
1150    pub object: String,
1151    pub data: Vec<EmbeddingData>,
1152    pub model: String,
1153    pub usage: EmbeddingUsage,
1154}
1155
1156/// An embedding vector in the representation requested by `encoding_format`.
1157#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1158#[serde(untagged)]
1159pub enum EmbeddingVector {
1160    Float(Vec<f64>),
1161    Base64(String),
1162}
1163
1164impl EmbeddingVector {
1165    pub fn as_floats(&self) -> Option<&[f64]> {
1166        match self {
1167            Self::Float(values) => Some(values),
1168            Self::Base64(_) => None,
1169        }
1170    }
1171
1172    pub fn as_base64(&self) -> Option<&str> {
1173        match self {
1174            Self::Float(_) => None,
1175            Self::Base64(value) => Some(value),
1176        }
1177    }
1178}
1179
1180#[derive(Debug, Clone, Serialize, Deserialize)]
1181pub struct EmbeddingData {
1182    pub object: String,
1183    pub index: i32,
1184    pub embedding: EmbeddingVector,
1185}
1186
1187#[derive(Debug, Clone, Serialize, Deserialize)]
1188pub struct EmbeddingUsage {
1189    pub prompt_tokens: i32,
1190    pub total_tokens: i32,
1191}
1192
1193// Web API Types
1194
1195#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
1196#[serde(rename_all = "snake_case")]
1197pub enum WebSearchWorkflow {
1198    #[default]
1199    Search,
1200    Images,
1201    Videos,
1202    News,
1203    Podcasts,
1204}
1205
1206#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1207#[serde(rename_all = "snake_case")]
1208pub enum WebSearchTimeRelative {
1209    Day,
1210    Week,
1211    Month,
1212}
1213
1214#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1215pub struct WebSearchLens {
1216    #[serde(skip_serializing_if = "Option::is_none")]
1217    pub sites_included: Option<Vec<String>>,
1218    #[serde(skip_serializing_if = "Option::is_none")]
1219    pub sites_excluded: Option<Vec<String>>,
1220    #[serde(skip_serializing_if = "Option::is_none")]
1221    pub keywords_included: Option<Vec<String>>,
1222    #[serde(skip_serializing_if = "Option::is_none")]
1223    pub keywords_excluded: Option<Vec<String>>,
1224    #[serde(skip_serializing_if = "Option::is_none")]
1225    pub file_type: Option<String>,
1226    #[serde(skip_serializing_if = "Option::is_none")]
1227    pub time_after: Option<String>,
1228    #[serde(skip_serializing_if = "Option::is_none")]
1229    pub time_before: Option<String>,
1230    #[serde(skip_serializing_if = "Option::is_none")]
1231    pub time_relative: Option<WebSearchTimeRelative>,
1232    #[serde(skip_serializing_if = "Option::is_none")]
1233    pub search_region: Option<String>,
1234}
1235
1236#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1237pub struct WebSearchFilters {
1238    #[serde(skip_serializing_if = "Option::is_none")]
1239    pub region: Option<String>,
1240    #[serde(skip_serializing_if = "Option::is_none")]
1241    pub after: Option<String>,
1242    #[serde(skip_serializing_if = "Option::is_none")]
1243    pub before: Option<String>,
1244}
1245
1246#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1247pub struct WebSearchRequest {
1248    pub query: String,
1249    /// Search result class. The server defaults to [`WebSearchWorkflow::Search`].
1250    #[serde(skip_serializing_if = "Option::is_none")]
1251    pub workflow: Option<WebSearchWorkflow>,
1252    /// One-based result page, from 1 through 10.
1253    #[serde(skip_serializing_if = "Option::is_none")]
1254    pub page: Option<u8>,
1255    /// Maximum results to return, from 1 through 50. The server defaults to 10.
1256    #[serde(skip_serializing_if = "Option::is_none")]
1257    pub limit: Option<u16>,
1258    /// Whether to omit potentially unsafe content. The server defaults to true.
1259    #[serde(skip_serializing_if = "Option::is_none")]
1260    pub safe_search: Option<bool>,
1261    /// Search collection timeout in seconds, from 0.5 through 4.
1262    #[serde(skip_serializing_if = "Option::is_none")]
1263    pub timeout: Option<f64>,
1264    #[serde(skip_serializing_if = "Option::is_none")]
1265    pub lens_id: Option<String>,
1266    #[serde(skip_serializing_if = "Option::is_none")]
1267    pub lens: Option<WebSearchLens>,
1268    #[serde(skip_serializing_if = "Option::is_none")]
1269    pub filters: Option<WebSearchFilters>,
1270}
1271
1272impl WebSearchRequest {
1273    pub fn new(query: impl Into<String>) -> Self {
1274        Self {
1275            query: query.into(),
1276            workflow: None,
1277            page: None,
1278            limit: None,
1279            safe_search: None,
1280            timeout: None,
1281            lens_id: None,
1282            lens: None,
1283            filters: None,
1284        }
1285    }
1286}
1287
1288#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1289pub struct WebSearchResult {
1290    pub category: String,
1291    pub url: String,
1292    pub title: String,
1293    #[serde(default, skip_serializing_if = "Option::is_none")]
1294    pub snippet: Option<String>,
1295    #[serde(default, skip_serializing_if = "Option::is_none")]
1296    pub published_at: Option<String>,
1297}
1298
1299#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1300pub struct WebSearchResponse {
1301    #[serde(default, skip_serializing_if = "Option::is_none")]
1302    pub trace_id: Option<String>,
1303    pub results: Vec<WebSearchResult>,
1304}
1305
1306#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1307pub struct WebExtractRequest {
1308    /// Public HTTPS URLs to extract, from 1 through 10 entries.
1309    pub urls: Vec<String>,
1310    /// Bulk extraction timeout in seconds, from 0.5 through 10.
1311    #[serde(skip_serializing_if = "Option::is_none")]
1312    pub timeout: Option<f64>,
1313}
1314
1315impl WebExtractRequest {
1316    pub fn new(urls: impl IntoIterator<Item = impl Into<String>>) -> Self {
1317        Self {
1318            urls: urls.into_iter().map(Into::into).collect(),
1319            timeout: None,
1320        }
1321    }
1322}
1323
1324#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1325pub struct WebExtractPageError {
1326    pub code: String,
1327    pub message: String,
1328}
1329
1330#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1331pub struct WebExtractPage {
1332    pub url: String,
1333    #[serde(default, skip_serializing_if = "Option::is_none")]
1334    pub markdown: Option<String>,
1335    #[serde(default, skip_serializing_if = "Option::is_none")]
1336    pub error: Option<WebExtractPageError>,
1337}
1338
1339#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1340pub struct WebExtractResponse {
1341    #[serde(default, skip_serializing_if = "Option::is_none")]
1342    pub trace_id: Option<String>,
1343    pub pages: Vec<WebExtractPage>,
1344}
1345
1346// Agent API Types
1347
1348#[derive(Debug, Clone, Serialize, Deserialize)]
1349pub struct AgentChatRequest {
1350    pub input: String,
1351}
1352
1353#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
1354pub struct InitMainAgentRequest {
1355    #[serde(skip_serializing_if = "Option::is_none")]
1356    pub timezone: Option<String>,
1357    #[serde(skip_serializing_if = "Option::is_none")]
1358    pub locale: Option<String>,
1359}
1360
1361#[derive(Debug, Clone, Serialize, Deserialize)]
1362pub struct InitMainAgentResponse {
1363    pub id: Uuid,
1364    pub object: String,
1365    pub kind: String,
1366    pub conversation_id: Uuid,
1367    pub display_name: String,
1368    pub created_at: i64,
1369    pub updated_at: i64,
1370    pub messages: Vec<ConversationItem>,
1371}
1372
1373#[derive(Debug, Clone, Serialize, Deserialize)]
1374pub struct CreateSubagentRequest {
1375    #[serde(skip_serializing_if = "Option::is_none")]
1376    pub display_name: Option<String>,
1377    pub purpose: String,
1378}
1379
1380#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1381pub struct SetMessageReactionRequest {
1382    pub emoji: String,
1383}
1384
1385#[derive(Debug, Clone, Serialize, Deserialize)]
1386pub struct MainAgentResponse {
1387    pub id: Uuid,
1388    pub object: String,
1389    pub kind: String,
1390    pub conversation_id: Uuid,
1391    pub display_name: String,
1392    pub created_at: i64,
1393    pub updated_at: i64,
1394}
1395
1396#[derive(Debug, Clone, Serialize, Deserialize)]
1397pub struct SubagentResponse {
1398    pub id: Uuid,
1399    pub object: String,
1400    pub kind: String,
1401    pub conversation_id: Uuid,
1402    pub display_name: String,
1403    pub purpose: String,
1404    pub created_by: String,
1405    pub created_at: i64,
1406    pub updated_at: i64,
1407}
1408
1409#[derive(Debug, Clone, Serialize, Deserialize, Default)]
1410pub struct AgentItemsListParams {
1411    #[serde(skip_serializing_if = "Option::is_none")]
1412    pub limit: Option<i64>,
1413    #[serde(skip_serializing_if = "Option::is_none")]
1414    pub after: Option<Uuid>,
1415    #[serde(skip_serializing_if = "Option::is_none")]
1416    pub order: Option<String>,
1417    #[serde(skip_serializing_if = "Option::is_none")]
1418    pub include: Option<Vec<String>>,
1419}
1420
1421#[derive(Debug, Clone, Serialize, Deserialize, Default)]
1422pub struct ListSubagentsParams {
1423    #[serde(skip_serializing_if = "Option::is_none")]
1424    pub limit: Option<i64>,
1425    #[serde(skip_serializing_if = "Option::is_none")]
1426    pub after: Option<Uuid>,
1427    #[serde(skip_serializing_if = "Option::is_none")]
1428    pub order: Option<String>,
1429    #[serde(skip_serializing_if = "Option::is_none")]
1430    pub created_by: Option<String>,
1431}
1432
1433#[derive(Debug, Clone, Serialize, Deserialize)]
1434#[serde(tag = "type")]
1435pub enum ConversationContent {
1436    #[serde(rename = "text")]
1437    Text { text: String },
1438    #[serde(rename = "input_text")]
1439    InputText { text: String },
1440    #[serde(rename = "output_text")]
1441    OutputText { text: String },
1442    #[serde(rename = "input_image")]
1443    InputImage { image_url: String },
1444    #[serde(rename = "input_file")]
1445    InputFile { filename: String },
1446}
1447
1448#[derive(Debug, Clone, Serialize, Deserialize)]
1449#[serde(tag = "type")]
1450pub enum ReasoningContentItem {
1451    #[serde(rename = "text")]
1452    Text { text: String },
1453}
1454
1455#[derive(Debug, Clone, Serialize, Deserialize)]
1456#[serde(tag = "type")]
1457pub enum ConversationItem {
1458    #[serde(rename = "message")]
1459    Message {
1460        id: Uuid,
1461        #[serde(skip_serializing_if = "Option::is_none")]
1462        status: Option<String>,
1463        role: String,
1464        content: Vec<ConversationContent>,
1465        #[serde(skip_serializing_if = "Option::is_none")]
1466        reaction: Option<String>,
1467        #[serde(skip_serializing_if = "Option::is_none")]
1468        created_at: Option<i64>,
1469    },
1470    #[serde(rename = "function_call")]
1471    FunctionToolCall {
1472        id: Uuid,
1473        call_id: Uuid,
1474        name: String,
1475        arguments: String,
1476        #[serde(skip_serializing_if = "Option::is_none")]
1477        status: Option<String>,
1478        #[serde(skip_serializing_if = "Option::is_none")]
1479        created_at: Option<i64>,
1480    },
1481    #[serde(rename = "function_call_output")]
1482    FunctionToolCallOutput {
1483        id: Uuid,
1484        call_id: Uuid,
1485        output: String,
1486        #[serde(skip_serializing_if = "Option::is_none")]
1487        status: Option<String>,
1488        #[serde(skip_serializing_if = "Option::is_none")]
1489        created_at: Option<i64>,
1490    },
1491    #[serde(rename = "reasoning")]
1492    Reasoning {
1493        id: Uuid,
1494        content: Vec<ReasoningContentItem>,
1495        #[serde(skip_serializing_if = "Option::is_none")]
1496        status: Option<String>,
1497        #[serde(skip_serializing_if = "Option::is_none")]
1498        created_at: Option<i64>,
1499    },
1500}
1501
1502#[derive(Debug, Clone, Serialize, Deserialize)]
1503pub struct AgentItemsListResponse {
1504    pub object: String,
1505    pub data: Vec<ConversationItem>,
1506    pub first_id: Option<Uuid>,
1507    pub last_id: Option<Uuid>,
1508    pub has_more: bool,
1509}
1510
1511pub type ConversationItemsResponse = AgentItemsListResponse;
1512
1513#[derive(Debug, Clone, Serialize, Deserialize)]
1514pub struct SubagentListResponse {
1515    pub object: String,
1516    pub data: Vec<SubagentResponse>,
1517    pub first_id: Option<Uuid>,
1518    pub last_id: Option<Uuid>,
1519    pub has_more: bool,
1520}
1521
1522#[derive(Debug, Clone, Serialize, Deserialize)]
1523pub struct DeletedObjectResponse {
1524    pub id: Uuid,
1525    pub object: String,
1526    pub deleted: bool,
1527}
1528
1529// Agent SSE event types
1530#[derive(Debug, Clone, Serialize, Deserialize)]
1531pub struct AgentMessageEvent {
1532    pub message_id: Uuid,
1533    pub message: String,
1534}
1535
1536#[derive(Debug, Clone, Serialize, Deserialize)]
1537pub struct AgentReactionEvent {
1538    pub item_id: Uuid,
1539    pub emoji: String,
1540}
1541
1542#[derive(Debug, Clone, Serialize, Deserialize)]
1543pub struct AgentTypingEvent {}
1544
1545#[derive(Debug, Clone, Serialize, Deserialize)]
1546pub struct AgentDoneEvent {}
1547
1548#[derive(Debug, Clone, Serialize, Deserialize)]
1549pub struct AgentErrorEvent {
1550    pub error: String,
1551}
1552
1553/// Parsed SSE event from the agent chat stream
1554#[derive(Debug, Clone)]
1555pub enum AgentSseEvent {
1556    Message(AgentMessageEvent),
1557    Reaction(AgentReactionEvent),
1558    Typing(AgentTypingEvent),
1559    Done(AgentDoneEvent),
1560    Error(AgentErrorEvent),
1561}
1562
1563#[cfg(test)]
1564mod tests {
1565    #[test]
1566    fn catalog_preserves_optional_model_and_alias_labels() {
1567        let catalog: super::ModelCatalogResponse = serde_json::from_value(serde_json::json!({
1568            "object": "list",
1569            "data": [
1570                {"id": "model-a", "short_name": "Compact", "display_name": "Full name"},
1571                {"id": "legacy-model"}
1572            ],
1573            "aliases": [
1574                {"id": "auto:quick", "short_name": "Quick", "label": "Automatic quick"},
1575                {"id": "legacy-alias"}
1576            ]
1577        }))
1578        .unwrap();
1579        assert_eq!(catalog.data[0].short_name.as_deref(), Some("Compact"));
1580        assert_eq!(catalog.data[0].display_name.as_deref(), Some("Full name"));
1581        assert_eq!(catalog.aliases[0].short_name.as_deref(), Some("Quick"));
1582        assert_eq!(catalog.aliases[0].label.as_deref(), Some("Automatic quick"));
1583        assert!(catalog.data[1].short_name.is_none());
1584        assert!(catalog.data[1].display_name.is_none());
1585        assert!(catalog.aliases[1].short_name.is_none());
1586        assert!(catalog.aliases[1].label.is_none());
1587        let serialized = serde_json::to_value(catalog).unwrap();
1588        assert_eq!(serialized["data"][0]["short_name"], "Compact");
1589        assert!(serialized["data"][1].get("short_name").is_none());
1590        assert!(serialized["aliases"][1].get("label").is_none());
1591    }
1592
1593    use super::*;
1594    use serde_json::json;
1595
1596    fn reset_proof() -> PasswordResetProof {
1597        PasswordResetProof {
1598            email: "user@example.test".to_string(),
1599            alphanumeric_code: "ABCD1234".to_string(),
1600            plaintext_secret: "client-reset-secret".to_string(),
1601            client_id: Uuid::nil(),
1602        }
1603    }
1604
1605    #[test]
1606    fn password_reset_completion_matches_the_server_wire_shape() {
1607        let proof = json!({
1608            "email": "user@example.test",
1609            "alphanumeric_code": "ABCD1234",
1610            "plaintext_secret": "client-reset-secret",
1611            "client_id": Uuid::nil(),
1612        });
1613        let preserve = CompletePasswordResetRequest {
1614            proof: reset_proof(),
1615            new_password: "new-password".to_string(),
1616            mode: PasswordResetCompletion::Preserve {
1617                recovery_code: "MPLRC1-CODE".to_string(),
1618            },
1619        };
1620        assert_eq!(
1621            serde_json::to_value(&preserve).unwrap(),
1622            json!({
1623                "proof": proof,
1624                "new_password": "new-password",
1625                "mode": {"preserve": {"recovery_code": "MPLRC1-CODE"}},
1626            })
1627        );
1628
1629        let destructive = CompletePasswordResetRequest {
1630            mode: PasswordResetCompletion::Destructive {
1631                acknowledge_data_loss: true,
1632            },
1633            ..preserve
1634        };
1635        assert_eq!(
1636            serde_json::to_value(&destructive).unwrap()["mode"],
1637            json!({"destructive": {"acknowledge_data_loss": true}})
1638        );
1639
1640        assert_eq!(
1641            serde_json::to_value(PasswordResetOptionsRequest {
1642                proof: reset_proof()
1643            })
1644            .unwrap(),
1645            json!({ "proof": proof })
1646        );
1647    }
1648
1649    #[test]
1650    fn recovery_status_accepts_unenrolled_and_enrolled_responses() {
1651        let unenrolled: RecoveryCodeStatus = serde_json::from_value(json!({
1652            "enrolled": false,
1653            "issued_at": null,
1654            "last_used_at": null,
1655            "use_count": 0,
1656        }))
1657        .unwrap();
1658        assert!(!unenrolled.enrolled);
1659        assert!(unenrolled.issued_at.is_none());
1660
1661        let enrolled: RecoveryCodeStatus = serde_json::from_value(json!({
1662            "enrolled": true,
1663            "issued_at": "2026-11-01T12:00:00Z",
1664            "last_used_at": "2026-11-02T08:30:00.123456Z",
1665            "use_count": 1,
1666        }))
1667        .unwrap();
1668        assert!(enrolled.enrolled);
1669        assert!(enrolled.last_used_at.is_some());
1670        assert_eq!(enrolled.use_count, 1);
1671    }
1672
1673    #[test]
1674    fn recovery_secrets_are_redacted_from_debug_output() {
1675        let secrets = [
1676            "MPLRC1-SECRET",
1677            "ABCD1234",
1678            "client-reset-secret",
1679            "new-password",
1680            "current-password",
1681            "reset-access-token",
1682            "reset-refresh-token",
1683        ];
1684        let debug = format!(
1685            "{:?} {:?} {:?} {:?}",
1686            CompletePasswordResetRequest {
1687                proof: reset_proof(),
1688                new_password: "new-password".to_string(),
1689                mode: PasswordResetCompletion::Preserve {
1690                    recovery_code: "MPLRC1-SECRET".to_string(),
1691                },
1692            },
1693            RecoveryCodePasswordRequest {
1694                current_password: "current-password".to_string(),
1695            },
1696            RecoveryCodeResponse {
1697                recovery_code: "MPLRC1-SECRET".to_string(),
1698            },
1699            CompletePasswordResetResponse {
1700                message: "Password reset successful.".to_string(),
1701                access_token: "reset-access-token".to_string(),
1702                refresh_token: "reset-refresh-token".to_string(),
1703            },
1704        );
1705        for secret in secrets {
1706            assert!(!debug.contains(secret), "Debug output leaked {secret}");
1707        }
1708    }
1709
1710    #[test]
1711    fn nullable_field_request_serialization_distinguishes_missing_and_null() {
1712        let conversation_update = ConversationUpdateRequest::default();
1713        assert!(conversation_update.is_empty());
1714        assert_eq!(
1715            serde_json::to_value(&conversation_update).unwrap(),
1716            json!({})
1717        );
1718
1719        let conversation_update = ConversationUpdateRequest {
1720            project_id: NullableField::null(),
1721            ..Default::default()
1722        };
1723        assert!(!conversation_update.is_empty());
1724        assert_eq!(
1725            serde_json::to_value(&conversation_update).unwrap(),
1726            json!({ "project_id": null })
1727        );
1728
1729        let project_update = ConversationProjectUpdateRequest {
1730            instructions: NullableField::null(),
1731            ..Default::default()
1732        };
1733        assert!(!project_update.is_empty());
1734        assert_eq!(
1735            serde_json::to_value(&project_update).unwrap(),
1736            json!({ "instructions": null })
1737        );
1738    }
1739
1740    #[test]
1741    fn batch_update_project_request_serializes_none_as_explicit_null() {
1742        let request = BatchUpdateConversationProjectRequest {
1743            ids: vec![Uuid::parse_str("550e8400-e29b-41d4-a716-446655440000").unwrap()],
1744            project_id: None,
1745        };
1746
1747        assert_eq!(
1748            serde_json::to_value(&request).unwrap(),
1749            json!({
1750                "ids": ["550e8400-e29b-41d4-a716-446655440000"],
1751                "project_id": null
1752            })
1753        );
1754    }
1755
1756    #[test]
1757    fn credential_update_response_tolerates_missing_message() {
1758        let response: CredentialUpdateResponse =
1759            serde_json::from_value(json!({ "access_token": "new-access" })).unwrap();
1760
1761        assert_eq!(response.message, "");
1762        assert_eq!(response.access_token.as_deref(), Some("new-access"));
1763        assert_eq!(response.refresh_token, None);
1764    }
1765
1766    #[test]
1767    fn web_requests_omit_unspecified_options() {
1768        let search = WebSearchRequest::new("maple privacy");
1769        assert_eq!(
1770            serde_json::to_value(search).unwrap(),
1771            json!({ "query": "maple privacy" })
1772        );
1773
1774        let extract = WebExtractRequest::new(["https://example.com/article"]);
1775        assert_eq!(
1776            serde_json::to_value(extract).unwrap(),
1777            json!({ "urls": ["https://example.com/article"] })
1778        );
1779    }
1780
1781    #[test]
1782    fn web_responses_tolerate_absent_optional_fields() {
1783        let search: WebSearchResponse = serde_json::from_value(json!({
1784            "results": [{
1785                "category": "search",
1786                "url": "https://example.com",
1787                "title": "Example"
1788            }]
1789        }))
1790        .unwrap();
1791        assert_eq!(search.trace_id, None);
1792        assert_eq!(search.results[0].snippet, None);
1793        assert_eq!(search.results[0].published_at, None);
1794
1795        let extract: WebExtractResponse = serde_json::from_value(json!({
1796            "pages": [{ "url": "https://example.com" }]
1797        }))
1798        .unwrap();
1799        assert_eq!(extract.trace_id, None);
1800        assert_eq!(extract.pages[0].markdown, None);
1801        assert_eq!(extract.pages[0].error, None);
1802    }
1803
1804    #[test]
1805    fn embedding_response_deserializes_float_vectors() {
1806        let response: EmbeddingResponse = serde_json::from_value(json!({
1807            "object": "list",
1808            "data": [{
1809                "object": "embedding",
1810                "index": 0,
1811                "embedding": [0.1, 0.2, 0.3]
1812            }],
1813            "model": "nomic-embed-text",
1814            "usage": { "prompt_tokens": 4, "total_tokens": 4 }
1815        }))
1816        .unwrap();
1817
1818        assert_eq!(
1819            response.data[0].embedding,
1820            EmbeddingVector::Float(vec![0.1, 0.2, 0.3])
1821        );
1822        assert_eq!(
1823            response.data[0].embedding.as_floats(),
1824            Some([0.1, 0.2, 0.3].as_slice())
1825        );
1826        assert_eq!(response.data[0].embedding.as_base64(), None);
1827        assert_eq!(
1828            serde_json::to_value(&response).unwrap()["data"][0]["embedding"],
1829            json!([0.1, 0.2, 0.3])
1830        );
1831    }
1832
1833    #[test]
1834    fn embedding_response_deserializes_base64_vectors() {
1835        let response: EmbeddingResponse = serde_json::from_value(json!({
1836            "object": "list",
1837            "data": [{
1838                "object": "embedding",
1839                "index": 0,
1840                "embedding": "AQIDBA=="
1841            }],
1842            "model": "nomic-embed-text",
1843            "usage": { "prompt_tokens": 4, "total_tokens": 4 }
1844        }))
1845        .unwrap();
1846
1847        assert_eq!(
1848            response.data[0].embedding,
1849            EmbeddingVector::Base64("AQIDBA==".to_string())
1850        );
1851        assert_eq!(response.data[0].embedding.as_floats(), None);
1852        assert_eq!(response.data[0].embedding.as_base64(), Some("AQIDBA=="));
1853        assert_eq!(
1854            serde_json::to_value(&response).unwrap()["data"][0]["embedding"],
1855            json!("AQIDBA==")
1856        );
1857    }
1858
1859    #[test]
1860    fn embedding_response_rejects_unknown_vector_representations() {
1861        let response = serde_json::from_value::<EmbeddingResponse>(json!({
1862            "object": "list",
1863            "data": [{
1864                "object": "embedding",
1865                "index": 0,
1866                "embedding": { "values": [0.1, 0.2, 0.3] }
1867            }],
1868            "model": "nomic-embed-text",
1869            "usage": { "prompt_tokens": 4, "total_tokens": 4 }
1870        }));
1871
1872        assert!(response.is_err());
1873    }
1874}