letta 0.1.2

A robust Rust client for the Letta REST API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
//! HTTP client and configuration for the Letta API.

use crate::auth::AuthConfig;
use crate::environment::LettaEnvironment;
use crate::error::{LettaError, LettaResult};
use crate::retry::{retry_with_config, RetryConfig};
use reqwest::header::HeaderMap;
use std::time::Duration;
use url::Url;

/// Configuration for the Letta client.
#[derive(Debug, Clone)]
pub struct ClientConfig {
    /// Base URL for the Letta API.
    pub base_url: Url,
    /// Authentication configuration.
    pub auth: AuthConfig,
    /// Request timeout duration.
    pub timeout: Duration,
    /// Additional headers to include with all requests.
    pub headers: HeaderMap,
}

impl ClientConfig {
    /// Create a new client configuration.
    pub fn new(base_url: impl AsRef<str>) -> LettaResult<Self> {
        let base_url = Url::parse(base_url.as_ref())?;
        Ok(Self {
            base_url,
            auth: AuthConfig::default(),
            timeout: Duration::from_secs(30),
            headers: HeaderMap::new(),
        })
    }

    /// Set the authentication configuration.
    pub fn auth(mut self, auth: AuthConfig) -> Self {
        self.auth = auth;
        self
    }

    /// Set the request timeout.
    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.timeout = timeout;
        self
    }

    /// Set additional headers to include with all requests.
    pub fn headers(mut self, headers: HeaderMap) -> Self {
        self.headers = headers;
        self
    }

    /// Add a single header to include with all requests.
    pub fn header(mut self, key: impl AsRef<str>, value: impl AsRef<str>) -> LettaResult<Self> {
        let key = key.as_ref();
        let value = value.as_ref();

        let header_name = reqwest::header::HeaderName::from_bytes(key.as_bytes())
            .map_err(|_| LettaError::validation(format!("Invalid header name: {}", key)))?;
        let header_value = reqwest::header::HeaderValue::from_str(value).map_err(|_| {
            LettaError::validation(format!("Invalid header value for {}: {}", key, value))
        })?;

        self.headers.insert(header_name, header_value);
        Ok(self)
    }

    /// Set the X-Project header for all requests.
    ///
    /// This associates all operations with a specific project context.
    pub fn project(self, project_id: impl AsRef<str>) -> LettaResult<Self> {
        self.header("X-Project", project_id)
    }

    /// Set the user-id header for all requests.
    ///
    /// This identifies the user making the requests.
    pub fn user_id(self, user_id: impl AsRef<str>) -> LettaResult<Self> {
        self.header("user-id", user_id)
    }
}

/// Main Letta API client.
#[derive(Debug, Clone)]
pub struct LettaClient {
    http: reqwest::Client,
    config: ClientConfig,
    retry_config: RetryConfig,
}

impl LettaClient {
    /// Create a new Letta client.
    pub fn new(config: ClientConfig) -> LettaResult<Self> {
        let http = reqwest::Client::builder()
            .timeout(config.timeout)
            .default_headers(config.headers.clone())
            .build()?;

        Ok(Self {
            http,
            config,
            retry_config: RetryConfig::default(),
        })
    }

    /// Create a new client for Letta Cloud with the given API token.
    pub fn cloud(token: impl Into<String>) -> LettaResult<Self> {
        ClientBuilder::new()
            .environment(LettaEnvironment::Cloud)
            .auth(AuthConfig::bearer(token))
            .build()
    }

    /// Create a new client for a self-hosted/local Letta server.
    pub fn local() -> LettaResult<Self> {
        ClientBuilder::new()
            .environment(LettaEnvironment::SelfHosted)
            .build()
    }

    /// Create a new client for Letta Cloud with project context.
    ///
    /// This creates a client that automatically includes the X-Project header
    /// with all requests, associating them with the specified project.
    pub fn cloud_with_project(
        token: impl Into<String>,
        project_id: impl AsRef<str>,
    ) -> LettaResult<Self> {
        ClientBuilder::new()
            .environment(LettaEnvironment::Cloud)
            .auth(AuthConfig::bearer(token))
            .project(project_id)?
            .build()
    }

    /// Create a new client builder.
    pub fn builder() -> ClientBuilder {
        ClientBuilder::new()
    }

    /// Get the base URL.
    pub fn base_url(&self) -> &Url {
        &self.config.base_url
    }

    /// Get the HTTP client.
    pub fn http(&self) -> &reqwest::Client {
        &self.http
    }

    /// Get the authentication configuration.
    pub fn auth(&self) -> &AuthConfig {
        &self.config.auth
    }

    /// Get the agent API.
    pub fn agents(&self) -> crate::api::AgentApi<'_> {
        crate::api::AgentApi::new(self)
    }

    /// Get the message API.
    pub fn messages(&self) -> crate::api::MessageApi<'_> {
        crate::api::MessageApi::new(self)
    }

    /// Get the memory API.
    pub fn memory(&self) -> crate::api::MemoryApi<'_> {
        crate::api::MemoryApi::new(self)
    }

    /// Get the source API.
    pub fn sources(&self) -> crate::api::SourceApi<'_> {
        crate::api::SourceApi::new(self)
    }

    /// Get the tool API.
    pub fn tools(&self) -> crate::api::ToolApi<'_> {
        crate::api::ToolApi::new(self)
    }

    /// Get the health API.
    pub fn health(&self) -> crate::api::HealthApi<'_> {
        crate::api::HealthApi::new(self)
    }

    /// Get the blocks API.
    pub fn blocks(&self) -> crate::api::BlocksApi<'_> {
        crate::api::BlocksApi::new(self)
    }

    /// Get the retry configuration.
    pub fn retry_config(&self) -> &RetryConfig {
        &self.retry_config
    }

    /// Set the retry configuration.
    pub fn set_retry_config(&mut self, config: RetryConfig) {
        self.retry_config = config;
    }

    // HTTP helper methods

    /// Make a GET request.
    pub async fn get<T>(&self, path: &str) -> LettaResult<T>
    where
        T: serde::de::DeserializeOwned,
    {
        self.get_internal(path).await
    }

    /// Internal GET implementation with retry logic.
    #[tracing::instrument(skip(self), fields(path = %path))]
    async fn get_internal<T>(&self, path: &str) -> LettaResult<T>
    where
        T: serde::de::DeserializeOwned,
    {
        let url = self.base_url().join(path.trim_start_matches('/'))?;

        retry_with_config(&self.retry_config, || async {
            let mut headers = HeaderMap::new();
            self.auth().apply_to_headers(&mut headers)?;

            tracing::debug!("Sending GET request to {}", url);
            let response = self.http().get(url.clone()).headers(headers).send().await?;

            if !response.status().is_success() {
                let status = response.status().as_u16();
                let headers = response.headers().clone();
                let body = response.text().await?;
                return Err(LettaError::from_response_with_context(
                    status,
                    body,
                    Some(&headers),
                    Some(url.clone()),
                    Some("GET".to_string()),
                ));
            }

            Ok(response.json().await?)
        })
        .await
    }

    /// Make a POST request with a JSON body.
    #[tracing::instrument(skip(self, body), fields(path = %path))]
    pub async fn post<T, B>(&self, path: &str, body: &B) -> LettaResult<T>
    where
        T: serde::de::DeserializeOwned,
        B: serde::Serialize + ?Sized,
    {
        let url = self.base_url().join(path.trim_start_matches('/'))?;
        let body_json = serde_json::to_value(body)?;

        retry_with_config(&self.retry_config, || async {
            let mut headers = HeaderMap::new();
            self.auth().apply_to_headers(&mut headers)?;
            headers.insert(
                "Content-Type",
                "application/json"
                    .parse()
                    .map_err(|_| LettaError::config("Failed to parse Content-Type header"))?,
            );

            let response = self
                .http()
                .post(url.clone())
                .headers(headers)
                .json(&body_json)
                .send()
                .await?;

            if !response.status().is_success() {
                let status = response.status().as_u16();
                let headers = response.headers().clone();
                let body = response.text().await?;
                return Err(LettaError::from_response_with_context(
                    status,
                    body,
                    Some(&headers),
                    Some(url.clone()),
                    Some("POST".to_string()),
                ));
            }

            Ok(response.json().await?)
        })
        .await
    }

    /// Make a PATCH request with a JSON body.
    #[tracing::instrument(skip(self, body), fields(path = %path))]
    pub async fn patch<T, B>(&self, path: &str, body: &B) -> LettaResult<T>
    where
        T: serde::de::DeserializeOwned,
        B: serde::Serialize + ?Sized,
    {
        let url = self.base_url().join(path.trim_start_matches('/'))?;
        let body_json = serde_json::to_value(body)?;

        retry_with_config(&self.retry_config, || async {
            let mut headers = HeaderMap::new();
            self.auth().apply_to_headers(&mut headers)?;
            headers.insert(
                "Content-Type",
                "application/json"
                    .parse()
                    .map_err(|_| LettaError::config("Failed to parse Content-Type header"))?,
            );

            let response = self
                .http()
                .patch(url.clone())
                .headers(headers)
                .json(&body_json)
                .send()
                .await?;

            if !response.status().is_success() {
                let status = response.status().as_u16();
                let headers = response.headers().clone();
                let body = response.text().await?;
                return Err(LettaError::from_response_with_context(
                    status,
                    body,
                    Some(&headers),
                    Some(url.clone()),
                    Some("PATCH".to_string()),
                ));
            }

            Ok(response.json().await?)
        })
        .await
    }

    /// Make a PATCH request without a body.
    #[tracing::instrument(skip(self), fields(path = %path))]
    pub async fn patch_no_body<T>(&self, path: &str) -> LettaResult<T>
    where
        T: serde::de::DeserializeOwned,
    {
        let url = self.base_url().join(path.trim_start_matches('/'))?;

        retry_with_config(&self.retry_config, || async {
            let mut headers = HeaderMap::new();
            self.auth().apply_to_headers(&mut headers)?;

            let response = self
                .http()
                .patch(url.clone())
                .headers(headers)
                .send()
                .await?;

            if !response.status().is_success() {
                let status = response.status().as_u16();
                let headers = response.headers().clone();
                let body = response.text().await?;
                return Err(LettaError::from_response_with_context(
                    status,
                    body,
                    Some(&headers),
                    Some(url.clone()),
                    Some("PATCH".to_string()),
                ));
            }

            Ok(response.json().await?)
        })
        .await
    }

    /// Make a PUT request with a JSON body.
    #[tracing::instrument(skip(self, body), fields(path = %path))]
    pub async fn put<T, B>(&self, path: &str, body: &B) -> LettaResult<T>
    where
        T: serde::de::DeserializeOwned,
        B: serde::Serialize + ?Sized,
    {
        let url = self.base_url().join(path.trim_start_matches('/'))?;
        let body_json = serde_json::to_value(body)?;

        retry_with_config(&self.retry_config, || async {
            let mut headers = HeaderMap::new();
            self.auth().apply_to_headers(&mut headers)?;
            headers.insert(
                "Content-Type",
                "application/json"
                    .parse()
                    .map_err(|_| LettaError::config("Failed to parse Content-Type header"))?,
            );

            let response = self
                .http()
                .put(url.clone())
                .headers(headers)
                .json(&body_json)
                .send()
                .await?;

            if !response.status().is_success() {
                let status = response.status().as_u16();
                let headers = response.headers().clone();
                let body = response.text().await?;
                return Err(LettaError::from_response_with_context(
                    status,
                    body,
                    Some(&headers),
                    Some(url.clone()),
                    Some("PUT".to_string()),
                ));
            }

            Ok(response.json().await?)
        })
        .await
    }

    /// Make a PUT request with custom headers.
    #[tracing::instrument(skip(self, body, extra_headers), fields(path = %path))]
    pub async fn put_with_headers<T, B>(
        &self,
        path: &str,
        body: &B,
        extra_headers: HeaderMap,
    ) -> LettaResult<T>
    where
        T: serde::de::DeserializeOwned,
        B: serde::Serialize + ?Sized,
    {
        let url = self.base_url().join(path.trim_start_matches('/'))?;
        let body_json = serde_json::to_value(body)?;

        retry_with_config(&self.retry_config, || async {
            let mut headers = HeaderMap::new();
            self.auth().apply_to_headers(&mut headers)?;
            headers.insert(
                "Content-Type",
                "application/json"
                    .parse()
                    .map_err(|_| LettaError::config("Failed to parse Content-Type header"))?,
            );

            // Add extra headers
            for (key, value) in extra_headers.iter() {
                headers.insert(key.clone(), value.clone());
            }

            let response = self
                .http()
                .put(url.clone())
                .headers(headers)
                .json(&body_json)
                .send()
                .await?;

            if !response.status().is_success() {
                let status = response.status().as_u16();
                let headers = response.headers().clone();
                let body = response.text().await?;
                return Err(LettaError::from_response_with_context(
                    status,
                    body,
                    Some(&headers),
                    Some(url.clone()),
                    Some("PUT".to_string()),
                ));
            }

            Ok(response.json().await?)
        })
        .await
    }

    /// Make a DELETE request.
    #[tracing::instrument(skip(self), fields(path = %path))]
    pub async fn delete<T>(&self, path: &str) -> LettaResult<T>
    where
        T: serde::de::DeserializeOwned,
    {
        let url = self.base_url().join(path.trim_start_matches('/'))?;

        retry_with_config(&self.retry_config, || async {
            let mut headers = HeaderMap::new();
            self.auth().apply_to_headers(&mut headers)?;

            let response = self
                .http()
                .delete(url.clone())
                .headers(headers)
                .send()
                .await?;

            if !response.status().is_success() {
                let status = response.status().as_u16();
                let headers = response.headers().clone();
                let body = response.text().await?;
                return Err(LettaError::from_response_with_context(
                    status,
                    body,
                    Some(&headers),
                    Some(url.clone()),
                    Some("DELETE".to_string()),
                ));
            }

            Ok(response.json().await?)
        })
        .await
    }

    /// Make a DELETE request expecting no response body.
    #[tracing::instrument(skip(self), fields(path = %path))]
    pub async fn delete_no_response(&self, path: &str) -> LettaResult<()> {
        let url = self.base_url().join(path.trim_start_matches('/'))?;

        retry_with_config(&self.retry_config, || async {
            let mut headers = HeaderMap::new();
            self.auth().apply_to_headers(&mut headers)?;

            let response = self
                .http()
                .delete(url.clone())
                .headers(headers)
                .send()
                .await?;

            if !response.status().is_success() {
                let status = response.status().as_u16();
                let headers = response.headers().clone();
                let body = response.text().await?;
                return Err(LettaError::from_response_with_context(
                    status,
                    body,
                    Some(&headers),
                    Some(url.clone()),
                    Some("DELETE".to_string()),
                ));
            }

            Ok(())
        })
        .await
    }

    /// Make a GET request with query parameters.
    #[tracing::instrument(skip(self, query), fields(path = %path))]
    pub async fn get_with_query<T, Q>(&self, path: &str, query: &Q) -> LettaResult<T>
    where
        T: serde::de::DeserializeOwned,
        Q: serde::Serialize + ?Sized,
    {
        let url = self.base_url().join(path.trim_start_matches('/'))?;

        retry_with_config(&self.retry_config, || async {
            let mut headers = HeaderMap::new();
            self.auth().apply_to_headers(&mut headers)?;

            let response = self
                .http()
                .get(url.clone())
                .headers(headers)
                .query(query)
                .send()
                .await?;

            if !response.status().is_success() {
                let status = response.status().as_u16();
                let headers = response.headers().clone();
                let body = response.text().await?;
                return Err(LettaError::from_response_with_context(
                    status,
                    body,
                    Some(&headers),
                    Some(url.clone()),
                    Some("GET".to_string()),
                ));
            }

            Ok(response.json().await?)
        })
        .await
    }

    /// Make a POST request with custom headers.
    #[tracing::instrument(skip(self, body, extra_headers), fields(path = %path))]
    pub async fn post_with_headers<T, B>(
        &self,
        path: &str,
        body: &B,
        extra_headers: HeaderMap,
    ) -> LettaResult<T>
    where
        T: serde::de::DeserializeOwned,
        B: serde::Serialize + ?Sized,
    {
        let url = self.base_url().join(path.trim_start_matches('/'))?;
        let body_json = serde_json::to_value(body)?;

        retry_with_config(&self.retry_config, || async {
            let mut headers = HeaderMap::new();
            self.auth().apply_to_headers(&mut headers)?;
            headers.insert(
                "Content-Type",
                "application/json"
                    .parse()
                    .map_err(|_| LettaError::config("Failed to parse Content-Type header"))?,
            );

            // Add extra headers
            for (key, value) in extra_headers.iter() {
                headers.insert(key.clone(), value.clone());
            }

            let response = self
                .http()
                .post(url.clone())
                .headers(headers)
                .json(&body_json)
                .send()
                .await?;

            if !response.status().is_success() {
                let status = response.status().as_u16();
                let headers = response.headers().clone();
                let body = response.text().await?;
                return Err(LettaError::from_response_with_context(
                    status,
                    body,
                    Some(&headers),
                    Some(url.clone()),
                    Some("POST".to_string()),
                ));
            }

            Ok(response.json().await?)
        })
        .await
    }

    /// Make a POST request with multipart form data.
    #[tracing::instrument(skip(self, form), fields(path = %path))]
    pub async fn post_multipart<T>(
        &self,
        path: &str,
        form: reqwest::multipart::Form,
    ) -> LettaResult<T>
    where
        T: serde::de::DeserializeOwned,
    {
        let url = self.base_url().join(path.trim_start_matches('/'))?;

        // Note: We can't retry multipart uploads easily since the form is consumed
        // For now, we'll do a single attempt. In the future, we could implement
        // a more sophisticated retry mechanism for multipart uploads.
        let mut headers = HeaderMap::new();
        self.auth().apply_to_headers(&mut headers)?;

        let response = self
            .http()
            .post(url.clone())
            .headers(headers)
            .multipart(form)
            .send()
            .await?;

        if !response.status().is_success() {
            let status = response.status().as_u16();
            let headers = response.headers().clone();
            let body = response.text().await?;
            return Err(LettaError::from_response_with_context(
                status,
                body,
                Some(&headers),
                Some(url.clone()),
                Some("POST".to_string()),
            ));
        }

        Ok(response.json().await?)
    }
}

/// Builder for creating a Letta client.
#[derive(Debug, Default)]
pub struct ClientBuilder {
    environment: Option<LettaEnvironment>,
    base_url: Option<String>,
    auth: Option<AuthConfig>,
    timeout: Option<Duration>,
    headers: Option<HeaderMap>,
}

impl ClientBuilder {
    /// Create a new client builder.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the environment (Cloud or SelfHosted).
    pub fn environment(mut self, env: LettaEnvironment) -> Self {
        self.environment = Some(env);
        self
    }

    /// Set the base URL (overrides environment).
    pub fn base_url(mut self, url: impl Into<String>) -> Self {
        self.base_url = Some(url.into());
        self
    }

    /// Set the authentication.
    pub fn auth(mut self, auth: AuthConfig) -> Self {
        self.auth = Some(auth);
        self
    }

    /// Set the timeout.
    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.timeout = Some(timeout);
        self
    }

    /// Set any custom headers.
    pub fn headers(mut self, headers: HeaderMap) -> Self {
        self.headers = Some(headers);
        self
    }

    /// Add a single header to include with all requests.
    pub fn header(mut self, key: impl AsRef<str>, value: impl AsRef<str>) -> LettaResult<Self> {
        let key = key.as_ref();
        let value = value.as_ref();

        let header_name = reqwest::header::HeaderName::from_bytes(key.as_bytes())
            .map_err(|_| LettaError::validation(format!("Invalid header name: {}", key)))?;
        let header_value = reqwest::header::HeaderValue::from_str(value).map_err(|_| {
            LettaError::validation(format!("Invalid header value for {}: {}", key, value))
        })?;

        let headers = self.headers.get_or_insert_with(HeaderMap::new);
        headers.insert(header_name, header_value);
        Ok(self)
    }

    /// Set the X-Project header for all requests.
    ///
    /// This associates all operations with a specific project context.
    pub fn project(self, project_id: impl AsRef<str>) -> LettaResult<Self> {
        self.header("X-Project", project_id)
    }

    /// Set the user-id header for all requests.
    ///
    /// This identifies the user making the requests.
    pub fn user_id(self, user_id: impl AsRef<str>) -> LettaResult<Self> {
        self.header("user-id", user_id)
    }

    /// Build the client.
    pub fn build(self) -> LettaResult<LettaClient> {
        // Check if we have an explicit base URL
        let has_explicit_url = self.base_url.is_some();

        // Determine base URL: explicit base_url takes precedence over environment
        let base_url = if let Some(url) = self.base_url {
            url
        } else {
            // Use environment or default to Cloud
            let env = self.environment.unwrap_or_default();
            env.base_url().to_string()
        };

        let mut config = ClientConfig::new(base_url)?;

        // Apply authentication
        if let Some(auth) = self.auth {
            config = config.auth(auth);
        } else if self.environment.unwrap_or_default().requires_auth() && !has_explicit_url {
            // Warn if using cloud environment without auth
            eprintln!("Warning: Cloud environment typically requires authentication");
        }

        if let Some(timeout) = self.timeout {
            config = config.timeout(timeout);
        }

        if let Some(headers) = self.headers {
            config = config.headers(headers);
        }

        LettaClient::new(config)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_client_config() {
        let config = ClientConfig::new("http://localhost:8283").unwrap();
        assert_eq!(config.base_url.as_str(), "http://localhost:8283/");
        assert_eq!(config.timeout, Duration::from_secs(30));
    }

    #[test]
    fn test_client_builder() {
        let client = ClientBuilder::new()
            .base_url("http://localhost:8283")
            .timeout(Duration::from_secs(60))
            .build()
            .unwrap();

        assert_eq!(client.base_url().as_str(), "http://localhost:8283/");
    }

    #[test]
    fn test_environment_based_client() {
        // Test cloud environment
        let client = ClientBuilder::new()
            .environment(LettaEnvironment::Cloud)
            .auth(AuthConfig::bearer("test-token"))
            .build()
            .unwrap();
        assert_eq!(client.base_url().as_str(), "https://api.letta.com/");

        // Test self-hosted environment
        let client = ClientBuilder::new()
            .environment(LettaEnvironment::SelfHosted)
            .build()
            .unwrap();
        assert_eq!(client.base_url().as_str(), "http://localhost:8283/");
    }

    #[test]
    fn test_convenience_constructors() {
        // Test cloud constructor
        let client = LettaClient::cloud("test-token").unwrap();
        assert_eq!(client.base_url().as_str(), "https://api.letta.com/");

        // Test local constructor
        let client = LettaClient::local().unwrap();
        assert_eq!(client.base_url().as_str(), "http://localhost:8283/");
    }

    #[test]
    fn test_base_url_overrides_environment() {
        // base_url should override environment setting
        let client = ClientBuilder::new()
            .environment(LettaEnvironment::Cloud)
            .base_url("http://custom.example.com")
            .build()
            .unwrap();
        assert_eq!(client.base_url().as_str(), "http://custom.example.com/");
    }

    #[test]
    fn test_header_configuration() -> LettaResult<()> {
        // Test adding headers via builder
        let _client = ClientBuilder::new()
            .base_url("http://localhost:8283")
            .header("user-id", "test-user-123")?
            .header("x-custom-header", "custom-value")?
            .build()?;

        // The headers are stored in the internal HTTP client, so we can't directly
        // verify them in this test. But we've verified the builder pattern works.

        // Test adding headers via ClientConfig
        let mut config = ClientConfig::new("http://localhost:8283")?;
        config = config.header("user-id", "test-user-456")?;
        let _client = LettaClient::new(config)?;

        Ok(())
    }

    #[test]
    fn test_header_helpers() -> LettaResult<()> {
        // Test project helper
        let _client = ClientBuilder::new()
            .base_url("http://localhost:8283")
            .project("my-project-123")?
            .build()?;

        // Test user_id helper
        let _client = ClientBuilder::new()
            .base_url("http://localhost:8283")
            .user_id("user-456")?
            .build()?;

        // Test both helpers together
        let _client = ClientBuilder::new()
            .base_url("http://localhost:8283")
            .project("project-789")?
            .user_id("user-789")?
            .build()?;

        // Test on ClientConfig
        let config = ClientConfig::new("http://localhost:8283")?
            .project("config-project")?
            .user_id("config-user")?;
        let _client = LettaClient::new(config)?;

        Ok(())
    }

    #[test]
    fn test_cloud_with_project() -> LettaResult<()> {
        let client = LettaClient::cloud_with_project("test-token", "project-123")?;
        assert_eq!(client.base_url().as_str(), "https://api.letta.com/");
        // Headers are configured internally
        Ok(())
    }
}