Skip to main content

Crate grokbot_api

Crate grokbot_api 

Source
Expand description

§grokbot_api

crates.io docs.rs CI License: BSD-3-Clause

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

GuideWhat it covers
Sessions and authenticationGateway sessions, EnsureSandBox, client identity, 401/417 re-authentication, ClientOptions
Credential policyThe host allowlist, loopback gateways, GROKBOT_ALLOW_LOCAL_GATEWAY
Agents, groups and team agentsListing, creating, updating and deleting bots; groups; team bots shared with you
Sending prompts and deliverysend_prompt, nonces, Delivery, promptAcceptanceStatus, waiting for replies
TranscriptsTail pages, beforeSeq paging, full history, threads, entry parsing, sanitizing
ApprovalsDetecting approval cards and resolving them (on a user’s decision only)
Workflows (skills)Listing, importing and deleting skills
Errors, limits and redactionError variants, delivery mapping, timeouts, size caps, secret redaction
Desktop sessionThe opt-in desktop-session feature: reading the desktop app’s saved login
Wire protocolEndpoints, 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-deps

The 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
  • reqwest client 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.
desktopdesktop-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.
AgentProfile
An updateAgent profile. name and description are always sent; None fields 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.
ClientOptions
Settings for Client, ensure_sandbox and grokbot_service_call.
CreateAgent
A createAgent request (sent with origin: "user").
CreateGroup
A createGroup request.
Entry
One transcript entry: a user prompt, a bot reply, a tool event, an approval card, …
ImportResult
The result of importAgentWorkflowText.
Policy
Which URLs may receive credentials.
SendPrompt
A sendPrompt request.
SendReceipt
The receipt for a sendPrompt call. Replies arrive later in the transcript.
Session
A gateway connection: base URL, bearer token and extra headers.
SkippedImport
A workflow the server declined to import.
TeamAgent
One agent from the Cursor backend’s GrokBotService/ListGrokBotTeamAgents: your own agents plus team agents shared with you (which the box gateway’s listAgents omits).
Transcript
A page of transcript entries (getAgentTranscriptTail), a walked history (Client::transcript_history) or a thread (getAgentThread).
Workflow
A workflow (“skill”) from getAgentWorkflows.

Enums§

AcceptanceStatus
Result of promptAcceptanceStatus, mirroring the desktop app’s mapping: {outcome: "not-found" | "unknown-durability"} or {outcome: "found", record: {status: "accepted" | "rejected" | "pending", rejectionCode?}}.
ApprovalKind
Which resolve method an Approval needs.
AutoReviewResolution
A resolveAutoReviewApproval decision.
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.
LocalToolResolution
A resolveLocalToolPermission decision.

Constants§

ALLOW_LOCAL_ENV
Environment variable read by Policy::from_env: 1, true or yes allows 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’s SAND_CLIENT_TYPE).
DEFAULT_CLIENT_VERSION
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).
DEFAULT_SANDBOX_NAMESPACE
Default x-sand-box-namespace for 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_text rejects 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 \n and \t) so server text cannot drive the terminal.

Type Aliases§

Result
Shorthand for std::result::Result<T, grokbot_api::Error>.