# CmdrBridge reference

> Every configuration field and public function of the CmdrBridge module, its lifecycle from registration to shutdown, and every result it can report.

This is the complete public API of the `CmdrBridge` module, version `1.0.0`. Most games never call it directly: `Analytics:Start` starts the bridge when you pass `Cmdr` (see [the overview](https://docs.bloxlytics.app/sdk/cmdr-bridge)). The wire protocol is documented in the API reference under [hello](https://docs.bloxlytics.app/api/bridge/hello), [poll](https://docs.bloxlytics.app/api/bridge/poll), [result](https://docs.bloxlytics.app/api/bridge/result) and [bye](https://docs.bloxlytics.app/api/bridge/bye).

```luau
local CmdrBridge = require(game.ServerScriptService.Analytics.CmdrBridge)
```

## Configuration

`CmdrBridge:Init` takes one table. When you use `Analytics:Start`, it builds this table from your `Start` configuration, as shown in the last column.

| Field | Type | Default | Meaning | From `Start` |
| --- | --- | --- | --- | --- |
| `Cmdr` | Cmdr server module | required | Your server Cmdr module. Must have `Registry` and `Dispatcher`. | `Cmdr` |
| `BridgeKey` | `string` or `Secret` | required | The project's bridge key. As a string it must start with `bxb_`. | `BridgeKey` |
| `ApiUrl` | `string` | required | `https://api.bloxlytics.app`. Must start with `http://` or `https://`; trailing slashes are removed. | `ApiUrl` |
| `ProjectID` | `string` or `number` | `game.GameId` | The Universe ID. Same rules as [analytics](https://docs.bloxlytics.app/sdk/configuration#project-id). | `ProjectID` |
| `Analytics` | the `Analytics` module | none | Shares the analytics server id and server tags, and reports the bridge in heartbeats. | the module itself |
| `AllowedGroups` | `{ string }` | all groups | Cmdr groups Bloxlytics may run. Exact, case-sensitive; commands with no group are refused when set. | `AllowedGroups` |
| `AllowSystemCommands` | `boolean` | `true` | `false`: Cmdr commands only run as the sender's own player, when they are in this server. | `AllowSystemCommands` |
| `AllowKick` | `boolean` | `true` | `false` refuses kicks and stops advertising the `kick` capability. | `AllowKick` |
| `OnWarn` | `(Player, string) -> ()` | none | Called with the player and the message to show a warning. Enables the `warn` capability. | `OnWarn` |
| `OnAnnounce` | `(string) -> ()` | none | Called with the message to show an announcement. Enables the `announce` capability. | `OnAnnounce` |
| `EnableInStudio` | `boolean` | `true` | `false` keeps the bridge off in Studio. | `EnableBridgeInStudio ~= false` |
| `Debug` | `boolean` | `false` | Print registration, polling and each command's outcome, prefixed `[Bloxlytics bridge]`. | `Debug` |

`OnWarn` and `OnAnnounce` run inside `pcall`, on the bridge's thread. If they error, the command fails with the error as its message. They may yield, but the bridge waits for them before running the next command.

### Configuration checks

`Init` checks, in order, and stops at the first problem with `[Bloxlytics bridge] Not started: <problem>. Remote commands are off.`:

| Check | Problem |
| --- | --- |
| Running on the server | `it must run on the server` |
| A table was passed | `pass a configuration table` |
| `Cmdr` is a table with `Registry` and `Dispatcher` | `pass the server Cmdr module as Cmdr` |
| `ProjectID` resolves | The same messages as analytics, for example `this place isn't published, so it has no Universe ID yet; …` |
| `BridgeKey` is a string starting with `bxb_` | `BridgeKey must start with bxb_ (use the bridge key, not the write key)` |
| `BridgeKey` is otherwise a `Secret` | `BridgeKey must be a string or a Secret from HttpService:GetSecret` |
| `ApiUrl` starts with `http://` or `https://` | `ApiUrl is required` |

A second call warns `Init called twice; ignoring the second call`. Like `Analytics:Init`, it changes `ApiUrl` and `ProjectID` in the table you passed.

## Functions

### Init

```luau
CmdrBridge:Init(config: Config): boolean
```

Starts the bridge. Never throws and never yields: registration and polling run on a new thread.

- `config` (table, body, required): The fields above.

- `returns` (boolean): `true` when the configuration is usable (including in Studio with `EnableInStudio = false`, where the bridge then stays off). `false` when a check failed or `Init` was already called. A `true` result doesn't mean registration succeeded: that happens a few seconds later.

```luau
local HttpService = game:GetService("HttpService")
local Cmdr = require(game.ServerScriptService.Cmdr)
local Analytics = require(game.ServerScriptService.Analytics)
local CmdrBridge = require(game.ServerScriptService.Analytics.CmdrBridge)

CmdrBridge:Init({
	Cmdr = Cmdr,
	Analytics = Analytics,
	BridgeKey = HttpService:GetSecret("bloxlytics_bridge_key"),
	ApiUrl = "https://api.bloxlytics.app",
	AllowedGroups = { "Admin", "DefaultAdmin" },
	AllowKick = true,
	OnWarn = function(player: Player, message: string)
		-- show the warning with your own UI
	end,
	OnAnnounce = function(message: string)
		-- show the announcement to everyone
	end,
	AllowSystemCommands = true,
	EnableInStudio = true,
	Debug = false,
})
```

### IsPlatformContext

```luau
CmdrBridge.IsPlatformContext(context: any): boolean
```

Returns `true` when a Cmdr context was created by the bridge **in the system context**: `context.Executor` is `nil` and `context.Data.Bloxlytics` is a table. Use it in BeforeRun hooks. Note the dot: it is a plain function, not a method. It doesn't need the bridge to be started.

- `context` (CommandContext, body, required): The context your hook receives.

- `returns` (boolean): `true` for system-context commands from Bloxlytics. `false` for everything else, including Bloxlytics commands running as the sender's player.

```luau
Cmdr.Registry:RegisterHook("BeforeRun", function(context)
	if CmdrBridge.IsPlatformContext(context) then
		-- context.Data.Bloxlytics = { Id, Name, Role, ExecutionId }
		return nil
	end
	-- your in-game checks
	return nil
end)
```

### Version

- `CmdrBridge.Version` (string): The module's version, `"1.0.0"`. Sent when the server registers.

## Lifecycle

### Start-up

1. `Init` checks the configuration. In Studio with `EnableInStudio = false` it stops here.
2. It binds a `game:BindToClose` handler for the [shutdown](#shutdown).
3. On a new thread, it waits **3 seconds**, so your game can finish registering Cmdr commands, then [registers](#registration).
4. If registration fails, it tries again after 5 seconds, then 10, 20, 40, 80 and every 120 seconds, until it succeeds.
5. If Bloxlytics answers that the project's **Cmdr bridge** switch is off, the bridge stops for the life of this server. It doesn't poll and won't start later.
6. Otherwise it starts [polling](#polling). In Studio it prints `Listening for commands as Studio server "studio-…". Pick it in Bloxlytics to target this session.`

### Server id

The bridge identifies its server with `Analytics.ServerKey` when you pass `Analytics` (which `Start` always does), so commands, heartbeats and live presence refer to the same server. Without it, it uses `game.JobId`, or in Studio its own `studio-` key.

### Registration

`POST /v1/bridge/hello` sends:

- the protocol version (`1`), the bridge version, the server id and `game.PlaceId`;
- the **capabilities**: always `cmdr`, `presence` and `executor`; `kick` unless `AllowKick = false`; `warn` with `OnWarn`; `announce` with `OnAnnounce`;
- the **command catalogue** from `Cmdr.Registry:GetCommands()`: each command's name, aliases, description (cut to 512 characters), group, arguments and whether `AllowedGroups` allows it. Each argument has a name, a type (the type name, or the type's `DisplayName`, or `custom`), a description (cut to 256 characters), whether it is optional and its default when that is a string, number or boolean. Arguments defined by a function are sent as `dynamic`;
- `allowSystemCommands`, whether this is Studio, and the current server tags.

The response says whether the bridge is enabled for the project. The bridge passes that to the analytics module, so heartbeats report `bridge = true` only while it is enabled.

The bridge **re-registers every 5 minutes** while polling, so commands registered later, and changes to the switch, are picked up. A re-registration that finds the switch off makes heartbeats report `bridge = false`, but the server keeps polling.

> **Note:** The API accepts at most 500 commands per server, 20 aliases and 32 arguments per command. A catalogue over those limits fails to register.

### Polling

`POST /v1/bridge/poll` reports the server id, `game.PlaceId`, the user ids of everyone in the server, the server tags and whether this is Studio. Bloxlytics uses the player list to send commands about a player to that player's server, and to run commands as their sender.

The API holds each poll open for up to **20 seconds**, returning as soon as there are commands for this server or for any server (this server's own first, up to 10 at a time). An empty answer starts the next poll at once.

If a poll fails, the bridge waits 2 seconds, then 4, 8, 16, 32 and at most 60, resetting after a success.

### Running commands

Commands from one poll run **one after another**, in order. Before running each, the bridge checks:

1. it has a string id that hasn't run on this server in the last **10 minutes**;
2. its expiry hasn't passed by the server's clock (commands expire 60 seconds after they are sent).

Then, by kind:

| Kind | What happens | Output on success |
| --- | --- | --- |
| `cmdr` | The steps on [security](https://docs.bloxlytics.app/sdk/cmdr-bridge/security#hooks): lookup, `AllowedGroups`, executor, `AllowSystemCommands`, `Evaluate`, `Validate`, BeforeRun hooks, run. | Every `context:Reply` line, then the command's return value, joined by new lines; `Command executed.` if both are empty. |
| `kick` | Refused if `AllowKick = false`. Otherwise kicks the player with the message, or `You were removed from the server.` | `Kicked <Name>` |
| `warn` | Refused without `OnWarn`. Otherwise calls `OnWarn(player, message)`. | `Warned <Name>` |
| `announce` | Refused without `OnAnnounce`. Otherwise calls `OnAnnounce(message)`. | `Announced` |

The Bloxlytics dashboard currently sends `cmdr`, `kick` and `warn` commands; `announce` is part of the protocol but nothing in the dashboard sends it yet.

### Results

All results from one poll are sent together in one `POST /v1/bridge/result`. Each result has the command id, `ok`, the output or error (each cut to 4,000 characters), the time taken in milliseconds and, for Cmdr commands, the context: `player` or `system`. The result request isn't retried: if it is lost, the command shows as timed out in Bloxlytics after 75 seconds.

| Error | Cause |
| --- | --- |
| `Duplicate command ignored.` | This command id already ran on this server. |
| `Command expired before it reached the server.` | Its 60 seconds were up by the server's clock. |
| `Empty command.` | The command line was blank. |
| `"<name>" is not a registered command.` | No such command or alias in the server's Cmdr registry. |
| `The <group> group isn't allowed from Bloxlytics (AllowedGroups).` | The command's group isn't in `AllowedGroups`. |
| `This game only runs Bloxlytics commands as a team member who is in the server (AllowSystemCommands = false).` | No executor, and system commands are refused. |
| Cmdr's own parse or validation message | `Evaluate` or `Validate` failed, for example an unknown player name. |
| `Rejected by BeforeRun hook: <message>` | A BeforeRun hook returned a value. |
| The error raised by the command | The command errored while running. |
| `Kick is disabled in this game's bridge configuration.` | `AllowKick = false`. |
| `Player is not in this server.` | The kick or warning's target left. |
| `Warnings aren't configured in this game (OnWarn).` | No `OnWarn`. |
| `Announcements aren't configured in this game (OnAnnounce).` | No `OnAnnounce`. |
| The error raised by `OnWarn` or `OnAnnounce` | Your function errored. |
| `Unsupported command kind <kind>` | A kind this bridge version doesn't know. |

### Shutdown

The bridge's `BindToClose` handler stops the poll loop and sends `POST /v1/bridge/bye`. Bloxlytics marks the server as stopped and removes it from the live list straight away, instead of waiting for it to go quiet. A poll already in flight finishes on its own; no new poll starts after it.

### Requests

Every request is a `POST` with a JSON body and these headers:

| Header | Value |
| --- | --- |
| `Authorization` | `Bearer <bridge key>`, built with `Secret:AddPrefix` when the key is a `Secret`. |
| `X-Bloxlytics-Project` | The resolved Universe ID. |
| `X-Bloxlytics-Timestamp` | `os.time()` |
| `X-Bloxlytics-Nonce` | A new GUID per request. |

See [replay protection](https://docs.bloxlytics.app/sdk/cmdr-bridge/security#replay-protection).

## Types

```luau
type Config = {
	Cmdr: any,
	Analytics: any?,
	ProjectID: (string | number)?,
	BridgeKey: any, -- string or Secret
	ApiUrl: string,
	AllowedGroups: { string }?,
	AllowKick: boolean?,
	OnWarn: ((Player, string) -> ())?,
	OnAnnounce: ((string) -> ())?,
	AllowSystemCommands: boolean?,
	EnableInStudio: boolean?,
	Debug: boolean?,
}
```
