openintents 0.2.0

Rust SDK for OpenIntents, the agentic API to buy anything
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
use std::time::{Duration, Instant};

use rand::Rng;
use reqwest::{header, Method, RequestBuilder, StatusCode};
use serde::de::DeserializeOwned;
use serde::Deserialize;

use crate::error::{Error, Result};
use crate::stream::EventStream;
use crate::types::{
    AnswerInput, Balance, CreateIntent, CreateProfile, CreateSession, CreateTopup, Customer, CustomerList,
    CustomerParams, EventList, Intent, IntentList, IntentStatus, ListCustomers, ListEvents, ListIntents, ListProfiles,
    ListSessions, Profile, ProfileLease, ProfileList, Session, SessionCommand, SessionCommandResult, SessionList,
    Topup,
};
use crate::types_v1::{
    CreatePortalSession, CreateSecret, CreateSecretRequest, CreateSignIn, CreateWebhookEndpoint, ListSecrets, LiveLink,
    Page, PortalSession, RateLimit, Secret, SecretList, SecretRequest, SecretRequestCreated, SecretUseList, SignIn,
    UpdateWebhookEndpoint, WebhookDelivery, WebhookDeliveryList, WebhookEndpoint, WebhookEndpointList,
};

pub const DEFAULT_BASE_URL: &str = "https://api.openintents.io/v1";
const VERSION: &str = env!("CARGO_PKG_VERSION");
/// The longest the API holds a request for `Prefer: wait`.
const MAX_HOLD_SECS: u32 = 50;
/// A stream with no event and no keep-alive for this long (or the client
/// timeout, if longer) is dropped and resumed.
const STREAM_IDLE_TIMEOUT: Duration = Duration::from_secs(60);

/// Client for the OpenIntents agentic API.
///
/// ```no_run
/// # async fn run() -> openintents::Result<()> {
/// use openintents::{Client, CreateIntent};
///
/// let oi = Client::from_env()?; // OPENINTENTS_API_KEY
/// let intent = oi.create_intent(CreateIntent::new("flat white, oat milk").max_amount(1000)).await?;
/// let intent = oi.wait(&intent.id, Default::default()).await?;
/// if let Some(payment) = &intent.payment {
///     println!("pay here: {}", payment.payment_url);
/// }
/// # Ok(()) }
/// ```
#[derive(Debug, Clone)]
pub struct Client {
    http: reqwest::Client,
    api_key: String,
    base_url: String,
    timeout: Duration,
    pub(crate) max_retries: u32,
}

/// Options for [`Client::wait`].
#[derive(Debug, Clone, Copy)]
pub struct WaitOptions {
    /// Give up after this long. Default 5 minutes.
    pub timeout: Duration,
    /// Time between polls. Default 2s.
    pub interval: Duration,
    /// Return when the intent needs payment (default true), so a person can
    /// be sent `payment.payment_url`. False keeps waiting until it is final.
    pub return_on_payment: bool,
    /// Return when the intent waits for its payer to sign in to the shop
    /// (default true), so they can be sent `sign_in.url`. False keeps waiting
    /// until it is final.
    pub return_on_sign_in: bool,
    /// Return when the intent waits for its payer to answer what the agent
    /// asks, while it signs them in or for a detail the purchase needs
    /// (default true), so they can be asked `input_request.prompt`. False
    /// keeps waiting until it is final.
    pub return_on_input: bool,
}

impl Default for WaitOptions {
    fn default() -> Self {
        Self {
            timeout: Duration::from_secs(300),
            interval: Duration::from_secs(2),
            return_on_payment: true,
            return_on_sign_in: true,
            return_on_input: true,
        }
    }
}

#[derive(Deserialize)]
struct ErrorBody {
    error: Option<ErrorDetail>,
}

#[derive(Deserialize)]
struct ErrorDetail {
    #[serde(rename = "type")]
    kind: Option<String>,
    code: Option<String>,
    message: Option<String>,
    param: Option<String>,
    lease: Option<ProfileLease>,
}

impl Client {
    /// A client with the given API key and default settings.
    pub fn new(api_key: impl Into<String>) -> Self {
        Self::builder(api_key).build()
    }

    /// Reads OPENINTENTS_API_KEY (and OPENINTENTS_BASE_URL, if set).
    pub fn from_env() -> Result<Self> {
        let key = std::env::var("OPENINTENTS_API_KEY")
            .ok()
            .filter(|k| !k.trim().is_empty())
            .ok_or(Error::MissingApiKey)?;
        let mut builder = Self::builder(key);
        if let Ok(url) = std::env::var("OPENINTENTS_BASE_URL") {
            builder = builder.base_url(url);
        }
        Ok(builder.build())
    }

    pub fn builder(api_key: impl Into<String>) -> ClientBuilder {
        ClientBuilder {
            api_key: api_key.into(),
            base_url: DEFAULT_BASE_URL.to_string(),
            timeout: Duration::from_secs(30),
            max_retries: 2,
        }
    }

    /// Start an intent. Returns immediately, usually with status `queued`.
    /// Sends a fresh Idempotency-Key; use [`Client::create_intent_idempotent`] to set your own.
    pub async fn create_intent(&self, params: CreateIntent) -> Result<Intent> {
        self.create_intent_idempotent(params, &uuid::Uuid::new_v4().to_string())
            .await
    }

    pub async fn create_intent_idempotent(&self, params: CreateIntent, idempotency_key: &str) -> Result<Intent> {
        self.send(Method::POST, "/intents", Some(idempotency_key), |r| r.json(&params))
            .await
    }

    pub async fn get_intent(&self, id: &str) -> Result<Intent> {
        self.send(Method::GET, &format!("/intents/{id}"), None, |r| r).await
    }

    /// [`Client::create_intent`], holding the request up to `wait_secs` whole
    /// seconds (`Prefer: wait=N`, applied as 50 at most) until the intent is
    /// neither `queued` nor `running`: it finished, or now needs a payment, an
    /// answer or a sign-in. A hold that runs out is no error: the intent comes
    /// back as it stands. The client's timeout is stretched to outlast the hold.
    pub async fn create_intent_waiting(&self, params: CreateIntent, wait_secs: u32) -> Result<Intent> {
        let key = uuid::Uuid::new_v4().to_string();
        self.send(Method::POST, "/intents", Some(&key), |r| {
            self.hold(r, wait_secs).json(&params)
        })
        .await
    }

    /// [`Client::get_intent`], held like [`Client::create_intent_waiting`].
    pub async fn get_intent_waiting(&self, id: &str, wait_secs: u32) -> Result<Intent> {
        self.send(Method::GET, &format!("/intents/{id}"), None, |r| {
            self.hold(r, wait_secs)
        })
        .await
    }

    pub async fn list_intents(&self, params: &ListIntents) -> Result<IntentList> {
        self.send(Method::GET, "/intents", None, |r| r.query(params)).await
    }

    /// Cancel an intent that hasn't paid yet. Cancelled intents are free.
    pub async fn cancel_intent(&self, id: &str) -> Result<Intent> {
        let key = uuid::Uuid::new_v4().to_string();
        self.send(Method::POST, &format!("/intents/{id}/cancel"), Some(&key), |r| r)
            .await
    }

    /// Answer the intent's `input_request` while it waits in
    /// `requires_input`. Returns the intent, usually `running` again. A
    /// request already answered or expired is a 409 `input_not_waiting`.
    /// Sends a fresh Idempotency-Key, so a retry never answers twice.
    ///
    /// ```no_run
    /// # async fn run(oi: openintents::Client, intent: openintents::Intent) -> openintents::Result<()> {
    /// use openintents::AnswerInput;
    ///
    /// if let Some(request) = &intent.input_request {
    ///     // Ask the payer `request.prompt`, then:
    ///     oi.answer_intent_input(&intent.id, AnswerInput::value(&request.id, "481516"))
    ///         .await?;
    /// }
    /// # Ok(()) }
    /// ```
    pub async fn answer_intent_input(&self, id: &str, answer: AnswerInput) -> Result<Intent> {
        let key = uuid::Uuid::new_v4().to_string();
        self.send(Method::POST, &format!("/intents/{id}/input"), Some(&key), |r| {
            r.json(&answer)
        })
        .await
    }

    /// The agent balance intents pay from, and this month's spend.
    pub async fn balance(&self) -> Result<Balance> {
        self.send(Method::GET, "/balance", None, |r| r).await
    }

    /// A customer's balance.
    pub async fn balance_for(&self, customer: &str) -> Result<Balance> {
        self.send(Method::GET, "/balance", None, |r| r.query(&[("customer", customer)]))
            .await
    }

    /// Someone you buy for, with their own balance and browser profile.
    /// Sends a fresh Idempotency-Key; use [`Client::create_customer_idempotent`] to set your own.
    pub async fn create_customer(&self, params: CustomerParams) -> Result<Customer> {
        self.create_customer_idempotent(params, &uuid::Uuid::new_v4().to_string())
            .await
    }

    pub async fn create_customer_idempotent(&self, params: CustomerParams, idempotency_key: &str) -> Result<Customer> {
        self.send(Method::POST, "/customers", Some(idempotency_key), |r| r.json(&params))
            .await
    }

    pub async fn get_customer(&self, id: &str) -> Result<Customer> {
        self.send(Method::GET, &format!("/customers/{id}"), None, |r| r).await
    }

    /// Fields left out stay as they are (see [`CustomerParams`]).
    pub async fn update_customer(&self, id: &str, params: CustomerParams) -> Result<Customer> {
        self.send(Method::PATCH, &format!("/customers/{id}"), None, |r| r.json(&params))
            .await
    }

    /// Newest first.
    pub async fn list_customers(&self, params: &ListCustomers) -> Result<CustomerList> {
        self.send(Method::GET, "/customers", None, |r| r.query(params)).await
    }

    /// A payment link that adds `amount` to a balance once paid. Live keys only.
    /// Sends a fresh Idempotency-Key; use [`Client::create_topup_idempotent`] to set your own.
    pub async fn create_topup(&self, params: CreateTopup) -> Result<Topup> {
        self.create_topup_idempotent(params, &uuid::Uuid::new_v4().to_string())
            .await
    }

    pub async fn create_topup_idempotent(&self, params: CreateTopup, idempotency_key: &str) -> Result<Topup> {
        self.send(Method::POST, "/topups", Some(idempotency_key), |r| r.json(&params))
            .await
    }

    pub async fn get_topup(&self, id: &str) -> Result<Topup> {
        self.send(Method::GET, &format!("/topups/{id}"), None, |r| r).await
    }

    /// A page of the intent's timeline, oldest first: status changes, the
    /// agent's steps, its checkout.
    pub async fn list_intent_events(&self, id: &str, params: &ListEvents) -> Result<EventList> {
        self.send(Method::GET, &format!("/intents/{id}/events"), None, |r| r.query(params))
            .await
    }

    /// Follow the intent's timeline live: past events first, then new ones as
    /// they happen, after `last_event_id` if given. The stream resumes by
    /// itself after a dropped connection, and ends once the intent is over and
    /// its last event was sent.
    ///
    /// ```no_run
    /// # async fn run(oi: openintents::Client) -> openintents::Result<()> {
    /// let mut events = oi.stream_intent_events("int_7f3a2c", None);
    /// while let Some(event) = events.next().await {
    ///     let event = event?;
    ///     println!("{} {}", event.kind, event.data);
    /// }
    /// # Ok(()) }
    /// ```
    pub fn stream_intent_events(&self, id: &str, last_event_id: Option<&str>) -> EventStream {
        EventStream::new(self.clone(), format!("/intents/{id}/events"), last_event_id)
    }

    /// Your account's profile and your customers' that exist so far, newest first.
    pub async fn list_profiles(&self, params: &ListProfiles) -> Result<ProfileList> {
        self.send(Method::GET, "/profiles", None, |r| r.query(params)).await
    }

    /// Make the profile of your account, or of a customer, ahead of its first
    /// intent or session. Optional: an intent makes the profile it needs.
    /// Making one that exists returns it unchanged, so no Idempotency-Key is
    /// sent.
    pub async fn create_profile(&self, params: CreateProfile) -> Result<Profile> {
        self.send(Method::POST, "/profiles", None, |r| r.json(&params)).await
    }

    pub async fn get_profile(&self, id: &str) -> Result<Profile> {
        self.send(Method::GET, &format!("/profiles/{id}"), None, |r| r).await
    }

    /// Erase everything the profile kept: logins, cookies, saved data. Returns
    /// it `forgetting`, then it turns `forgotten`. Forgetting twice is fine.
    pub async fn forget_profile(&self, id: &str) -> Result<Profile> {
        self.send(Method::DELETE, &format!("/profiles/{id}"), None, |r| r).await
    }

    /// Open a browser on a profile without an intent. A profile in use is a
    /// 409 `profile_busy` whose `lease` says what holds it. Sends a fresh
    /// Idempotency-Key; use [`Client::create_session_idempotent`] to set your own.
    pub async fn create_session(&self, params: CreateSession) -> Result<Session> {
        self.create_session_idempotent(params, &uuid::Uuid::new_v4().to_string())
            .await
    }

    pub async fn create_session_idempotent(&self, params: CreateSession, idempotency_key: &str) -> Result<Session> {
        self.send(Method::POST, "/sessions", Some(idempotency_key), |r| r.json(&params))
            .await
    }

    pub async fn get_session(&self, id: &str) -> Result<Session> {
        self.send(Method::GET, &format!("/sessions/{id}"), None, |r| r).await
    }

    /// Newest first.
    pub async fn list_sessions(&self, params: &ListSessions) -> Result<SessionList> {
        self.send(Method::GET, "/sessions", None, |r| r.query(params)).await
    }

    /// Close the browser, keeping what the session changed in the profile. A
    /// session that already ended is returned unchanged.
    pub async fn release_session(&self, id: &str) -> Result<Session> {
        let key = uuid::Uuid::new_v4().to_string();
        self.send(Method::POST, &format!("/sessions/{id}/release"), Some(&key), |r| r)
            .await
    }

    /// Run one command on the session's page. It waits up to 20 seconds; a
    /// command still running then comes back `Pending`, to follow with
    /// [`Client::get_session_command`]. A refused or failed one says why in
    /// `error`. Sends a fresh Idempotency-Key, so a retry never runs it twice;
    /// use [`Client::run_session_command_idempotent`] to set your own.
    pub async fn run_session_command(&self, id: &str, command: SessionCommand) -> Result<SessionCommandResult> {
        self.run_session_command_idempotent(id, command, &uuid::Uuid::new_v4().to_string())
            .await
    }

    pub async fn run_session_command_idempotent(
        &self,
        id: &str,
        command: SessionCommand,
        idempotency_key: &str,
    ) -> Result<SessionCommandResult> {
        self.send(
            Method::POST,
            &format!("/sessions/{id}/commands"),
            Some(idempotency_key),
            |r| r.json(&command),
        )
        .await
    }

    pub async fn get_session_command(&self, id: &str, command_id: &str) -> Result<SessionCommandResult> {
        self.send(
            Method::GET,
            &format!("/sessions/{id}/commands/{command_id}"),
            None,
            |r| r,
        )
        .await
    }

    /// A screenshot of the session's page, taken now: JPEG bytes.
    pub async fn session_screenshot(&self, id: &str) -> Result<Vec<u8>> {
        let res = self
            .send_raw(
                Method::GET,
                &format!("/sessions/{id}/screenshot"),
                None,
                "image/jpeg",
                |r| r,
            )
            .await?;
        Ok(res.bytes().await?.to_vec())
    }

    /// A page of the session's timeline, oldest first: status changes, pages
    /// and commands.
    pub async fn list_session_events(&self, id: &str, params: &ListEvents) -> Result<EventList> {
        self.send(Method::GET, &format!("/sessions/{id}/events"), None, |r| {
            r.query(params)
        })
        .await
    }

    /// Follow the session's timeline live, like [`Client::stream_intent_events`].
    pub fn stream_session_events(&self, id: &str, last_event_id: Option<&str>) -> EventStream {
        EventStream::new(self.clone(), format!("/sessions/{id}/events"), last_event_id)
    }

    /// A link to the session's live view, valid for 10 minutes. Whoever holds
    /// `url` sees the browser and drives it, though never to pay or place an
    /// order. The session must be `open`. Each call makes a new link.
    pub async fn create_live_link(&self, session: &str) -> Result<LiveLink> {
        let key = uuid::Uuid::new_v4().to_string();
        self.send(
            Method::POST,
            &format!("/sessions/{session}/live_links"),
            Some(&key),
            |r| r,
        )
        .await
    }

    /// A link to a customer's own page, shown once: send `url` to the
    /// customer only. Until portal sessions are open to your key this is a
    /// 503 `portal_unavailable`.
    pub async fn create_portal_session(&self, customer: &str, params: CreatePortalSession) -> Result<PortalSession> {
        let key = uuid::Uuid::new_v4().to_string();
        self.send(
            Method::POST,
            &format!("/customers/{customer}/portal_sessions"),
            Some(&key),
            |r| r.json(&params),
        )
        .await
    }

    /// Ask a customer for their secrets on a page of their own. Send them the
    /// `url`; its end is a `secret_request.completed` webhook.
    pub async fn create_secret_request(
        &self,
        customer: &str,
        params: CreateSecretRequest,
    ) -> Result<SecretRequestCreated> {
        let key = uuid::Uuid::new_v4().to_string();
        self.send(
            Method::POST,
            &format!("/customers/{customer}/secret_requests"),
            Some(&key),
            |r| r.json(&params),
        )
        .await
    }

    /// Where a request for a customer's secrets stands.
    pub async fn get_secret_request(&self, id: &str) -> Result<SecretRequest> {
        self.send(Method::GET, &format!("/secret_requests/{id}"), None, |r| r)
            .await
    }

    /// Store details a purchase may need and that you would not put in a
    /// prompt. Secrets are write-only: one comes back as its label, a mask and
    /// a few public fields, never its values. Sends a fresh Idempotency-Key.
    pub async fn create_secret(&self, params: CreateSecret) -> Result<Secret> {
        let key = uuid::Uuid::new_v4().to_string();
        self.send(Method::POST, "/secrets", Some(&key), |r| r.json(&params))
            .await
    }

    /// A payer's secrets in the key's mode, without their values: your
    /// account's, or a customer's.
    pub async fn list_secrets(&self, params: &ListSecrets) -> Result<SecretList> {
        self.send(Method::GET, "/secrets", None, |r| r.query(params)).await
    }

    pub async fn get_secret(&self, id: &str) -> Result<Secret> {
        self.send(Method::GET, &format!("/secrets/{id}"), None, |r| r).await
    }

    /// Replace a secret's whole content; its version goes up.
    pub async fn replace_secret(&self, id: &str, params: CreateSecret) -> Result<Secret> {
        let key = uuid::Uuid::new_v4().to_string();
        self.send(Method::PUT, &format!("/secrets/{id}"), Some(&key), |r| r.json(&params))
            .await
    }

    /// Delete a secret and its values.
    pub async fn delete_secret(&self, id: &str) -> Result<()> {
        self.send_raw(
            Method::DELETE,
            &format!("/secrets/{id}"),
            None,
            "application/json",
            |r| r,
        )
        .await?;
        Ok(())
    }

    /// A secret's history, newest first: made, replaced, filled into a shop or
    /// refused. Never a value.
    pub async fn list_secret_uses(&self, id: &str, page: &Page) -> Result<SecretUseList> {
        self.send(Method::GET, &format!("/secrets/{id}/uses"), None, |r| r.query(page))
            .await
    }

    /// A link where the payer signs in to a shop with no intent attached; the
    /// profile keeps the login. Send them `url`. Its end is a
    /// `sign_in.completed` or `sign_in.expired` webhook.
    pub async fn create_sign_in(&self, params: CreateSignIn) -> Result<SignIn> {
        let key = uuid::Uuid::new_v4().to_string();
        self.send(Method::POST, "/sign_ins", Some(&key), |r| r.json(&params))
            .await
    }

    pub async fn get_sign_in(&self, id: &str) -> Result<SignIn> {
        self.send(Method::GET, &format!("/sign_ins/{id}"), None, |r| r).await
    }

    /// Register a URL for your account's events. The response alone carries
    /// its `secret`: keep it.
    pub async fn create_webhook_endpoint(&self, params: CreateWebhookEndpoint) -> Result<WebhookEndpoint> {
        let key = uuid::Uuid::new_v4().to_string();
        self.send(Method::POST, "/webhook_endpoints", Some(&key), |r| r.json(&params))
            .await
    }

    /// Newest first, without their secrets.
    pub async fn list_webhook_endpoints(&self, page: &Page) -> Result<WebhookEndpointList> {
        self.send(Method::GET, "/webhook_endpoints", None, |r| r.query(page))
            .await
    }

    pub async fn get_webhook_endpoint(&self, id: &str) -> Result<WebhookEndpoint> {
        self.send(Method::GET, &format!("/webhook_endpoints/{id}"), None, |r| r)
            .await
    }

    /// Change its URL, its event types (an empty list is every intent event)
    /// or whether it is disabled.
    pub async fn update_webhook_endpoint(&self, id: &str, params: UpdateWebhookEndpoint) -> Result<WebhookEndpoint> {
        self.send(Method::PATCH, &format!("/webhook_endpoints/{id}"), None, |r| {
            r.json(&params)
        })
        .await
    }

    pub async fn delete_webhook_endpoint(&self, id: &str) -> Result<()> {
        self.send_raw(
            Method::DELETE,
            &format!("/webhook_endpoints/{id}"),
            None,
            "application/json",
            |r| r,
        )
        .await?;
        Ok(())
    }

    /// Make a new secret, returned here only. The one before keeps signing for
    /// 24 hours; [`verify_webhook`](crate::verify_webhook) accepts a header
    /// that carries both.
    pub async fn rotate_webhook_secret(&self, id: &str) -> Result<WebhookEndpoint> {
        self.send(
            Method::POST,
            &format!("/webhook_endpoints/{id}/rotate_secret"),
            None,
            |r| r,
        )
        .await
    }

    /// Send a `webhook_endpoint.test` event to this endpoint alone; the
    /// delivery shows how it goes.
    pub async fn test_webhook_endpoint(&self, id: &str) -> Result<WebhookDelivery> {
        self.send(Method::POST, &format!("/webhook_endpoints/{id}/test"), None, |r| r)
            .await
    }

    /// What was sent to the endpoint, newest first.
    pub async fn list_webhook_deliveries(&self, id: &str, page: &Page) -> Result<WebhookDeliveryList> {
        self.send(Method::GET, &format!("/webhook_endpoints/{id}/deliveries"), None, |r| {
            r.query(page)
        })
        .await
    }

    /// Send a delivery again, with the same event `id` and body.
    pub async fn redeliver_webhook(&self, endpoint: &str, delivery: &str) -> Result<WebhookDelivery> {
        self.send(
            Method::POST,
            &format!("/webhook_endpoints/{endpoint}/deliveries/{delivery}/redeliver"),
            None,
            |r| r,
        )
        .await
    }

    /// Poll until the intent is final, or (by default) waits on a person: its
    /// payment, an answer from its payer, or its payer's sign-in.
    pub async fn wait(&self, id: &str, opts: WaitOptions) -> Result<Intent> {
        let deadline = Instant::now() + opts.timeout;
        loop {
            let intent = self.get_intent(id).await?;
            let waits_on_person = (opts.return_on_payment && intent.status == IntentStatus::RequiresPayment)
                || (opts.return_on_sign_in && intent.status == IntentStatus::RequiresLogin)
                || (opts.return_on_input && intent.status == IntentStatus::RequiresInput);
            if intent.status.is_final() || waits_on_person {
                return Ok(intent);
            }
            if Instant::now() + opts.interval > deadline {
                return Err(Error::WaitTimeout {
                    intent_id: id.to_string(),
                    timeout: opts.timeout,
                });
            }
            tokio::time::sleep(opts.interval).await;
        }
    }

    /// Asks the API to hold a request (`Prefer: wait=N`) and stretches the
    /// timeout to outlast the hold.
    fn hold(&self, req: RequestBuilder, wait_secs: u32) -> RequestBuilder {
        let hold = Duration::from_secs(u64::from(wait_secs.min(MAX_HOLD_SECS)) + 10);
        req.header("Prefer", format!("wait={wait_secs}"))
            .timeout(self.timeout.max(hold))
    }

    async fn send<T: DeserializeOwned>(
        &self,
        method: Method,
        path: &str,
        idempotency_key: Option<&str>,
        build: impl Fn(RequestBuilder) -> RequestBuilder,
    ) -> Result<T> {
        let res = self
            .send_raw(method, path, idempotency_key, "application/json", build)
            .await?;
        Ok(res.json().await?)
    }

    /// Sends a request, retrying 429, 5xx and connection errors with backoff,
    /// and returns the 2xx response.
    async fn send_raw(
        &self,
        method: Method,
        path: &str,
        idempotency_key: Option<&str>,
        accept: &str,
        build: impl Fn(RequestBuilder) -> RequestBuilder,
    ) -> Result<reqwest::Response> {
        let mut attempt = 0;
        loop {
            let req = self
                .request(method.clone(), path, accept, idempotency_key)
                .timeout(self.timeout);
            let res = match build(req).send().await {
                Ok(res) => res,
                Err(err) if attempt < self.max_retries && (err.is_connect() || err.is_timeout()) => {
                    tokio::time::sleep(backoff(attempt, None)).await;
                    attempt += 1;
                    continue;
                }
                Err(err) => return Err(err.into()),
            };
            let status = res.status();
            if status.is_success() {
                return Ok(res);
            }
            if retryable(status) && attempt < self.max_retries {
                tokio::time::sleep(backoff(attempt, retry_after(&res))).await;
                attempt += 1;
                continue;
            }
            return Err(api_error(res).await);
        }
    }

    /// A request with the key and the headers every call sends. Without a
    /// per-request timeout, only the client's connect and read timeouts apply,
    /// which is what an event stream needs.
    pub(crate) fn request(
        &self,
        method: Method,
        path: &str,
        accept: &str,
        idempotency_key: Option<&str>,
    ) -> RequestBuilder {
        let mut req = self
            .http
            .request(method, format!("{}{}", self.base_url, path))
            .bearer_auth(&self.api_key)
            .header(header::ACCEPT, accept);
        if let Some(key) = idempotency_key {
            req = req.header("Idempotency-Key", key);
        }
        req
    }
}

pub(crate) fn retryable(status: StatusCode) -> bool {
    status == StatusCode::TOO_MANY_REQUESTS || status.is_server_error()
}

pub(crate) fn retry_after(res: &reqwest::Response) -> Option<f64> {
    res.headers()
        .get(header::RETRY_AFTER)
        .and_then(|v| v.to_str().ok())
        .and_then(|v| v.parse::<f64>().ok())
}

/// Turns a non-2xx response into [`Error::Api`].
pub(crate) async fn api_error(res: reqwest::Response) -> Error {
    let status = res.status();
    let request_id = res
        .headers()
        .get("request-id")
        .and_then(|v| v.to_str().ok())
        .map(str::to_string);
    let retry_after = header_int(&res, "retry-after");
    let rate_limit = rate_limit(&res);
    let detail = res.json::<ErrorBody>().await.ok().and_then(|b| b.error);
    let (kind, code, param, message, lease) = match detail {
        Some(d) => (d.kind, d.code, d.param, d.message, d.lease),
        None => (None, None, None, None, None),
    };
    Error::Api {
        status: status.as_u16(),
        kind: kind.unwrap_or_else(|| {
            if status.is_server_error() {
                "api_error"
            } else {
                "invalid_request"
            }
            .into()
        }),
        code,
        param,
        message: message.unwrap_or_else(|| format!("HTTP {}", status.as_u16())),
        lease,
        request_id,
        retry_after,
        rate_limit,
    }
}

fn header_int(res: &reqwest::Response, name: &str) -> Option<u64> {
    res.headers()
        .get(name)
        .and_then(|v| v.to_str().ok())
        .and_then(|v| v.trim().parse::<u64>().ok())
}

fn rate_limit(res: &reqwest::Response) -> Option<RateLimit> {
    let int = |name: &str| header_int(res, name).and_then(|v| u32::try_from(v).ok());
    Some(RateLimit {
        limit: int("ratelimit-limit")?,
        remaining: int("ratelimit-remaining")?,
        reset: int("ratelimit-reset")?,
    })
}

pub(crate) fn backoff(attempt: u32, retry_after: Option<f64>) -> Duration {
    if let Some(secs) = retry_after.filter(|s| *s > 0.0) {
        return Duration::from_secs_f64(secs);
    }
    let base = (0.5 * 2f64.powi(attempt as i32)).min(8.0);
    Duration::from_secs_f64(base * rand::thread_rng().gen_range(0.75..1.25))
}

/// Configures a [`Client`].
#[derive(Debug, Clone)]
pub struct ClientBuilder {
    api_key: String,
    base_url: String,
    timeout: Duration,
    max_retries: u32,
}

impl ClientBuilder {
    pub fn base_url(mut self, url: impl Into<String>) -> Self {
        self.base_url = url.into().trim_end_matches('/').to_string();
        self
    }

    /// Per-request timeout. Default 30s.
    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.timeout = timeout;
        self
    }

    /// Retries for 429, 5xx and connection errors. Default 2.
    pub fn max_retries(mut self, n: u32) -> Self {
        self.max_retries = n;
        self
    }

    pub fn build(self) -> Client {
        // Each request sets its own total timeout, but an event stream lives
        // longer: the read timeout only drops one that stalls, as keep-alives
        // reset it.
        let http = reqwest::Client::builder()
            .connect_timeout(self.timeout)
            .read_timeout(self.timeout.max(STREAM_IDLE_TIMEOUT))
            .user_agent(format!("openintents-rust/{VERSION}"))
            .build()
            .expect("reqwest client with rustls builds");
        Client {
            http,
            api_key: self.api_key,
            base_url: self.base_url,
            timeout: self.timeout,
            max_retries: self.max_retries,
        }
    }
}