> ## Documentation Index
> Fetch the complete documentation index at: https://docs.runlayer.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Grok Bot

> Requirements and limitations for configuring monitor-only Grok Bot cloud hooks.

Grok Bot runs work on a cloud computer. The desktop and iOS apps are control
surfaces, so they do not inherit AI Watch binaries, MDM settings, or the local
Grok CLI hooks under `~/.grok`. [AI Watch Detect](https://docs.runlayer.com/shadow-ai/detect/index.md)
still reports the desktop app as an installed client on macOS, Windows, and
Linux; the hooks below are what give you visibility into the sessions.

> [!WARNING]
>
> Grok Bot monitoring is experimental and disabled by default. Enabling it in
> Runlayer does not install anything on Grok's cloud computer. You must configure
> a cloud hook helper and a dedicated organization API key separately.
>
> Native tool hooks have been verified through an HTTPS tunnel to a local Runlayer
> stack, including paired input/output, tool failures, opt-out, and key revocation.
> A central installation through Enterprise Team Setup and Team Secrets has also
> recorded native tool activity in a production tenant for a one-member pilot group.
> Our tested native runtime emits empty Bot IDs. Runlayer groups these events by
> tool call when Grok provides a valid `tool_use_id`, but cannot reconstruct the
> Bot's conversation. Verify recorded activity in your environment before relying
> on coverage.

This integration is **monitor-only**: the collector cannot block tools, enforce
MCP policy, read Runlayer data, or administer your workspace.
On the monitor-only path, AgentGuard behavioral threat scoring can only alert,
never block. A **Monitored** badge confirms the recording mode, not a completed
threat scan.

## Choose a setup path

* **Organization rollout:** on Enterprise, use [Central Grok Bot setup](https://docs.runlayer.com/shadow-ai/grok-bot-central-setup.md).
  Team Setup installs the helper and Team Secrets delivers the key to every
  member's cloud computer, with no per-member key entry.
* **Single-user pilot:** follow the steps below on one member's cloud computer.
  These steps do not deploy monitoring to other members. Without Enterprise,
  repeat them for each member.

## Before configuring

* A Runlayer administrator must create a key with only **Grok Bot Hooks** access.
* A Grok administrator or user must be able to install and register command hooks
  on the cloud computer. Local AI Watch installation does not perform this step.
* The hook process must receive the key securely, either as the
  `RUNLAYER_GROK_BOT_HOOK_KEY` secret or from the key file that central setup
  writes, and reach your Runlayer tenant over HTTPS.
* Conversation grouping requires a stable Bot ID. Tool-only monitoring requires
  a nonempty `tool_use_id` that matches across a call's pre/post hooks and differs
  between calls. A shared computer ID is insufficient.

[Cursor's Team Setup](https://cursor.com/docs/grok-bot/teams) and Team Secrets
are Enterprise only. Availability of Grok Bot on a Teams plan does not imply
access to them.

## Session identity

Runlayer groups a Bot's activity into one session across turns. Supply the real
Bot ID in `conversation_id`; it takes precedence over `session_id`. The Sessions
list and drawer use that ID as the session name. If `conversation_id` is absent,
the collector retains `session_id` for compatibility.

The helper forwards Grok's identifiers unchanged. When `conversation_id` and
`session_id` are missing or blank, Runlayer accepts `preToolUse`, `postToolUse`,
and `postToolUseFailure` events with a valid, nonblank `tool_use_id`.
It derives an internal activity ID from the authenticated organization, hook API
key, and tool-use ID. A call's pre/post events appear together; different calls
appear separately, including calls in the same Bot. Rotating the hook key changes
this grouping boundary.

These entries are labeled **Grok tool activity — Bot unknown**. The provider Bot
ID stays missing. Tool input/output can be recorded, but conversation
history, Bot attribution, and cross-call context remain unavailable. This does not
provide complete conversation monitoring.

Events without either a provider session identifier or an eligible tool-use ID
receive HTTP 422. Lifecycle and prompt events still require a provider session
identifier. Do not substitute a shared cloud-computer ID or a random ID in the
helper: different Bots can run on the same computer.

[Cursor's telemetry documentation](https://cursor.com/docs/enterprise/opentelemetry-export#joining-sessions)
identifies a Bot with `cursor.conversation.id` and a turn with
`cursor.grok_bot.turn.id`. Those are Enterprise export fields; the hook helper
does not consume OTLP exports.

## 1. Create a scoped key

In Runlayer, go to **Settings → Organization API Keys**, create a key with only
the **Grok Bot Hooks** permission, and copy it when shown. Runlayer stores only
its hash.

The key belongs to the helper running on Grok's cloud computer, not the Mac
running AI Watch. Do not commit it to a repository, paste it into Bot chat, or
use an AI Watch organization key or Agent Account secret.

[Grok Bot Secrets](https://cursor.com/help/grok-bot/secrets) provides a secure
**Secrets → Add secret** flow with an environment-variable name. Inside a Bot,
you can also request a secure secret-entry card for
`RUNLAYER_GROK_BOT_HOOK_KEY`; paste the key into that card, never the chat input.

Check credential availability in the actual hook process. In our native test,
the secure card confirmed **Saved** and native pre/post hooks reported the named
environment variable present, while ordinary Shell processes reported it absent.
A Shell check therefore does not establish whether hooks receive the key.

Variable presence alone does not prove that the credential is valid. Our native
pre/post hooks authenticated with the saved key and recorded paired tool activity
on the local stack despite empty Bot IDs. Revoking the key made subsequent native
hooks return HTTP 401 while the tool still ran. Verify authenticated delivery and
the applicable identity mode below without printing or exposing the key.

## 2. Add the hook helper

Create `~/.grokbot/runlayer_hook.py` on the Grok cloud computer. Replace
the hostname in `COLLECTOR_URL` with your Runlayer tenant hostname. Keep the full
HTTPS URL literal so repository content cannot redirect the credential.

```python theme={null}
#!/usr/bin/env python3
import os
import sys
import time
import urllib.error
import urllib.request
import uuid

COLLECTOR_URL = "https://YOUR-TENANT.runlayer.com/api/v1/hooks/grok-bot/events"
MAX_PAYLOAD_BYTES = 256 * 1024
ALLOW = '{"permission":"allow"}'
KEY_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "runlayer_hook.key")


class NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None


def deliver(payload: bytes, key: str) -> None:
    delivery_id = str(uuid.uuid4())
    request = urllib.request.Request(
        COLLECTOR_URL,
        data=payload,
        method="POST",
        headers={
            "Content-Type": "application/json",
            "X-Runlayer-Delivery-ID": delivery_id,
            "x-runlayer-api-key": key,
        },
    )
    opener = urllib.request.build_opener(NoRedirect)
    for attempt, delay in enumerate((0, 0.2, 0.8)):
        if delay:
            time.sleep(delay)
        try:
            with opener.open(request, timeout=2) as response:
                if 200 <= response.status < 300:
                    return
        except urllib.error.HTTPError as error:
            if error.code < 500 and error.code != 429:
                return
            if attempt == 2:
                return
        except (urllib.error.URLError, TimeoutError):
            if attempt == 2:
                return


def read_key() -> str:
    try:
        with open(KEY_FILE, encoding="utf-8") as key_file:
            key = key_file.read().strip()
    except OSError:
        key = ""
    return key or os.environ.get("RUNLAYER_GROK_BOT_HOOK_KEY", "")


def main() -> int:
    try:
        payload = sys.stdin.buffer.read(MAX_PAYLOAD_BYTES + 1)
        key = read_key()
        if key and len(payload) <= MAX_PAYLOAD_BYTES:
            deliver(payload, key)
    except Exception:
        pass
    sys.stdout.write(ALLOW)
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
```

The helper reuses one delivery ID across transient retries, never logs the key
or payload, and always returns Grok Bot's explicit allow response. A Runlayer
outage therefore cannot block or change a Bot run.

The helper first reads the key from `runlayer_hook.key` in its own directory,
which [central setup](https://docs.runlayer.com/shadow-ai/grok-bot-central-setup.md) writes from a Team
Secret. Without that file, it uses the `RUNLAYER_GROK_BOT_HOOK_KEY` secret.

## 3. Register cloud hooks

Our native probe loaded command hooks from `~/.cursor/hooks.json` on the Grok
cloud computer. Preserve existing hooks when adding this configuration. Replace
`/ABSOLUTE/PATH/TO/runlayer_hook.py` in every command below with the helper's full
path on that computer. A relative path can break when a Bot changes directories.

This file is shared by the user's Bots because they share one cloud computer.
Register the hooks before creating the test Bots, then verify that a native action
invokes the intended helper. The tested executor holds hook configuration in
memory, so file presence alone does not prove which registration is active.
Our native probe observed `preToolUse`, `postToolUse`, and `postToolUseFailure`
(for a nonzero Shell exit). Registering lifecycle hooks does not guarantee that
this runtime emits them.

Runlayer supports exactly the configured events below. This list defines the
integration contract; it is not a claim that every Grok Bot version emits every
event during every run. Other event names are rejected by the collector.

```json theme={null}
{
  "version": 1,
  "hooks": {
    "sessionStart": [{ "command": "python3 /ABSOLUTE/PATH/TO/runlayer_hook.py", "timeout": 3, "failClosed": false }],
    "sessionEnd": [{ "command": "python3 /ABSOLUTE/PATH/TO/runlayer_hook.py", "timeout": 3, "failClosed": false }],
    "beforeSubmitPrompt": [{ "command": "python3 /ABSOLUTE/PATH/TO/runlayer_hook.py", "timeout": 3, "failClosed": false }],
    "afterAgentThought": [{ "command": "python3 /ABSOLUTE/PATH/TO/runlayer_hook.py", "timeout": 3, "failClosed": false }],
    "preToolUse": [{ "command": "python3 /ABSOLUTE/PATH/TO/runlayer_hook.py", "timeout": 3, "failClosed": false }],
    "postToolUse": [{ "command": "python3 /ABSOLUTE/PATH/TO/runlayer_hook.py", "timeout": 3, "failClosed": false }],
    "postToolUseFailure": [{ "command": "python3 /ABSOLUTE/PATH/TO/runlayer_hook.py", "timeout": 3, "failClosed": false }],
    "subagentStart": [{ "command": "python3 /ABSOLUTE/PATH/TO/runlayer_hook.py", "timeout": 3, "failClosed": false }],
    "subagentStop": [{ "command": "python3 /ABSOLUTE/PATH/TO/runlayer_hook.py", "timeout": 3, "failClosed": false }],
    "afterAgentResponse": [{ "command": "python3 /ABSOLUTE/PATH/TO/runlayer_hook.py", "timeout": 3, "failClosed": false }],
    "stop": [{ "command": "python3 /ABSOLUTE/PATH/TO/runlayer_hook.py", "timeout": 3, "failClosed": false }],
    "preCompact": [{ "command": "python3 /ABSOLUTE/PATH/TO/runlayer_hook.py", "timeout": 3, "failClosed": false }]
  }
}
```

## 4. Enable and verify

In **Settings → Agent session monitoring → Cloud agent hooks**, explicitly enable
**Grok Bot** and save. The **Full session scanning APIs** master switch must also
be enabled. These controls accept events; they do not deploy the helper or key.

Verify the complete path with native Grok Bot actions:

1. Confirm the hook executes on the cloud computer and receives its credential
   without logging the value.
2. Inspect only identity metadata: either a nonempty Bot/session ID, or a nonempty
   `tool_use_id` matching across pre/post hooks. Confirm authenticated upload
   succeeds. Do not insert a synthetic ID to pass this check.
3. Open **Sessions**, filter for **Grok Bot**, and find the native action. With a
   provider ID, verify the Bot ID label. Without one, verify **Grok tool activity —
   Bot unknown**, paired input/output, and available scan results.
4. Run another call in that Bot, then a second Bot. With provider IDs, the first
   Bot's turns stay together and the second Bot appears separately. In tool-only
   mode, each call gets a separate entry and its pre/post events stay together.

Manual requests with invented IDs verify the collector contract only. They do
not verify a customer's Grok installation.

| Symptom | Check |
| - | - |
| Helper never runs | Register hooks before creating the test Bots and verify native invocation. Existing Bots may retain older hook configuration. |
| No upload | The helper silently skips delivery if its key is absent. Confirm credential availability in the hook process. |
| HTTP 401 or 403 | Key validity and the exclusive **Grok Bot Hooks** permission. |
| HTTP 422 | Payload shape; a nonblank `conversation_id` or `session_id`, or an eligible tool event with a valid `tool_use_id` (at most 255 characters). The helper cannot recover a missing Bot ID. |
| Many entries labeled Bot unknown | Native hooks lack Bot identity. Each entry groups one tool call; this is partial monitoring. |
| Upload succeeds but no session | Grok Bot opt-in, the master switch, and the tenant hostname. An allow response alone does not prove ingestion. |

For cleanup, revoke the test key and disable Grok Bot in Runlayer. Removing the
hook configuration may leave cached runners referencing the helper. Keep an
allow-only helper at that path until hook unloading is verified, then remove it.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.