grokbot_api 1.2.0

Unofficial async client for the (undocumented) Grok Bot gateway 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
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
//! The gateway client, EnsureSandBox, and Cursor backend calls.
use crate::error::{Delivery, Error, Result};
use crate::policy::Policy;
use crate::transcript::Transcript;
use crate::types::*;
use serde_json::{Value, json};
use std::collections::BTreeMap;
use std::sync::{Mutex, RwLock};
use std::time::Duration;

/// Default Cursor backend for EnsureSandBox.
pub const DEFAULT_BACKEND_BASE: &str = "https://api2.cursor.sh";
/// Per-request deadline.
pub const TIMEOUT: Duration = Duration::from_secs(30);
/// Response body cap.
pub const MAX_RESPONSE_BYTES: usize = 2 * 1024 * 1024;

/// Default `x-cursor-client-version` (Grok Bot 0.70.x era). Prefer detecting the
/// installed desktop app version via `desktop::detect_app_version` (`desktop-session` feature).
pub const DEFAULT_CLIENT_VERSION: &str = "0.70.2";
/// Default `x-cursor-client-type` (matches the desktop app's `SAND_CLIENT_TYPE`).
pub const DEFAULT_CLIENT_TYPE: &str = "sand";
/// Default `x-sand-box-namespace` for production EnsureSandBox.
pub const DEFAULT_SANDBOX_NAMESPACE: &str = "prod";

/// Settings for [`Client`], [`ensure_sandbox`] and [`grokbot_service_call`].
///
/// ```
/// use grokbot_api::{ClientOptions, Policy};
/// use std::time::Duration;
///
/// let opts = ClientOptions {
///     timeout: Duration::from_secs(10),
///     client_version: "0.70.2".into(),
///     ..ClientOptions::default()
/// };
/// assert_eq!(opts.policy, Policy::from_env());
/// ```
#[derive(Debug, Clone)]
pub struct ClientOptions {
    /// Which URLs may receive credentials (default: [`Policy::from_env`]).
    pub policy: Policy,
    /// Cursor backend base URL for EnsureSandBox (must pass [`Policy::check_backend`]).
    pub backend_base: String,
    /// Per-request deadline (default [`TIMEOUT`]).
    pub timeout: Duration,
    /// Response body cap in bytes (default [`MAX_RESPONSE_BYTES`]).
    pub max_response_bytes: usize,
    /// Sent as `x-cursor-client-version` on EnsureSandBox.
    pub client_version: String,
    /// Sent as `x-cursor-client-type` on EnsureSandBox.
    pub client_type: String,
    /// Sent as `x-sand-box-namespace` on EnsureSandBox.
    pub sandbox_namespace: String,
}

impl Default for ClientOptions {
    fn default() -> Self {
        Self {
            policy: Policy::from_env(),
            backend_base: DEFAULT_BACKEND_BASE.into(),
            timeout: TIMEOUT,
            max_response_bytes: MAX_RESPONSE_BYTES,
            client_version: DEFAULT_CLIENT_VERSION.into(),
            client_type: DEFAULT_CLIENT_TYPE.into(),
            sandbox_namespace: DEFAULT_SANDBOX_NAMESPACE.into(),
        }
    }
}

fn http_client(timeout: Duration) -> Result<reqwest::Client> {
    reqwest::Client::builder()
        .timeout(timeout)
        .redirect(reqwest::redirect::Policy::none())
        .user_agent(concat!("grokbot_api/", env!("CARGO_PKG_VERSION")))
        .build()
        .map_err(|e| Error::Transport {
            method: "client".into(),
            message: e.to_string(),
        })
}

/// Replace secrets and bearer values in error text.
fn redact(text: &str, secrets: &[&str]) -> String {
    let mut s = text.to_string();
    for sec in secrets.iter().filter(|s| s.len() >= 4) {
        s = s.replace(sec, "<redacted>");
    }
    // "Bearer xyz" -> "Bearer <redacted>"
    let mut out = String::new();
    let mut rest = s.as_str();
    while let Some(i) = rest.to_lowercase().find("bearer ") {
        out.push_str(&rest[..i + 7]);
        out.push_str("<redacted>");
        let tail = &rest[i + 7..];
        let end = tail
            .find(|c: char| c.is_whitespace() || c == '"' || c == ',')
            .unwrap_or(tail.len());
        rest = &tail[end..];
    }
    out.push_str(rest);
    out
}

/// POST JSON with a body cap; returns (status, parsed body). Non-JSON bodies become `{"raw": text}`.
async fn post(
    http: &reqwest::Client,
    url: &str,
    headers: &BTreeMap<String, String>,
    body: &Value,
    method: &str,
    cap: usize,
    secrets: &[&str],
) -> Result<(u16, Value)> {
    let mut rb = http
        .post(url)
        .header("content-type", "application/json")
        .body(body.to_string());
    for (k, v) in headers {
        rb = rb.header(k, v);
    }
    let transport = |e: reqwest::Error| Error::Transport {
        method: method.into(),
        message: redact(&e.to_string(), secrets),
    };
    let mut res = rb.send().await.map_err(transport)?;
    let status = res.status().as_u16();
    if res.status().is_redirection() {
        return Err(Error::Transport {
            method: method.into(),
            message: format!("refused redirect (HTTP {status})"),
        });
    }
    let mut buf = Vec::new();
    while let Some(chunk) = res.chunk().await.map_err(transport)? {
        buf.extend_from_slice(&chunk);
        if buf.len() > cap {
            return Err(Error::TooLarge {
                method: method.into(),
                limit: cap,
            });
        }
    }
    let text = String::from_utf8_lossy(&buf);
    let data = if text.trim().is_empty() {
        json!({})
    } else {
        serde_json::from_str(&text).unwrap_or_else(|_| json!({ "raw": text }))
    };
    Ok((status, data))
}

fn detail(data: &Value) -> String {
    ["message", "error", "raw"]
        .iter()
        .find_map(|k| {
            data.get(*k).map(|v| {
                v.as_str()
                    .map(str::to_string)
                    .unwrap_or_else(|| v.to_string())
            })
        })
        .unwrap_or_default()
}

fn pick<'a>(v: &'a Value, keys: &[&str]) -> Option<&'a Value> {
    keys.iter()
        .find_map(|k| v.get(*k).filter(|x| !x.is_null() && x.as_str() != Some("")))
}

/// Exchange a Cursor access token for a gateway session via
/// `POST {backend}/aiserver.v1.GrokBotService/EnsureSandBox`.
///
/// Do not pass a Cursor dashboard API key; those do not work.
pub async fn ensure_sandbox(access_token: &str, opts: &ClientOptions) -> Result<Session> {
    let base = opts
        .policy
        .check_backend(&opts.backend_base)
        .map_err(Error::Policy)?;
    let http = http_client(opts.timeout)?;
    ensure_sandbox_with(&http, &base, access_token, opts).await
}

/// Call a unary `aiserver.v1.GrokBotService/<method>` on the Cursor backend (Connect JSON)
/// with the same headers as EnsureSandBox. Returns the JSON body; the token is redacted
/// from any error.
pub async fn grokbot_service_call(
    access_token: &str,
    method: &str,
    body: &Value,
    opts: &ClientOptions,
) -> Result<Value> {
    let base = opts
        .policy
        .check_backend(&opts.backend_base)
        .map_err(Error::Policy)?;
    let http = http_client(opts.timeout)?;
    let url = format!("{base}/aiserver.v1.GrokBotService/{method}");
    let (status, out) = post(
        &http,
        &url,
        &backend_headers(access_token, opts),
        body,
        method,
        opts.max_response_bytes,
        &[access_token],
    )
    .await?;
    if !(200..300).contains(&status) {
        return Err(Error::Http {
            method: method.into(),
            status,
            message: redact(&detail(&out), &[access_token]),
        });
    }
    Ok(out)
}

fn backend_headers(access_token: &str, opts: &ClientOptions) -> BTreeMap<String, String> {
    [
        ("connect-protocol-version", "1".to_string()),
        ("authorization", format!("Bearer {access_token}")),
        ("x-cursor-client-type", opts.client_type.clone()),
        ("x-cursor-client-version", opts.client_version.clone()),
        ("x-sand-box-namespace", opts.sandbox_namespace.clone()),
    ]
    .into_iter()
    .map(|(k, v)| (k.to_string(), v))
    .collect()
}

async fn ensure_sandbox_with(
    http: &reqwest::Client,
    base: &str,
    access_token: &str,
    opts: &ClientOptions,
) -> Result<Session> {
    const M: &str = "EnsureSandBox";
    let url = format!("{base}/aiserver.v1.GrokBotService/EnsureSandBox");
    let headers = backend_headers(access_token, opts);
    let (status, body) = post(
        http,
        &url,
        &headers,
        &json!({}),
        M,
        opts.max_response_bytes,
        &[access_token],
    )
    .await?;
    if !(200..300).contains(&status) {
        return Err(Error::Http {
            method: M.into(),
            status,
            message: redact(&detail(&body), &[access_token]),
        });
    }
    let as_str = |v: &Value| {
        v.as_str()
            .map(str::to_string)
            .unwrap_or_else(|| v.to_string())
    };
    let (Some(u), Some(t)) = (
        pick(&body, &["gatewayUrl", "gateway_url"]),
        pick(&body, &["gatewayToken", "gateway_token"]),
    ) else {
        return Err(Error::InvalidResponse {
            method: M.into(),
            message:
                "returned no gatewayUrl/gatewayToken (a Cursor dashboard API key will not work)"
                    .into(),
        });
    };
    let gateway_url = opts
        .policy
        .check_gateway(&as_str(u))
        .map_err(Error::Policy)?;
    let mut headers = BTreeMap::new();
    if let Some(Value::Object(m)) = pick(&body, &["gatewayHeaders", "gateway_headers"]) {
        headers = normalize_headers(
            m.iter()
                .filter(|(_, v)| !v.is_null())
                .map(|(k, v)| (k.clone(), as_str(v))),
        );
    }
    if headers.is_empty()
        && let Some(tok) = pick(
            &body,
            &["anyrunNetworkToken", "anyrun_network_token", "networkToken"],
        )
    {
        headers.insert("x-anyrun-network-token".into(), as_str(tok));
    }
    Ok(Session {
        gateway_url,
        gateway_token: as_str(t),
        headers,
    })
}

struct State {
    session: Session,
    cursor_token: Option<String>,
    /// Viewer session per shared agent id (from the team list), sent as `sessionId`.
    agent_sessions: std::collections::HashMap<String, String>,
}

/// Async gateway client. Share it behind an `Arc`; methods take `&self`.
///
/// Every call is `POST {gateway_url}/api/<method>` with the session's bearer token and
/// headers, after re-checking the URL against the [`Policy`]. A client created with a
/// Cursor access token ([`Client::connect_cursor`] / [`Client::with_cursor_token`])
/// re-runs EnsureSandBox once and retries when the gateway answers 401 or 417; persist
/// the new session from [`Client::take_refreshed_session`].
///
/// ```no_run
/// use grokbot_api::{Client, ClientOptions, Session};
///
/// # async fn demo() -> grokbot_api::Result<()> {
/// let client = Client::new(
///     Session::new("https://box.us1.cursorvm.com", "gateway-token"),
///     ClientOptions::default(),
/// )?;
/// for agent in client.list_agents().await? {
///     println!("{} {}", agent.id, agent.display_name());
/// }
/// # Ok(()) }
/// ```
pub struct Client {
    http: reqwest::Client,
    opts: ClientOptions,
    state: RwLock<State>,
    refreshed: Mutex<Option<Session>>,
}

impl std::fmt::Debug for Client {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let st = self.state.read().unwrap();
        f.debug_struct("Client")
            .field("gateway_url", &st.session.gateway_url)
            .field("has_cursor_token", &st.cursor_token.is_some())
            .finish_non_exhaustive()
    }
}

impl Client {
    /// Client for an existing gateway session. The URL is checked against the policy on every call.
    pub fn new(session: Session, opts: ClientOptions) -> Result<Self> {
        opts.policy
            .check_gateway(&session.gateway_url)
            .map_err(Error::Policy)?;
        Ok(Self {
            http: http_client(opts.timeout)?,
            opts,
            state: RwLock::new(State {
                session,
                cursor_token: None,
                agent_sessions: Default::default(),
            }),
            refreshed: Mutex::new(None),
        })
    }

    /// Like [`Client::new`], but keeps the Cursor access token so a 401 triggers one
    /// EnsureSandBox re-exchange and a retry.
    pub fn with_cursor_token(
        session: Session,
        cursor_token: impl Into<String>,
        opts: ClientOptions,
    ) -> Result<Self> {
        let c = Self::new(session, opts)?;
        c.state.write().unwrap().cursor_token = Some(cursor_token.into());
        Ok(c)
    }

    /// EnsureSandBox then build a client that can re-exchange.
    pub async fn connect_cursor(access_token: &str, opts: ClientOptions) -> Result<Self> {
        let session = ensure_sandbox(access_token, &opts).await?;
        Self::with_cursor_token(session, access_token, opts)
    }

    /// The current session (it changes after a 401/417 re-exchange).
    pub fn session(&self) -> Session {
        self.state.read().unwrap().session.clone()
    }

    /// The new session if a 401 re-exchange happened since the last call (persist it).
    pub fn take_refreshed_session(&self) -> Option<Session> {
        self.refreshed.lock().unwrap().take()
    }

    async fn call_once(
        &self,
        s: &Session,
        cursor: Option<&str>,
        method: &str,
        body: &Value,
    ) -> Result<Value> {
        let base = self
            .opts
            .policy
            .check_gateway(&s.gateway_url)
            .map_err(Error::Policy)?;
        let mut headers = s.headers.clone();
        headers.insert(
            "authorization".into(),
            format!("Bearer {}", s.gateway_token),
        );
        let mut secrets = vec![s.gateway_token.as_str()];
        secrets.extend(cursor);
        secrets.extend(s.headers.values().map(String::as_str));
        let url = format!("{base}/api/{method}");
        let (status, data) = post(
            &self.http,
            &url,
            &headers,
            body,
            method,
            self.opts.max_response_bytes,
            &secrets,
        )
        .await?;
        if !(200..300).contains(&status) {
            let msg: String = detail(&data).chars().take(300).collect();
            return Err(Error::Http {
                method: method.into(),
                status,
                message: redact(&msg, &secrets),
            });
        }
        Ok(data)
    }

    /// Call any gateway method with a raw JSON body and return the raw JSON response.
    /// Handles the 401/417 re-exchange like the typed methods.
    pub async fn call_raw(&self, method: &str, body: Value) -> Result<Value> {
        let (session, cursor) = {
            let st = self.state.read().unwrap();
            (st.session.clone(), st.cursor_token.clone())
        };
        match self
            .call_once(&session, cursor.as_deref(), method, &body)
            .await
        {
            Err(e) if e.is_unauthorized() && cursor.is_some() => {
                let tok = cursor.unwrap();
                let base = self
                    .opts
                    .policy
                    .check_backend(&self.opts.backend_base)
                    .map_err(Error::Policy)?;
                let fresh = ensure_sandbox_with(&self.http, &base, &tok, &self.opts).await?;
                {
                    let mut st = self.state.write().unwrap();
                    st.session = fresh.clone();
                }
                *self.refreshed.lock().unwrap() = Some(fresh.clone());
                self.call_once(&fresh, Some(&tok), method, &body).await
            }
            r => r,
        }
    }

    // ------------------------------------------------------------------ agents

    /// `listAgents {}` → bots and groups (hidden ones included; check `hidden_from_sidebar`).
    pub async fn list_agents(&self) -> Result<Vec<Agent>> {
        Ok(Agent::list(&self.call_raw("listAgents", json!({})).await?))
    }

    /// `createAgent {name, description, title, avatarShape, avatarColor, origin: "user"}`.
    pub async fn create_agent(&self, input: &CreateAgent) -> Result<Option<Agent>> {
        if input.name.trim().is_empty() {
            return Err(Error::Validation("Name cannot be blank.".into()));
        }
        let shape = check_avatar("shape", &input.avatar_shape, AVATAR_SHAPES)?;
        let color = check_avatar("color", &input.avatar_color, AVATAR_COLORS)?;
        let data = self
            .call_raw(
                "createAgent",
                json!({ "name": input.name, "description": input.description, "title": input.title,
                        "avatarShape": shape, "avatarColor": color, "origin": "user" }),
            )
            .await?;
        Ok(Agent::one(&data))
    }

    /// `updateAgent {id, profile: {name, description, title?, avatarShape?, avatarColor?}}`.
    pub async fn update_agent(&self, id: &str, profile: &AgentProfile) -> Result<Value> {
        if profile.name.trim().is_empty() {
            return Err(Error::Validation("Name cannot be blank.".into()));
        }
        let mut p = json!({ "name": profile.name.trim(), "description": profile.description });
        if let Some(t) = &profile.title {
            p["title"] = json!(t);
        }
        if let Some(sh) = &profile.avatar_shape {
            p["avatarShape"] = json!(check_avatar("shape", sh, AVATAR_SHAPES)?);
        }
        if let Some(c) = &profile.avatar_color {
            p["avatarColor"] = json!(check_avatar("color", c, AVATAR_COLORS)?);
        }
        self.call_raw("updateAgent", json!({ "id": id, "profile": p }))
            .await
    }

    /// `deleteAgent {id}`.
    pub async fn delete_agent(&self, id: &str) -> Result<Value> {
        self.call_raw("deleteAgent", json!({ "id": id })).await
    }

    /// `setAgentNotifyOnUpdates {id, isEnabled}`.
    pub async fn set_agent_notify_on_updates(&self, id: &str, enabled: bool) -> Result<Value> {
        self.call_raw(
            "setAgentNotifyOnUpdates",
            json!({ "id": id, "isEnabled": enabled }),
        )
        .await
    }

    /// `setAgentHiddenFromSidebar {id, isHidden}`.
    pub async fn set_agent_hidden_from_sidebar(&self, id: &str, hidden: bool) -> Result<Value> {
        self.call_raw(
            "setAgentHiddenFromSidebar",
            json!({ "id": id, "isHidden": hidden }),
        )
        .await
    }

    // ------------------------------------------------------------------ groups

    /// `createGroup {name, description, memberAgentIds}` (1..=6 distinct members, no nested groups).
    pub async fn create_group(&self, input: &CreateGroup) -> Result<Option<Agent>> {
        let ids = check_members(&input.member_agent_ids)?;
        let data = self
            .call_raw(
                "createGroup",
                json!({ "name": input.name, "description": input.description, "memberAgentIds": ids }),
            )
            .await?;
        Ok(Agent::one(&data))
    }

    /// `setGroupMembers {id, memberAgentIds}`.
    pub async fn set_group_members(
        &self,
        group_id: &str,
        member_agent_ids: &[String],
    ) -> Result<Option<Agent>> {
        let ids = check_members(member_agent_ids)?;
        let data = self
            .call_raw(
                "setGroupMembers",
                json!({ "id": group_id, "memberAgentIds": ids }),
            )
            .await?;
        Ok(Agent::one(&data))
    }

    // ------------------------------------------------------------------ chat

    /// Route calls for `agent_id` through `session_id` (a shared agent's viewer session),
    /// sent as `sessionId` on `sendPrompt`, `promptAcceptanceStatus` and
    /// `getAgentTranscriptTail`. [`Client::list_team_agents`] sets this automatically.
    pub fn set_agent_session(&self, agent_id: &str, session_id: &str) {
        self.state
            .write()
            .unwrap()
            .agent_sessions
            .insert(agent_id.into(), session_id.into());
    }

    pub(crate) fn cursor_token_opt(&self) -> Option<String> {
        self.state.read().unwrap().cursor_token.clone()
    }

    pub(crate) fn options(&self) -> &ClientOptions {
        &self.opts
    }

    pub(crate) fn agent_session_id(&self, agent_id: &str) -> Option<String> {
        self.agent_session(agent_id)
    }

    /// Whether this client holds a Cursor access token (needed for attachments and
    /// team agents).
    pub fn has_cursor_session(&self) -> bool {
        self.cursor_token_opt().is_some()
    }

    fn agent_session(&self, agent_id: &str) -> Option<String> {
        self.state
            .read()
            .unwrap()
            .agent_sessions
            .get(agent_id)
            .cloned()
    }

    fn with_session(&self, agent_id: &str, mut body: Value) -> Value {
        if let Some(s) = self.agent_session(agent_id) {
            body["sessionId"] = json!(s);
        }
        body
    }

    /// Cursor backend `GrokBotService/ListGrokBotTeamAgents`: your agents plus team agents
    /// shared with you. `Ok(None)` when this client has no Cursor access token (a plain
    /// gateway session). Shared agents' viewer sessions are remembered for later calls.
    pub async fn list_team_agents(&self) -> Result<Option<Vec<crate::TeamAgent>>> {
        let Some(tok) = self.state.read().unwrap().cursor_token.clone() else {
            return Ok(None);
        };
        let v = grokbot_service_call(&tok, "ListGrokBotTeamAgents", &json!({}), &self.opts).await?;
        let list = crate::TeamAgent::list(&v);
        for a in &list {
            if !a.viewer_is_owner
                && let Some(s) = &a.viewer_session_id
            {
                self.set_agent_session(&a.agent_id, s);
            }
        }
        Ok(Some(list))
    }

    /// `sendPrompt {agentId, prompt, clientNonce, replyToId?, attachmentPaths?, attachmentNames?, sessionId?}` → receipt only.
    ///
    /// Replies arrive later: poll [`Client::transcript_tail`]. On error use
    /// [`Error::delivery`]: `Unknown` means the prompt may have landed, so check the
    /// transcript or [`Client::prompt_acceptance_status`] before resending. A gateway
    /// refusal (`{status: "refused"}` / `{accepted: false}`) is returned as
    /// [`Error::Http`] with status 422.
    pub async fn send_prompt(&self, req: &SendPrompt) -> Result<SendReceipt> {
        if req.prompt.is_empty() {
            return Err(Error::Validation("Prompt is empty.".into()));
        }
        let nonce = req
            .client_nonce
            .clone()
            .unwrap_or_else(|| uuid::Uuid::new_v4().to_string());
        let mut body =
            json!({ "agentId": req.agent_id, "prompt": req.prompt, "clientNonce": nonce });
        if let Some(r) = &req.reply_to_id {
            body["replyToId"] = json!(r);
        }
        if req.attachment_names.len() > req.attachment_paths.len() {
            return Err(Error::Validation(
                "More attachment names than attachment paths.".into(),
            ));
        }
        if !req.attachment_paths.is_empty() {
            body["attachmentPaths"] = json!(req.attachment_paths);
            body["attachmentNames"] = json!(req.attachment_names);
        }
        let body = self.with_session(&req.agent_id, body);
        let raw = self.call_raw("sendPrompt", body).await?;
        let (delivery, message_id) = classify_send(&raw, &nonce)?;
        Ok(SendReceipt {
            message_id,
            client_nonce: nonce,
            delivery,
            raw,
        })
    }

    /// `promptAcceptanceStatus {agentId, clientNonce}`: the gateway's own lookup of
    /// whether a prompt with this nonce landed (what the desktop app uses when a send's
    /// outcome is uncertain).
    pub async fn prompt_acceptance_status(
        &self,
        agent_id: &str,
        client_nonce: &str,
    ) -> Result<AcceptanceStatus> {
        Ok(AcceptanceStatus::from_value(
            &self
                .call_raw(
                    "promptAcceptanceStatus",
                    self.with_session(
                        agent_id,
                        json!({ "agentId": agent_id, "clientNonce": client_nonce }),
                    ),
                )
                .await?,
        ))
    }

    /// `getAgentTranscriptTail {id, limit, beforeSeq?}` (limit clamped to 1..=200).
    ///
    /// Omitting `before_seq` returns the newest page. When the response includes
    /// `nextBeforeSeq`, pass it here to walk older pages (as the desktop app does).
    pub async fn transcript_tail(
        &self,
        id: &str,
        limit: u32,
        before_seq: Option<u64>,
    ) -> Result<Transcript> {
        let limit = limit.clamp(1, 200);
        let mut body = json!({ "id": id, "limit": limit });
        if let Some(seq) = before_seq {
            body["beforeSeq"] = json!(seq);
        }
        let body = self.with_session(id, body);
        Ok(Transcript::from_value(
            self.call_raw("getAgentTranscriptTail", body).await?,
        ))
    }

    /// Walk `getAgentTranscriptTail` pages until the chat is exhausted or `max_entries`
    /// is reached. Newest page first; returned entries are oldest → newest.
    pub async fn transcript_history(
        &self,
        id: &str,
        page_size: u32,
        max_entries: usize,
    ) -> Result<Transcript> {
        let page_size = page_size.clamp(1, 200);
        let mut all: Vec<crate::transcript::Entry> = Vec::new();
        let mut before = None;
        let mut raw_pages = Vec::new();
        loop {
            let page = self.transcript_tail(id, page_size, before).await?;
            raw_pages.push(page.raw.clone());
            if page.entries.is_empty() {
                break;
            }
            // Each page is oldest→newest; older pages are prepended (desktop app does the same).
            all.splice(0..0, page.entries.iter().cloned());
            if all.len() >= max_entries {
                let overflow = all.len() - max_entries;
                all.drain(0..overflow); // keep the newest max_entries
                break;
            }
            match page.next_before_seq {
                Some(seq) => before = Some(seq),
                None => break,
            }
        }
        let mut seen = std::collections::HashSet::new();
        all.retain(|e| match &e.id {
            Some(eid) => seen.insert(eid.clone()),
            None => true,
        });
        Ok(Transcript {
            entries: all,
            next_before_seq: before,
            raw: json!({ "pages": raw_pages }),
        })
    }

    /// `getAgentThread {id, rootId}`.
    pub async fn thread(&self, id: &str, root_id: &str) -> Result<Transcript> {
        Ok(Transcript::from_value(
            self.call_raw("getAgentThread", json!({ "id": id, "rootId": root_id }))
                .await?,
        ))
    }

    // ------------------------------------------------------------------ workflows (skills)

    /// `getAgentWorkflows {id}`. The library is shared per box; `id` is any bot id.
    pub async fn get_agent_workflows(&self, id: &str) -> Result<Vec<Workflow>> {
        Ok(Workflow::list(
            &self
                .call_raw("getAgentWorkflows", json!({ "id": id }))
                .await?,
        ))
    }

    /// `importAgentWorkflowText {id, markdown}`.
    pub async fn import_agent_workflow_text(
        &self,
        id: &str,
        markdown: &str,
    ) -> Result<ImportResult> {
        if markdown.trim().is_empty() {
            return Err(Error::Validation("Skill markdown is empty.".into()));
        }
        if markdown.chars().count() > SKILL_MAX_BODY_LENGTH {
            return Err(Error::Validation(format!(
                "Skill markdown exceeds {SKILL_MAX_BODY_LENGTH} characters."
            )));
        }
        let data = self
            .call_raw(
                "importAgentWorkflowText",
                json!({ "id": id, "markdown": markdown }),
            )
            .await?;
        let r = data.get("result");
        let arr = |k: &str| {
            r.and_then(|r| r.get(k))
                .and_then(Value::as_array)
                .cloned()
                .unwrap_or_default()
        };
        Ok(ImportResult {
            workflows: Workflow::list(&data),
            imported: arr("imported")
                .iter()
                .filter_map(Workflow::from_value)
                .collect(),
            skipped: arr("skipped")
                .iter()
                .map(|s| SkippedImport {
                    reason: s
                        .get("reason")
                        .and_then(Value::as_str)
                        .unwrap_or("rejected")
                        .to_string(),
                })
                .collect(),
        })
    }

    /// `deleteAgentWorkflow {id, workflowId}`.
    pub async fn delete_agent_workflow(&self, id: &str, workflow_id: &str) -> Result<Value> {
        self.call_raw(
            "deleteAgentWorkflow",
            json!({ "id": id, "workflowId": workflow_id }),
        )
        .await
    }

    // ------------------------------------------------------------------ approvals

    /// `resolveLocalToolPermission {agentId, entryId, requestId, resolution: "allow-once"|"deny"}`.
    /// Only call on an explicit user decision.
    pub async fn resolve_local_tool_permission(
        &self,
        agent_id: &str,
        entry_id: &str,
        request_id: &str,
        resolution: LocalToolResolution,
    ) -> Result<Value> {
        self.call_raw(
            "resolveLocalToolPermission",
            json!({ "agentId": agent_id, "entryId": entry_id, "requestId": request_id, "resolution": resolution.as_str() }),
        )
        .await
    }

    /// `resolveAutoReviewApproval {agentId, entryId, requestId, resolution: "approved"|"denied"}`.
    /// Only call on an explicit user decision.
    pub async fn resolve_auto_review_approval(
        &self,
        agent_id: &str,
        entry_id: &str,
        request_id: &str,
        resolution: AutoReviewResolution,
    ) -> Result<Value> {
        self.call_raw(
            "resolveAutoReviewApproval",
            json!({ "agentId": agent_id, "entryId": entry_id, "requestId": request_id, "resolution": resolution.as_str() }),
        )
        .await
    }
}

fn check_avatar(kind: &str, v: &str, allowed: &[&str]) -> Result<String> {
    let t = v.trim();
    if t.is_empty() || allowed.contains(&t) {
        Ok(t.to_string())
    } else {
        Err(Error::Validation(format!(
            "Unknown avatar {kind} \"{v}\". Use: {}",
            allowed.join(" ")
        )))
    }
}

fn check_members(ids: &[String]) -> Result<Vec<String>> {
    let mut out: Vec<String> = vec![];
    for id in ids {
        if !id.is_empty() && !out.contains(id) {
            out.push(id.clone());
        }
    }
    if out.is_empty() {
        return Err(Error::Validation(
            "A group needs at least one existing member agent.".into(),
        ));
    }
    if out.len() > MAX_GROUP_MEMBERS {
        return Err(Error::Validation(format!(
            "A group can have at most {MAX_GROUP_MEMBERS} members."
        )));
    }
    Ok(out)
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn redaction() {
        assert_eq!(
            redact("bad token sekrit1 x", &["sekrit1"]),
            "bad token <redacted> x"
        );
        assert_eq!(
            redact("Authorization: Bearer abc.def, more", &[]),
            "Authorization: Bearer <redacted>, more"
        );
    }
}

/// Result of `promptAcceptanceStatus`, mirroring the desktop app's mapping:
/// `{outcome: "not-found" | "unknown-durability"}` or
/// `{outcome: "found", record: {status: "accepted" | "rejected" | "pending", rejectionCode?}}`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AcceptanceStatus {
    /// The gateway has the prompt.
    Accepted,
    /// The gateway refused it (with its rejection code, if any). Not delivered.
    Rejected(Option<String>),
    /// Still being processed; ask again shortly.
    Pending,
    /// No record of this nonce: it never arrived, so resending is safe.
    NotFound,
    /// The gateway can't tell (or the response was unrecognised).
    Unknown,
}

impl AcceptanceStatus {
    /// Map a `promptAcceptanceStatus` response (optionally wrapped in `{status, value}`).
    ///
    /// ```
    /// use grokbot_api::AcceptanceStatus;
    /// use serde_json::json;
    ///
    /// let s = AcceptanceStatus::from_value(&json!({"outcome": "found",
    ///     "record": {"status": "rejected", "rejectionCode": "too_long"}}));
    /// assert_eq!(s, AcceptanceStatus::Rejected(Some("too_long".into())));
    /// ```
    pub fn from_value(raw: &Value) -> Self {
        let v = raw.get("value").filter(|v| v.is_object()).unwrap_or(raw);
        match v.get("outcome").and_then(Value::as_str) {
            Some("not-found") => return Self::NotFound,
            Some("unknown-durability") => return Self::Unknown,
            _ => {}
        }
        let rec = v.get("record").unwrap_or(v);
        match rec.get("status").and_then(Value::as_str) {
            Some("accepted") => Self::Accepted,
            Some("pending") => Self::Pending,
            Some("rejected") => Self::Rejected(
                rec.get("rejectionCode")
                    .and_then(Value::as_str)
                    .filter(|s| !s.is_empty())
                    .map(str::to_string),
            ),
            Some("not-found") => Self::NotFound,
            _ => Self::Unknown,
        }
    }
}

/// Classify a 2xx `sendPrompt` body.
///
/// The gateway (per the desktop app) answers a successful send with
/// `{accepted: true}` (box/temporal acceptance or a duplicate of the same nonce) and
/// a refused one with `{status: "refused", message}`; it does not return a separate
/// message id; the message id is the client nonce. Older/alternative shapes with a
/// string `messageId` are also accepted, and a `{status, value}` wrapper is unwrapped.
fn classify_send(raw: &Value, nonce: &str) -> Result<(Delivery, Option<String>)> {
    let inner = raw.get("value").filter(|v| v.is_object()).unwrap_or(raw);
    let pick = |k: &str| inner.get(k).or_else(|| raw.get(k));
    let message_id = pick("messageId")
        .and_then(Value::as_str)
        .map(str::to_string);
    let refused = raw.get("status").and_then(Value::as_str) == Some("refused")
        || pick("accepted").and_then(Value::as_bool) == Some(false);
    if refused {
        let msg = pick("message")
            .and_then(Value::as_str)
            .unwrap_or("prompt refused by the gateway");
        return Err(Error::Http {
            method: "sendPrompt".into(),
            status: 422,
            message: msg.chars().take(300).collect(),
        });
    }
    if message_id.is_some() || pick("accepted").and_then(Value::as_bool) == Some(true) {
        return Ok((
            Delivery::Accepted,
            Some(message_id.unwrap_or_else(|| nonce.to_string())),
        ));
    }
    Ok((Delivery::Unknown, None))
}

#[cfg(test)]
mod send_classify_tests {
    use super::*;
    #[test]
    fn classify_shapes() {
        let ok = |v: Value| classify_send(&v, "n1").unwrap();
        assert_eq!(
            ok(json!({"accepted": true})),
            (Delivery::Accepted, Some("n1".into()))
        );
        assert_eq!(
            ok(json!({"status": "ok", "value": {"accepted": true}})),
            (Delivery::Accepted, Some("n1".into()))
        );
        assert_eq!(
            ok(json!({"messageId": "m1"})),
            (Delivery::Accepted, Some("m1".into()))
        );
        assert_eq!(ok(json!({})), (Delivery::Unknown, None));
        assert_eq!(ok(json!(null)), (Delivery::Unknown, None));
        let e =
            classify_send(&json!({"status": "refused", "message": "too long"}), "n").unwrap_err();
        assert_eq!(e.delivery(), Delivery::Rejected);
        assert!(e.to_string().contains("too long"));
        assert_eq!(
            classify_send(&json!({"accepted": false}), "n")
                .unwrap_err()
                .delivery(),
            Delivery::Rejected
        );
        use AcceptanceStatus as A;
        let a = |v: Value| A::from_value(&v);
        assert_eq!(
            a(json!({"outcome": "found", "record": {"status": "accepted"}})),
            A::Accepted
        );
        assert_eq!(
            a(
                json!({"status": "ok", "value": {"outcome": "found", "record": {"status": "rejected", "rejectionCode": "too_long"}}})
            ),
            A::Rejected(Some("too_long".into()))
        );
        assert_eq!(
            a(json!({"outcome": "found", "record": {"status": "pending"}})),
            A::Pending
        );
        assert_eq!(a(json!({"outcome": "not-found"})), A::NotFound);
        assert_eq!(a(json!({"outcome": "unknown-durability"})), A::Unknown);
        assert_eq!(a(json!({})), A::Unknown);
    }
}