# Bellona API Documentation

Bellona provides two categories of interfaces: **REST-like service APIs** for
build orchestration, rendering, and caching, and **WebSocket bridge protocols**
for real-time engine integration with Unity, Unreal Engine, Godot, and Blender.

---

## Service Overview

| Service          | Type      | Port | Protocol  | Description                                                              |
| ---------------- | --------- | ---- | --------- | ------------------------------------------------------------------------ |
| Build API        | Service   | 4005 | Event Bus | Build caching, job queuing, cross-domain events                          |
| Render API       | Service   | -    | Internal  | GPU render caching, output validation                                    |
| Bridge - Blender | WebSocket | 9001 | WS        | Blender scene, mesh, render, and material commands                       |
| Bridge - Godot   | WebSocket | 9002 | WS        | Godot scene tree, node, resource, and script commands                    |
| Bridge - Unreal  | WebSocket | 9003 | WS        | Unreal actor, level, blueprint, and sequencer commands                   |
| Bridge - Unity   | WebSocket | 9004 | WS        | Unity GameObject, scene, animation, and physics commands                 |
| CLI              | CLI       | -    | -         | `bellona-cli` with build, export, sync, config, health, project commands |

---

## Build API (Port 4005)

The Build API is an event-driven service (not a traditional HTTP REST server).
It listens for cross-domain events via the `@oshun/event-bus` Redis pub/sub
system and manages build/export job queues with content-addressable caching.

### Architecture

- **Event Bus**: Redis-backed pub/sub for cross-domain communication (source
  domain: `bellona`, key prefix: `oshun:events`)
- **Build Cache**: Content-addressable artifact caching with Redis backend
  - Memory cache: 100MB (configurable via `BUILD_CACHE_MEMORY_SIZE`)
  - Max cache: 10GB (configurable via `BUILD_CACHE_MAX_SIZE`)
  - Supports compression, deduplication, and pub/sub invalidation
- **Job Queues**: Build and export queues (in-memory in dev, Redis/Bull in
  production)

### Event Handlers

The Build API subscribes to cross-domain events and processes them:

| Event Source | Event Type                | Action                              |
| ------------ | ------------------------- | ----------------------------------- |
| Hathor       | `hathor:world-published`  | Enqueues build job for world export |
| Isis         | `isis:asset-generated`    | Enqueues build job for asset baking |
| Yemaya       | `yemaya:build-requested`  | Enqueues build job                  |
| Yemaya       | `yemaya:export-requested` | Enqueues export job                 |

### Programmatic API

The Build API exports a programmatic interface rather than HTTP endpoints:

```typescript
import {
  initialize,
  shutdown,
  getCacheService,
  isHealthy,
  getHealthStatus,
} from '@bellona/build-api';

// Initialize the service
await initialize();

// Check health
const health = await getHealthStatus();
// { status: 'healthy' | 'degraded' | 'unhealthy', cache: boolean, uptime: number, cacheStats?: {...} }

// Access cache service
const cache = getCacheService();
const stats = await cache.getStats();
// { hitRate, totalEntries, totalSize, byType, byPlatform, ... }

// Graceful shutdown
await shutdown();
```

### Build Job Types

| Job Type            | Description                                     |
| ------------------- | ----------------------------------------------- |
| `asset-bake`        | Process raw assets into engine-specific formats |
| `shader-compile`    | Compile shaders for target graphics API         |
| `texture-compress`  | Compress textures with format/quality options   |
| `mesh-optimize`     | Optimize meshes with Draco compression, LOD     |
| `audio-transcode`   | Transcode audio to target format/bitrate        |
| `animation-process` | Process animations with keyframe optimization   |
| `project-generate`  | Generate engine project files                   |
| `package-export`    | Package and export build artifacts              |
| `validation`        | Validate build inputs and outputs               |

### Build Job Statuses

| Status      | Description                               |
| ----------- | ----------------------------------------- |
| `pending`   | Job created, not yet queued               |
| `queued`    | Job added to processing queue             |
| `cache-hit` | Output found in content-addressable cache |
| `running`   | Job currently being processed             |
| `completed` | Job finished successfully                 |
| `failed`    | Job failed with error                     |
| `cancelled` | Job was cancelled                         |

### Supported Platforms

| Platform      | Engines                      |
| ------------- | ---------------------------- |
| `windows`     | Unity, Unreal, Godot, Native |
| `macos`       | Unity, Unreal, Godot, Native |
| `linux`       | Unity, Unreal, Godot, Native |
| `ios`         | Unity, Unreal                |
| `android`     | Unity, Unreal, Godot         |
| `webgl`       | Unity, Godot, Web            |
| `playstation` | Unity, Unreal                |
| `xbox`        | Unity, Unreal                |
| `switch`      | Unity, Unreal                |
| `universal`   | All                          |

### Artifact Types

| Type                | Description                                        |
| ------------------- | -------------------------------------------------- |
| `texture`           | Compressed textures (KTX2, Basis, DDS, ASTC, ETC2) |
| `mesh`              | Optimized meshes (glTF, GLB, FBX, USD)             |
| `shader`            | Compiled shaders (SPIR-V, HLSL, Metal, WGSL)       |
| `audio`             | Transcoded audio (MP3, OGG, WAV, FLAC, Opus)       |
| `animation`         | Processed animations                               |
| `material`          | Baked material definitions                         |
| `prefab`            | Engine prefab/blueprint assets                     |
| `scene`             | Full scene exports                                 |
| `project`           | Generated engine project files                     |
| `package`           | Complete export packages                           |
| `validation-report` | Validation results                                 |

### Error Codes

| Code                  | Description                                                     |
| --------------------- | --------------------------------------------------------------- |
| `BUILD_NOT_INIT`      | Service not initialized (call `initialize()` first)             |
| Error in `BuildError` | Structured error with `code`, `message`, `retryable`, `details` |

### Configuration

| Environment Variable      | Default                  | Description                       |
| ------------------------- | ------------------------ | --------------------------------- |
| `REDIS_URL`               | `redis://localhost:6379` | Redis connection URL              |
| `BUILD_CACHE_MEMORY_SIZE` | `104857600` (100MB)      | In-memory cache size in bytes     |
| `BUILD_CACHE_MAX_SIZE`    | `10737418240` (10GB)     | Maximum total cache size in bytes |

---

## Render API

The Render API provides GPU render job caching and output validation. Like the
Build API, it is a service-oriented module rather than a traditional HTTP
server.

### Programmatic API

```typescript
import {
  initialize,
  shutdown,
  getCacheService,
  isHealthy,
  getHealthStatus,
} from '@bellona/render-api';

await initialize();

const health = await getHealthStatus();
// { status: 'healthy' | 'degraded' | 'unhealthy', cache: boolean, uptime: number }

const cache = getCacheService();
// RenderCacheService with Redis-backed caching

await shutdown();
```

### Render Job Properties

| Property        | Type             | Description                  |
| --------------- | ---------------- | ---------------------------- |
| `id`            | `RenderJobId`    | Unique render job identifier |
| `engine`        | `RenderEngine`   | Rendering engine             |
| `outputFormat`  | `OutputFormat`   | Target output format         |
| `qualityPreset` | `QualityPreset`  | Quality setting              |
| `status`        | `RenderStatus`   | Current job status           |
| `progress`      | `RenderProgress` | Progress tracking            |

### Configuration

| Environment Variable | Default                  | Description          |
| -------------------- | ------------------------ | -------------------- |
| `REDIS_URL`          | `redis://localhost:6379` | Redis connection URL |

---

## WebSocket Bridge Protocol

All four engine bridges (Blender, Godot, Unreal, Unity) share the same
underlying protocol from `@bellona/bridge-core`. They communicate over WebSocket
connections using JSON-encoded command/response messages.

### Connection

```
ws://{host}:{port}/{engine-path}
```

| Engine  | Default URL                   | Environment Variables                        |
| ------- | ----------------------------- | -------------------------------------------- |
| Blender | `ws://localhost:9001/blender` | `BLENDER_BRIDGE_PORT`, `BLENDER_BRIDGE_HOST` |
| Godot   | `ws://localhost:9002/godot`   | `GODOT_BRIDGE_PORT`, `GODOT_BRIDGE_HOST`     |
| Unreal  | `ws://localhost:9003/unreal`  | `UNREAL_BRIDGE_PORT`, `UNREAL_BRIDGE_HOST`   |
| Unity   | `ws://localhost:9004/unity`   | `UNITY_BRIDGE_PORT`, `UNITY_BRIDGE_HOST`     |

### Message Protocol

All bridges use a request/response pattern with the following envelope:

**Request:**

```json
{
  "type": "command-type",
  "messageId": "unique-id",
  "data": { ... }
}
```

**Response:**

```json
{
  "type": "command-type:response",
  "messageId": "unique-id",
  "data": { ... },
  "error": null
}
```

### Common Commands (All Bridges)

| Command     | Description                   | Request                         | Response                                         |
| ----------- | ----------------------------- | ------------------------------- | ------------------------------------------------ |
| `handshake` | Establish connection identity | `{ clientName, clientVersion }` | `{ serverName, serverVersion, protocolVersion }` |
| `ping`      | Keep-alive / latency check    | `{}`                            | `{ timestamp }`                                  |

### Server Events

| Event           | Data                       | Description          |
| --------------- | -------------------------- | -------------------- |
| `connection`    | `{ connection: { id } }`   | New client connected |
| `disconnection` | `{ connectionId, reason }` | Client disconnected  |
| `command`       | `{ type, messageId }`      | Command received     |
| `error`         | `{ error }`                | Error occurred       |

---

## Unity Bridge Commands (Port 9004)

14 engine-specific commands for Unity Engine integration.

### Scene Management

| Command                | Request                                     | Response                                                                              | Description                      |
| ---------------------- | ------------------------------------------- | ------------------------------------------------------------------------------------- | -------------------------------- | ------------ |
| `unity:get-scene-info` | `{ includeGameObjects?, includeInactive? }` | `{ sceneName, scenePath, buildIndex, isLoaded, isDirty, rootCount, gameObjectCount }` | Get active scene info            |
| `unity:load-scene`     | `{ sceneName, mode: 'Single'                | 'Additive', async? }`                                                                 | `{ sceneName, success, error? }` | Load a scene |
| `unity:unload-scene`   | `{ sceneName }`                             | `{ sceneName, success }`                                                              | Unload a scene                   |

### GameObject Management

| Command                     | Request                                                             | Response                                      | Description              |
| --------------------------- | ------------------------------------------------------------------- | --------------------------------------------- | ------------------------ |
| `unity:create-game-object`  | `{ name, primitiveType?, position?, rotation?, scale?, parentId? }` | `{ instanceId, name, success }`               | Create a new GameObject  |
| `unity:destroy-game-object` | `{ instanceId, immediate? }`                                        | `{ instanceId, success }`                     | Destroy a GameObject     |
| `unity:instantiate-prefab`  | `{ prefabPath, position?, rotation?, parentId? }`                   | `{ instanceId, prefabPath, success, error? }` | Instantiate a prefab     |
| `unity:set-transform`       | `{ instanceId, position?, rotation?, scale?, local? }`              | `{ instanceId, success }`                     | Set transform properties |

### Component Management

| Command                        | Request                                      | Response                                                      | Description                 |
| ------------------------------ | -------------------------------------------- | ------------------------------------------------------------- | --------------------------- |
| `unity:add-component`          | `{ instanceId, componentType, properties? }` | `{ instanceId, componentType, componentId, success, error? }` | Add component to GameObject |
| `unity:set-component-property` | `{ componentId, property, value }`           | `{ componentId, property, success }`                          | Set component property      |

### Animation

| Command                        | Request                                                                      | Response                                 | Description                |
| ------------------------------ | ---------------------------------------------------------------------------- | ---------------------------------------- | -------------------------- | -------------------- | ---------------------------------------- | ---------------------- |
| `unity:play-animation`         | `{ instanceId, animationName, layer?, normalizedTime?, crossFadeDuration? }` | `{ instanceId, animationName, success }` | Play animation on Animator |
| `unity:set-animator-parameter` | `{ instanceId, parameterName, parameterType: 'bool'                          | 'int'                                    | 'float'                    | 'trigger', value? }` | `{ instanceId, parameterName, success }` | Set Animator parameter |

### Physics

| Command             | Request                                                             | Response                                                     | Description      |
| ------------------- | ------------------------------------------------------------------- | ------------------------------------------------------------ | ---------------- | ---------------------------- | ------------------------- | ------------------------ |
| `unity:apply-force` | `{ instanceId, force: {x,y,z}, mode: 'Force'                        | 'Impulse'                                                    | 'VelocityChange' | 'Acceleration', relative? }` | `{ instanceId, success }` | Apply force to Rigidbody |
| `unity:raycast`     | `{ origin: {x,y,z}, direction: {x,y,z}, maxDistance?, layerMask? }` | `{ hits: [{instanceId, point, normal, distance}], success }` | Physics raycast  |

### Messaging

| Command              | Request                                                    | Response                              | Description                |
| -------------------- | ---------------------------------------------------------- | ------------------------------------- | -------------------------- |
| `unity:send-message` | `{ instanceId, methodName, parameter?, requireReceiver? }` | `{ instanceId, methodName, success }` | Send message to GameObject |

---

## Unreal Engine Bridge Commands (Port 9003)

11 engine-specific commands for Unreal Engine integration.

### World and Level Management

| Command                 | Request                                              | Response                                                                                  | Description            |
| ----------------------- | ---------------------------------------------------- | ----------------------------------------------------------------------------------------- | ---------------------- |
| `unreal:get-world-info` | `{ includeActors?, includeLevels? }`                 | `{ worldName, mapName, gameMode, playerCount, actorCount, streamingLevels, timeSeconds }` | Get world info         |
| `unreal:load-level`     | `{ levelName, makeVisibleAfterLoad?, blockOnLoad? }` | `{ levelName, success, error? }`                                                          | Load streaming level   |
| `unreal:unload-level`   | `{ levelName }`                                      | `{ levelName, success }`                                                                  | Unload streaming level |

### Actor Management

| Command                     | Request                                                                              | Response                                             | Description          |
| --------------------------- | ------------------------------------------------------------------------------------ | ---------------------------------------------------- | -------------------- |
| `unreal:spawn-actor`        | `{ className, location: {x,y,z}, rotation?: {pitch,yaw,roll}, scale?, properties? }` | `{ actorId, actorName, className, success, error? }` | Spawn actor in world |
| `unreal:destroy-actor`      | `{ actorId }`                                                                        | `{ actorId, success }`                               | Destroy actor        |
| `unreal:set-actor-property` | `{ actorId, property, value }`                                                       | `{ actorId, property, success }`                     | Set actor property   |

### Blueprint Execution

| Command                          | Request                                  | Response                                                  | Description             |
| -------------------------------- | ---------------------------------------- | --------------------------------------------------------- | ----------------------- |
| `unreal:call-blueprint-function` | `{ actorId, functionName, parameters? }` | `{ actorId, functionName, returnValue, success, error? }` | Call Blueprint function |

### Materials and Rendering

| Command                         | Request                                                           | Response                        | Description         |
| ------------------------------- | ----------------------------------------------------------------- | ------------------------------- | ------------------- | ------------------------------------- | --------------------------------------------------- | ---------------------- |
| `unreal:set-material-parameter` | `{ actorId, materialIndex, parameterName, parameterType: 'scalar' | 'vector'                        | 'texture', value }` | `{ actorId, parameterName, success }` | Set material parameter                              |
| `unreal:sequencer-control`      | `{ sequenceName, action: 'play'                                   | 'pause'                         | 'stop'              | 'scrub', time?, playRate? }`          | `{ sequenceName, currentTime, isPlaying, success }` | Control level sequence |
| `unreal:take-screenshot`        | `{ filename?, showUI?, resolution?: {width, height} }`            | `{ filepath, success, error? }` | Take screenshot     |

### Console

| Command                          | Request       | Response                       | Description             |
| -------------------------------- | ------------- | ------------------------------ | ----------------------- |
| `unreal:execute-console-command` | `{ command }` | `{ command, output, success }` | Execute console command |

---

## Godot Bridge Commands (Port 9002)

9 engine-specific commands for Godot Engine integration. Commands follow Godot's
scene tree and node-based architecture.

Key commands include scene tree management (`godot:get-scene-tree`), node
creation/destruction, resource loading, signal handling, and GDScript execution.
See the bridge source at `apps/bellona/bridge-godot/src/main.ts` for the
complete command definitions.

---

## Blender Bridge Commands (Port 9001)

6 commands for Blender integration, plus cross-domain event publishing for
generated assets. Commands include scene management, mesh operations, render
control, and material management. See the bridge source at
`apps/bellona/bridge-blender/src/main.ts` for complete command definitions.

---

## Authentication

The Build API and Render API do not expose HTTP endpoints and therefore do not
implement HTTP-based authentication. They are internal services that communicate
via the Redis event bus.

The WebSocket bridges currently accept unauthenticated connections. In
production, authentication should be implemented at the connection level via the
`handshake` command or a reverse proxy.

---

## Error Response Format

All WebSocket bridge errors use the following format in the response envelope:

```json
{
  "type": "command-type:response",
  "messageId": "unique-id",
  "data": null,
  "error": {
    "code": "ERROR_CODE",
    "message": "Human-readable error description"
  }
}
```

Build API errors use the `BuildError` type:

```typescript
interface BuildError {
  code: string;
  message: string;
  stack?: string;
  retryable: boolean;
  details?: Record<string, unknown>;
}
```

---

## CLI Commands

The `bellona-cli` provides command-line access to Bellona services:

| Command   | Description                                  |
| --------- | -------------------------------------------- |
| `build`   | Submit and manage build jobs                 |
| `export`  | Export packages for target platforms/engines |
| `sync`    | Synchronize assets with engine projects      |
| `config`  | View and update CLI configuration            |
| `health`  | Check service health status                  |
| `project` | Manage engine project configurations         |

Usage: `bellona-cli <command> [options]`

---

## Related Documentation

- [Bellona Domain Overview](../README.md) -- Full app and library inventory
- [Bellona Architecture](../architecture.md) -- System design and data flow
- [Cross-Domain Integration](../../../cross-domain-integration.md) -- Event bus
  patterns
