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

# Factorio Integration

> Game automation and RCON integration for Factorio

## Overview

The Factorio integration enables AIRI to interact with Factorio servers through the RCON (Remote Console) protocol. This allows for game automation, monitoring, and AI-driven factory management.

<Warning>
  The Factorio integration is maintained as a separate project: **airi-factorio**. Documentation here covers the integration architecture and setup overview.
</Warning>

## Features

* **RCON API Integration**: Execute Lua commands remotely
* **Game State Monitoring**: Track resources, production, and entities
* **Factory Automation**: AI-driven base building and optimization
* **Vision Model Integration**: Computer vision for factory analysis
* **Event-Driven Architecture**: React to game events in real-time
* **Plugin System**: Extend with custom automation scripts

## Architecture

The Factorio integration uses a modular architecture:

```mermaid theme={null}
graph TB
    subgraph "AIRI Core"
        Module[Factorio Module]
        SDK[Server SDK]
    end
    
    subgraph "airi-factorio Project"
        RCON[RCON Client]
        Vision[Vision Pipeline]
        Lua[Lua Scripts]
    end
    
    subgraph "Factorio Server"
        Game[Factorio Game]
        Mod[AIRI Mod]
    end
    
    Module --> SDK
    SDK --> RCON
    RCON --> Game
    Vision --> Game
    Lua --> Mod
```

## Prerequisites

* Factorio server (headless or GUI)
* RCON enabled on Factorio server
* Python 3.8+ (for vision pipeline)
* Node.js 18+ (for AIRI integration)
* AIRI server runtime

## Setup

### 1. Enable RCON on Factorio Server

Edit your Factorio server settings (`server-settings.json`):

```json theme={null}
{
  "name": "AIRI Factorio Server",
  "description": "Server with AIRI automation",
  "_comment_rcon": "RCON configuration",
  "rcon_port": 27015,
  "rcon_password": "your-secure-password"
}
```

Restart the Factorio server.

### 2. Configure AIRI Module

In your AIRI configuration (Stage UI or config file):

```typescript theme={null}
// Gaming Factorio Module Configuration
{
  enabled: true,
  rconHost: 'localhost',
  rconPort: 27015,
  rconPassword: 'your-secure-password',
  enableVision: true
}
```

From `packages/stage-ui/src/stores/modules/gaming-factorio.ts:1`:

```typescript theme={null}
import { createGamingModuleStore } from './gaming-module-factory'

export const useFactorioStore = createGamingModuleStore('factorio', 34197)
```

### 3. Clone airi-factorio Project

```bash theme={null}
git clone https://github.com/moeru-ai/airi-factorio.git
cd airi-factorio
```

### 4. Install Dependencies

```bash theme={null}
# Node.js dependencies
pnpm install

# Python dependencies (for vision)
pip install -r requirements.txt
```

### 5. Configure Environment

```bash theme={null}
cp .env.example .env
```

Edit `.env`:

```bash theme={null}
# Factorio RCON
FACTORIO_HOST=localhost
FACTORIO_RCON_PORT=27015
FACTORIO_RCON_PASSWORD=your-secure-password

# AIRI Connection
AIRI_WS_URL=ws://localhost:6121/ws
AIRI_TOKEN=your-airi-token

# Vision Model
VISION_MODEL=yolov8
VISION_CONFIDENCE=0.5

# LLM for reasoning
OPENAI_API_KEY=sk-...
OPENAI_MODEL=gpt-4o
```

### 6. Start the Integration

```bash theme={null}
pnpm start
```

## Usage

### Basic Commands

Send commands to AIRI through any connected interface (Discord, Telegram, etc.):

```
Check my Factorio factory status
Build a new iron smelting array
Optimize my copper production
Show me the pollution levels
Research military science
```

### RCON API

Execute raw Lua commands:

```typescript theme={null}
import { FactorioClient } from 'airi-factorio'

const client = new FactorioClient({
  host: 'localhost',
  port: 27015,
  password: 'your-secure-password'
})

// Execute command
await client.send('/c game.print("Hello from AIRI!")')

// Get game state
const players = await client.send('/players')
const time = await client.send('/time')
```

### Vision Analysis

The vision pipeline can analyze factory screenshots:

```python theme={null}
from airi_factorio.vision import FactorioVision

vision = FactorioVision(model='yolov8')

# Analyze screenshot
results = vision.analyze('factory_screenshot.png')

print(f"Detected entities: {results.entities}")
print(f"Belt throughput: {results.belt_analysis}")
print(f"Bottlenecks: {results.bottlenecks}")
```

## Automation Examples

### Auto-Research

```typescript theme={null}
// Auto-research next technology
async function autoResearch() {
  const tech = await selectNextTech()
  await rcon.send(`/c game.forces.player.research_queue_add("${tech}")`)
}
```

### Resource Monitor

```typescript theme={null}
// Monitor resource production
async function monitorResources() {
  const data = await rcon.send('/c game.print(serpent.block(game.forces.player.item_production_statistics.input_counts))')
  
  const resources = parseResources(data)
  
  if (resources['iron-plate'] < 1000) {
    await alertLowResources('iron-plate')
  }
}
```

### Factory Builder

```typescript theme={null}
// Build production line
async function buildProductionLine(recipe: string, x: number, y: number) {
  const layout = generateLayout(recipe)
  
  for (const entity of layout.entities) {
    await rcon.send(`/c game.surfaces[1].create_entity{
      name="${entity.name}",
      position={${x + entity.x}, ${y + entity.y}},
      force="player"
    }`)
  }
}
```

## Plugin Development

Create custom automation plugins:

```typescript theme={null}
// plugins/auto-defense.ts
export default {
  name: 'auto-defense',
  version: '1.0.0',
  
  async onLoad(bot) {
    bot.on('entity-damaged', async (event) => {
      if (event.entity.type === 'player') {
        await bot.rcon.send('/c game.forces.player.set_spawn_position({0, 0}, game.surfaces[1])')
      }
    })
  },
  
  async onUnload(bot) {
    // Cleanup
  }
}
```

Register plugin:

```typescript theme={null}
import autoDefense from './plugins/auto-defense'

await factorioBot.loadPlugin(autoDefense)
```

## Vision Model Training

The integration supports custom YOLO models trained on Factorio:

### Dataset Structure

```
dataset/
├── images/
│   ├── train/
│   └── val/
├── labels/
│   ├── train/
│   └── val/
└── data.yaml
```

### Training

```bash theme={null}
python train.py --data dataset/data.yaml --epochs 100 --img 640
```

### Deployment

```bash theme={null}
cp runs/train/exp/weights/best.pt models/factorio_yolo.pt
```

Update `.env`:

```bash theme={null}
VISION_MODEL_PATH=models/factorio_yolo.pt
```

## Configuration Reference

### Module Settings

```typescript theme={null}
interface FactorioModuleConfig {
  enabled: boolean
  rconHost: string
  rconPort: number
  rconPassword: string
  enableVision: boolean
  visionModel?: string
  autoResearch?: boolean
  autoDefense?: boolean
  pollInterval?: number  // milliseconds
}
```

### RCON Commands

Common Lua commands:

```lua theme={null}
-- Get player position
/c game.player.print(serpent.line(game.player.position))

-- List all entities
/c game.print(serpent.block(game.player.surface.find_entities()))

-- Research tech
/c game.forces.player.research_queue_add("automation")

-- Spawn entity
/c game.surfaces[1].create_entity{name="assembling-machine-1", position={0, 0}}

-- Get production stats
/c game.print(serpent.block(game.forces.player.item_production_statistics.output_counts))
```

## Troubleshooting

### RCON connection refused

1. Verify RCON is enabled in `server-settings.json`
2. Check firewall allows port 27015
3. Confirm password is correct
4. Restart Factorio server

### Vision model not detecting

1. Ensure model is trained on Factorio data
2. Check confidence threshold (try lowering)
3. Verify screenshot quality and resolution
4. Update to latest model weights

### Commands not executing

1. Check Lua syntax in RCON commands
2. Verify player permissions
3. Review Factorio logs for errors
4. Test commands in Factorio console first

## Performance Considerations

* **Polling Interval**: Balance between responsiveness and server load (recommended: 1000ms)
* **Vision Analysis**: CPU-intensive, consider running on separate machine
* **RCON Limits**: Some servers limit command rate
* **Memory**: Vision model requires \~2GB GPU RAM

## External Resources

* [airi-factorio GitHub](https://github.com/moeru-ai/airi-factorio)
* [Factorio RCON Protocol](https://wiki.factorio.com/Console#Command_line_parameters)
* [Factorio Lua API](https://lua-api.factorio.com/latest/)
* [YOLOv8 Documentation](https://docs.ultralytics.com/)

## Next Steps

<CardGroup cols={2}>
  <Card title="Training Custom Models" href="https://github.com/moeru-ai/airi-factorio/wiki/Vision-Training">
    Train YOLO models on your factory
  </Card>

  <Card title="Plugin Development" href="https://github.com/moeru-ai/airi-factorio/wiki/Plugin-API">
    Build custom automation plugins
  </Card>
</CardGroup>
