Expand description
§grokbot_api
Version 1.1.0 · Tests: 117 unit and integration tests and 36 doctests, all passing ·
Coverage: 99% of lines (cargo llvm-cov --all-features) · MSRV: Rust 1.89
An unofficial async Rust client for the Grok Bot gateway: the private API behind the Grok Bot desktop app that lists your bots, sends them prompts and reads their replies.
It gives you typed calls for every known gateway method, plus the pieces needed to use them:
- Sessions. Turn a Cursor access token into a gateway session with EnsureSandBox, and re-authenticate automatically when the session expires.
- Safety. A host allowlist ensures credentials only go to Cursor hosts, and error messages never contain secrets.
- Delivery. Each send reports whether the prompt landed: accepted, rejected or unknown.
- Transcripts. Page through chat history and detect approval cards.
- Desktop app (opt-in). Reuse the desktop app’s saved login.
Unofficial and undocumented. The gateway has no public documentation. This crate mirrors what grok-bot-cli and the desktop app do, and the API may change without notice. It is not affiliated with or endorsed by the makers of Grok Bot or Cursor.
§Install
[dependencies]
grokbot_api = "1"
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
# Optional: read the Grok Bot desktop app's saved session.
# grokbot_api = { version = "1", features = ["desktop-session"] }Or cargo add grokbot_api tokio --features tokio/macros,tokio/rt-multi-thread.
The client uses reqwest with rustls; it needs a Tokio runtime.
§Examples
List your bots with a gateway session:
use grokbot_api::{Client, ClientOptions, Session};
#[tokio::main]
async fn main() -> grokbot_api::Result<()> {
let session = Session::new("https://<box>.cursorvm.com", "<gateway token>");
let client = Client::new(session, ClientOptions::default())?;
for agent in client.list_agents().await? {
println!("{} {}", agent.id, agent.display_name());
}
Ok(())
}Log in with a Cursor access token, send a prompt and read the transcript:
use grokbot_api::{Client, ClientOptions, Delivery, SendPrompt};
#[tokio::main]
async fn main() -> grokbot_api::Result<()> {
// EnsureSandBox exchanges the token; the client re-exchanges on 401/417.
let client = Client::connect_cursor("<cursor access token>", ClientOptions::default()).await?;
let bot = &client.list_agents().await?[0];
let receipt = client.send_prompt(&SendPrompt::new(&bot.id, "hello")).await?;
assert_eq!(receipt.delivery, Delivery::Accepted);
// Replies arrive asynchronously: poll the transcript.
for entry in client.transcript_tail(&bot.id, 20, None).await?.entries {
let who = if entry.is_from_user() { "you" } else { "bot" };
println!("[{who}] {}", grokbot_api::sanitize_text(&entry.text));
}
Ok(())
}Check where credentials may be sent (no network):
use grokbot_api::Policy;
let policy = Policy::default();
assert!(policy.check_gateway("https://box.us1.cursorvm.com").is_ok());
assert!(policy.check_gateway("https://example.com").is_err());More in examples/. cargo run --example mock_gateway runs the whole flow
offline against a mock server.
§Table of contents
| Guide | What it covers |
|---|---|
| Sessions and authentication | Gateway sessions, EnsureSandBox, client identity, 401/417 re-authentication, ClientOptions |
| Credential policy | The host allowlist, loopback gateways, GROKBOT_ALLOW_LOCAL_GATEWAY |
| Agents, groups and team agents | Listing, creating, updating and deleting bots; groups; team bots shared with you |
| Sending prompts and delivery | send_prompt, nonces, Delivery, promptAcceptanceStatus, waiting for replies |
| Transcripts | Tail pages, beforeSeq paging, full history, threads, entry parsing, sanitizing |
| Approvals | Detecting approval cards and resolving them (on a user’s decision only) |
| Workflows (skills) | Listing, importing and deleting skills |
| Errors, limits and redaction | Error variants, delivery mapping, timeouts, size caps, secret redaction |
| Desktop session | The opt-in desktop-session feature: reading the desktop app’s saved login |
| Wire protocol | Endpoints, headers, every method’s request body, call_raw |
On docs.rs the same guides are in the
guide module.
§Development
cargo test --all-features # unit, integration and doc tests (mock servers only)
cargo clippy --all-targets --all-features -- -D warnings
cargo llvm-cov --all-features --summary-only
RUSTDOCFLAGS="-D warnings" cargo doc --all-features --no-depsThe tests never contact the real gateway and use only fake tokens. A few branches are not covered:
- code that only runs on another OS (the Windows DPAPI path)
- fixed system install paths such as
/opt/Grok Bot reqwestclient construction failures
See CHANGELOG.md for release notes.
§License
BSD 3-Clause. See LICENSE.
Re-exports§
pub use attachments::AttachmentKind;pub use attachments::AttachmentRead;pub use attachments::ReadOutcome;pub use attachments::UploadFailure;pub use attachments::UploadMode;pub use attachments::UploadProgress;pub use attachments::UploadRefusal;pub use attachments::UploadedAttachment;
Modules§
- attachments
- Prompt attachments: upload a file to the Grok Bot attachment store and get an alias
to send with
SendPrompt::attachment_paths. - desktop
desktop-session - Read and decrypt the Grok Bot desktop app’s saved gateway session.
- guide
- Topic guides.
Structs§
- Agent
- A bot or group as returned by
listAgents. - Agent
Profile - An
updateAgentprofile.nameanddescriptionare always sent;Nonefields are left unchanged. - Approval
- A pending approval request found in a transcript (see grok-bot-cli
grokApproval). Never approve automatically: approvals need an explicit user decision. - Client
- Async gateway client. Share it behind an
Arc; methods take&self. - Client
Options - Settings for
Client,ensure_sandboxandgrokbot_service_call. - Create
Agent - A
createAgentrequest (sent withorigin: "user"). - Create
Group - A
createGrouprequest. - Entry
- One transcript entry: a user prompt, a bot reply, a tool event, an approval card, …
- Import
Result - The result of
importAgentWorkflowText. - Policy
- Which URLs may receive credentials.
- Send
Prompt - A
sendPromptrequest. - Send
Receipt - The receipt for a
sendPromptcall. Replies arrive later in the transcript. - Session
- A gateway connection: base URL, bearer token and extra headers.
- Skipped
Import - A workflow the server declined to import.
- Team
Agent - One agent from the Cursor backend’s
GrokBotService/ListGrokBotTeamAgents: your own agents plus team agents shared with you (which the box gateway’slistAgentsomits). - Transcript
- A page of transcript entries (
getAgentTranscriptTail), a walked history (Client::transcript_history) or a thread (getAgentThread). - Workflow
- A workflow (“skill”) from
getAgentWorkflows.
Enums§
- Acceptance
Status - Result of
promptAcceptanceStatus, mirroring the desktop app’s mapping:{outcome: "not-found" | "unknown-durability"}or{outcome: "found", record: {status: "accepted" | "rejected" | "pending", rejectionCode?}}. - Approval
Kind - Which resolve method an
Approvalneeds. - Auto
Review Resolution - A
resolveAutoReviewApprovaldecision. - BoxIntent
- What the user is doing in a chat (
GrokBotBoxIntent). - Delivery
- Whether a prompt reached the gateway.
- Error
- Everything that can go wrong talking to the gateway, the Cursor backend, or the desktop app’s saved session.
- Local
Tool Resolution - A
resolveLocalToolPermissiondecision.
Constants§
- ALLOW_
LOCAL_ ENV - Environment variable read by
Policy::from_env:1,trueoryesallows loopback gateways (e.g. a local mock server). - AVATAR_
COLORS - Avatar colors accepted by
createAgent/updateAgent. - AVATAR_
SHAPES - Avatar shapes accepted by
createAgent/updateAgent. - DEFAULT_
BACKEND_ BASE - Default Cursor backend for EnsureSandBox.
- DEFAULT_
CLIENT_ TYPE - Default
x-cursor-client-type(matches the desktop app’sSAND_CLIENT_TYPE). - DEFAULT_
CLIENT_ VERSION - Default
x-cursor-client-version(Grok Bot 0.70.x era). Prefer detecting the installed desktop app version viadesktop::detect_app_version(desktop-sessionfeature). - DEFAULT_
SANDBOX_ NAMESPACE - Default
x-sand-box-namespacefor production EnsureSandBox. - MAX_
GROUP_ MEMBERS - Most member agents a group may have (
createGroup/setGroupMembers). - MAX_
RESPONSE_ BYTES - Response body cap.
- SKILL_
MAX_ BODY_ LENGTH - Grok Bot truncates workflow (skill) bodies over this many characters, so
Client::import_agent_workflow_textrejects longer input. - TIMEOUT
- Per-request deadline.
Functions§
- ensure_
sandbox - Exchange a Cursor access token for a gateway session via
POST {backend}/aiserver.v1.GrokBotService/EnsureSandBox. - grokbot_
service_ call - 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. - sanitize_
text - Strip ANSI escape sequences and control characters (except
\nand\t) so server text cannot drive the terminal.
Type Aliases§
- Result
- Shorthand for
std::result::Result<T, grokbot_api::Error>.