Update all docs: README, AI_KNOWLEDGE_BASE, MOD_DEV_GUIDE, batch_example, SKILL

This commit is contained in:
JianFeeeee
2026-05-30 12:51:05 +08:00
parent 3d70338087
commit 21423a6bb4
4 changed files with 367 additions and 824 deletions

376
README.md
View File

@ -1,325 +1,173 @@
# ONI Agent — 缺氧 AI 助手工具集
[Oxygen Not Included](https://www.kleientertainment.com/games/oxygen-not-included)(《缺氧》)是一款高难度的太空殖民模拟游戏。**ONI Agent** 为 AI 提供了一套完整的"眼手"系统:92 个 RESTful API 端点覆盖了玩家能做的全部操作(建造/挖掘/研究/管线/自动化/生物管理/覆盖层切换等),截图和视角控制让 AI 看到游戏画面,事件守护进程让 AI 实时感知游戏动态。Mod + Python 工具链 + AI 三层架构,让任何支持 Tool Use 的模型都能像人类一样操作游戏。
[Oxygen Not Included](https://www.kleientertainment.com/games/oxygen-not-included)(《缺氧》)高难度太空殖民模拟游戏。
**ONI Agent** 为 AI 提供"眼手"系统:RESTful API + Mod(C# Harmony)+ Python 工具链,让任何支持 Tool Use 的模型都能像人类一样操作游戏。
## 整体架构
## 架构
```
┌─────────────────────────────────────────────────┐
│ AI Agent │
│ (Claude / GPT / 任何支持 Tool Use 的模型) │
└──────┬──────────────────────────┬───────────────┘
│ HTTP API (RESTful JSON) │ CLI 工具链
▼ ▼
┌──────────────┐ ┌────────────────────────────┐
│ ONI Mod │ │ Python Tools │
│ (C# / │ │ ├── oni_api.py (客户端) │
│ Harmony) │ │ ├── oni_analyzer.py (分析) │
│ 端口 23876 │ │ └── oni_builder.py (蓝图) │
└──────┬───────┘ └──────────┬─────────────────┘
│ │
▼ ▼
┌─────────────────────────────────────────────────┐
│ Oxygen Not Included (游戏) │
└─────────────────────────────────────────────────┘
AI Agent (Claude/GPT/任何支持 Tool Use 的模型)
↕ HTTP API (RESTful JSON, 端口 23876) + CLI 工具链
ONI Mod (C# Harmony) ←→ Python Tools
↕
Oxygen Not Included (游戏)
```
## 快速开始
### 前置条件
- [Oxygen Not Included](https://store.steampowered.com/app/457140) 游戏
- Python 3.8+
- Mod 文件部署到游戏 Mod 目录
### 1. 安装 Mod
将 `mod/` 目录下的内容(`mod_info.yaml` + `ONIAgentBridge.dll`)放入游戏的 Mod 文件夹:
将 `mod/` 下的 3 个文件放入游戏的 Mod 目录:
```
Windows: %USERPROFILE%\Documents\Klei\OxygenNotIncluded\mods\local\ONIAgentBridge\
macOS: ~/Library/Application Support/Klei/OxygenNotIncluded/mods/local/ONIAgentBridge/
Linux: ~/.config/unity3d/Klei/OxygenNot Included/mods/local/ONIAgentBridge/
```
部署后目录结构:
```
ONIAgentBridge/
├── mod.yaml # Mod 元信息
├── mod_info.yaml # DLC/版本配置
└── ONIAgentBridge.dll # Mod DLL
```
### 2. 启动游戏
启动 ONI,在 Mod 菜单中启用 **ONI Agent Bridge**,加载存档。
启动 ONI → Mod 菜单 → 启用 **ONI Agent Bridge** → 加载存档。
### 3. 验证连接
```bash
python3 tools/oni_api.py health
python tools/oni_api.py health
# 输出: Status: ok Version: 2.0.0
```
预期输出: `{ "status": "ok", "service": "oni-agent-bridge" }`
## 工具链
### 4. 查看游戏状态
```bash
python3 tools/oni_api.py status
python3 tools/oni_analyzer.py
```
## 工具链详解
### `tools/oni_api.py` — Mod API 客户端
与游戏 Mod 通信的核心 CLI 工具,支持所有查询和操作。
### `tools/oni_api.py` — 主 CLI 客户端
```bash
# 状态查询
python3 tools/oni_api.py status # 游戏总览
python3 tools/oni_api.py resources # 全部资源
python3 tools/oni_api.py buildings # 全部建筑
python3 tools/oni_api.py duplicants # 复制人详情
python3 tools/oni_api.py research # 科技进度
python3 tools/oni_api.py geysers # 喷泉列表
python3 tools/oni_api.py critters # 小动物
python3 tools/oni_api.py plants # 植物
python3 tools/oni_api.py rooms # 房间
python tools/oni_api.py status # 游戏总览
python tools/oni_api.py resources # 资源清单
python tools/oni_api.py buildings # 全部建筑
python tools/oni_api.py duplicants # 复制人
python tools/oni_api.py research # 科研
python tools/oni_api.py rooms # 房间
python tools/oni_api.py events # 事件日志
# 地图/格子数据
python3 tools/oni_api.py cell 10 5 # 查看单个格子
python3 tools/oni_api.py cells 0 0 20 20 # 查看 20x20 区域
python3 tools/oni_api.py slice y 20 0 50 # 扫描第 20 行
python3 tools/oni_api.py gas 50 50 30 # 气体分析
python3 tools/oni_api.py explore 40 40 30 20 # AI 友好摘要
# 地图数据
python tools/oni_api.py cell <x> <y> # 单格
python tools/oni_api.py cells <x> <y> <w> <h> # 矩形区域
python tools/oni_api.py slice <axis> <i> <s> <e> # 行列扫描
python tools/oni_api.py gas <x> <y> <r> # 气体分布
python tools/oni_api.py explore <x> <y> <w> <h> # AI摘要
# 实体注册表(查询 ID)
python3 tools/oni_api.py registry buildings Electrolyzer
python3 tools/oni_api.py registry elements Water
python3 tools/oni_api.py registry techs
# 注册表查询
python tools/oni_api.py registry buildings [filter]
python tools/oni_api.py registry elements [filter]
python tools/oni_api.py registry techs
# 执行操作
python3 tools/oni_api.py dig 10 10 8 6 # 挖掘区域
python3 tools/oni_api.py build Electrolyzer 15 12 # 建造建筑
python3 tools/oni_api.py deconstruct Tile 10 10 # 拆除
python3 tools/oni_api.py prioritize 15 12 9 # 优先
python3 tools/oni_api.py research_select ImprovedOxygen # 科研
python3 tools/oni_api.py mop 10 10 # 清理液体
python3 tools/oni_api.py harvest 20 15 # 收获植物
# 游戏速度控制(AI 操作前必须先暂停)
python3 tools/oni_api.py pause "Reason here" # 暂停游戏
python3 tools/oni_api.py unpause 1 # 恢复(1x 速度)
python3 tools/oni_api.py speed 3 # 直接设速度(不暂停)
# 批量任务
python3 tools/oni_api.py batch docs/batch_example.json # 执行批量建造计划
# 优先级管理
python3 tools/oni_api.py priority_global dig 7 # 全局挖掘优先级设为 7
python3 tools/oni_api.py priority_type Electrolyzer 9 # 电解器建造优先级设为 9
# 管道/电线路径
python3 tools/oni_api.py build_pipe_line liquid 42 40 48 40 # 铺设液体管道
python3 tools/oni_api.py build_wire_line regular 42 40 48 40 # 铺设电线
# 高级指令(多个 API 组合)
python3 tools/oni_commander.py diagnose # 全面诊断
python3 tools/oni_commander.py fix_co2 # 自动处理 CO2
python3 tools/oni_commander.py fix_overload # 处理过载电路
python3 tools/oni_commander.py emergency_o2 # 紧急制氧
python3 tools/oni_commander.py expand_base 40 40 10 8 # 一键拓展房间
# 操作(自动拉视角)
python tools/oni_api.py dig <x> <y> <w> <h> # 挖掘
python tools/oni_api.py build <id> <x> <y> # 建造
python tools/oni_api.py deconstruct <x> <y> # 拆除
python tools/oni_api.py prioritize <x> <y> <1-9> # 优先级
python tools/oni_api.py research_select <techId> # 科研
python tools/oni_api.py mop <x> <y> # 清理
python tools/oni_api.py harvest <x> <y> # 收获
python tools/oni_api.py pause [reason] # 暂停
python tools/oni_api.py unpause [speed] # 恢复
python tools/oni_api.py speed <1-3> # 速度
python tools/oni_api.py camera <x> <y> [zoom] # 视角
python tools/oni_api.py batch <file> # 批量
python tools/oni_api.py save [name] # 存档
python tools/oni_api.py load <name> # 读档
python tools/oni_api.py priority_global <t> <p> # 全局优先级
python tools/oni_api.py priority_type <t> <p> # 类型优先级
```
### `tools/oni_analyzer.py` — 智能分析器
自动拉取全方位游戏状态,分析六大维度并生成可操作建议。
```bash
python3 tools/oni_analyzer.py
python tools/oni_analyzer.py
# 分析:氧气/食物/电力/温度/水/科研 六维度 + 建议
```
分析内容:
- 氧气供应状态 → 建议 SPOM 建造时机
- 食物储备 → 建议扩建农场/养殖
- 电力状况 → 建议新增发电类型
- 温度异常 → 建议冷却方案
- 水资源 → 建议过滤/收集策略
- 科研进度 → 建议下一个研究方向
### `tools/oni_builder.py` — 蓝图建造器
预置常用建筑模块,一键部署。
### `tools/oni_builder.py` — 蓝图
```bash
python3 tools/oni_builder.py list # 列出所有蓝图
python3 tools/oni_builder.py build spom 42 42 # 建造 SPOM
python tools/oni_builder.py list # 列出蓝图
python tools/oni_builder.py build spom x y # 部署SPOM
```
蓝图:spom, spom_mini, toilet_loop, farm_mealwood, bedroom, cooling, ranch_hatch
### `tools/oni_commander.py` — 高级指令
```bash
python tools/oni_commander.py diagnose # 全面诊断
python tools/oni_commander.py emergency_o2 # 紧急制氧
python tools/oni_commander.py fix_co2 # 处理CO₂
python tools/oni_commander.py fix_overload # 过载电路
python tools/oni_commander.py expand_base x y w h # 拓展
```
内置蓝图(7个):
### `scripts/event_daemon.py` — 事件守护进程
| 蓝图 | 说明 | 尺寸 |
```bash
python scripts/event_daemon.py
# 持续轮询事件,分类显示到控制台
```
## API 端点
| 类别 | 端点 | 方法 |
|------|------|------|
| `spom` | 标准 SPOM(电解制氧+氢气发电闭环) | 8×6 |
| `spom_mini` | 紧凑型 SPOM(前期过渡用) | 5×4 |
| `toilet_loop` | 卫生间水循环(厕所→净水器→厕所) | 8×4 |
| `ranch_hatch` | 哈奇养殖模块 | 10×6 |
| `farm_mealwood` | 浆果农场(6个种植箱+储物箱) | 6×4 |
| `cooling` | 蒸汽涡轮冷却模块 | 8×6 |
| `bedroom` | 标准卧室(床+梯子床+装饰) | 8×4 |
| 健康 | `/health` | GET |
| 状态 | `/api/state/game`, `resources`, `buildings`, `duplicants`, `research`, `rooms`, `alert`, `camera`, `storage`, `saves`, `events` | GET |
| 地图 | `/api/state/cell`, `cells`, `cells/slice`, `gas` | GET |
| 注册表 | `/api/registry/buildings`, `elements`, `techs` | GET |
| 截图 | `/api/screenshot/latest` | GET |
| 操作 | `/api/action/pause`, `unpause`, `speed`, `dig`, `build`, `deconstruct`, `prioritize`, `research`, `mop`, `harvest`, `batch`, `save`, `load`, `camera`, `priority_global`, `priority_type` | POST |
| | **所有操作自动拉视角到坐标** | |
### `scripts/event_daemon.py` — 事件守护进程(AI 输入源)
持续轮询游戏事件并将其注入 AI 输入流。这是 AI 感知游戏状态变化的实时通道。
```bash
python3 scripts/event_daemon.py
```
工作原理:
1. 每 5 秒轮询 `GET /api/state/events?since=<seq>` 获取新事件
2. 对事件分类(critical / warning / info)
3. critical 事件 → 红色告警 + **自动触发全量游戏快照**(周期/窒息/饥饿/压力)
4. warning 事件 → 结构化输出给 AI
5. 维护滚动事件历史(最多 200 条),AI 可随时查询摘要
事件类型:
- `critical` — 复制人窒息、建筑损坏、电力中断 → 立即触发分析
- `warning` — 低氧、食物短缺、高温 → 主动通知给 AI
- `action_feedback` — 建造/挖掘等操作的结果反馈
- `info` — 常规游戏状态变化
### 辅助脚本
```bash
bash scripts/auto_repair.sh # 诊断 Mod 连接
bash scripts/auto_analyze.sh # 一键健康检查+状态+分析
bash scripts/watch.sh 60 # 每 60 秒持续监控
bash scripts/setup.sh # 环境初始化
python3 scripts/event_daemon.py # 事件守护进程(AI 输入源)
```
## Mod API 完整端点
### 状态查询 (GET)
| 端点 | 说明 |
|------|------|
| `/health` | Mod 存活检测 |
| `/api/state/game` | 全局状态(周期/人数/世界尺寸) |
| `/api/state/resources` | 资源列表(含物态/分类) |
| `/api/state/duplicants` | 复制人(位置/压力/食物/当前任务) |
| `/api/state/buildings` | 建筑(位置/是否运行/功耗/分类) |
| `/api/state/research` | 科技树(进度/解锁建筑) |
| `/api/state/geysers` | 喷泉(位置/状态/排放率) |
| `/api/state/alert` | 警报 |
| `/api/state/critters` | 小动物(位置/种类/幸福度) |
| `/api/state/plants` | 植物(位置/生长进度/是否枯萎) |
| `/api/state/rooms` | 房间(类型/格数/建筑数) |
| `/api/state/queue` | 任务队列(查看待处理任务) |
| `/api/state/events?since=&limit=` | 事件流(AI 轮询增量事件) |
| `/api/state/priorities` | 优先级配置(全局/建筑/复制人) |
### 地图/格子数据 (GET)
| 端点 | 说明 |
|------|------|
| `/api/state/cell?x=10&y=5` | 单格详情 |
| `/api/state/cells?x=&y=&width=&height=` | 矩形区域批量查询 |
| `/api/state/cells/slice?axis=&index=&start=&end=` | 行/列扫描 |
| `/api/state/gas?x=&y=&radius=` | 区域气体分布 |
### 实体注册表 (GET,AI 参考)
| 端点 | 说明 |
|------|------|
| `/api/registry/buildings` | 全部建筑定义(尺寸/功耗/材料) |
| `/api/registry/elements` | 全部元素定义(比热容/熔沸点/导热) |
| `/api/registry/techs` | 全部科技定义(前置/解锁) |
| `/api/registry/priorities` | 优先级级别含义对照表 |
### 操作 (POST)
| 端点 | 请求体 |
|------|--------|
| `/api/action/dig` | `{x, y, width, height}` |
| `/api/action/build` | `{buildingId, x, y}` |
| `/api/action/deconstruct` | `{buildingId, x, y}` |
| `/api/action/prioritize` | `{x, y, priority}` |
| `/api/action/research` | `{techId}` |
| `/api/action/mop` | `{x, y}` |
| `/api/action/harvest` | `{x, y}` |
| `/api/action/schedule` | `{duplicantId, schedule}` |
| `/api/action/wardrobe` | `{duplicantId, equipment}` |
| `/api/action/batch` | `{actions: [{type, ...}]}` — 批量执行 |
| `/api/action/priority_global` | `{target, priority}` — 全局默认优先级 |
| `/api/action/priority_type` | `{buildingType, priority}` — 按建筑类型设优先级 |
| `/api/action/pause` | `{reason?}` — 暂停游戏(AI 操作前必须调用) |
| `/api/action/unpause` | `{speed?}` — 恢复游戏 |
| `/api/action/speed` | `{speed}` — 设置速度 1x/2x/3x |
错误格式:`{success: false, error: "...", errorMessage: "..."}`
## 项目结构
```
oni-agent/
├── README.md # ← 本文件
├── config.json # Mod 连接配置(host/port/timeout)
├── SKILL.md # AI Agent skill 定义与操作手册
│
├── mod/ # 游戏 Mod(C# / Harmony)
│ ├── mod_info.yaml # Mod 元信息(标题/版本/兼容性)
│ └── ONIAgentBridge.cs # HTTP API 服务实现
│
├── tools/ # Python 工具链
│ ├── oni_api.py # API 客户端(20+ 子命令)
│ ├── oni_analyzer.py # 状态分析(6维度预警+建议)
│ └── oni_builder.py # 蓝图建造(7个预置模块)
│
├── scripts/ # 辅助脚本
│ ├── setup.sh # 环境初始化
│ ├── auto_repair.sh # 连接诊断
│ ├── auto_analyze.sh # 一键分析
│ ├── watch.sh # 持续监控模式
│ └── event_daemon.py # 事件守护进程(AI 实时输入源)
│
├── README.md
├── SKILL.md # AI Agent 完整缺氧教程
├── config.json # Mod 连接配置
├── mod/
│ ├── ONIAgentBridge.cs # Mod 源码 (C# Harmony)
│ ├── ONIAgentBridge.csproj
│ ├── mod.yaml / mod_info.yaml
├── tools/
│ ├── oni_api.py # CLI 客户端 (20+ 子命令)
│ ├── oni_analyzer.py # 六维度分析
│ ├── oni_builder.py # 蓝图建造
│ └── oni_commander.py # 高级指令
├── scripts/
│ ├── event_daemon.py # 事件守护进程
│ ├── build_mod.sh # 编译脚本
│ └── setup.sh # 环境初始化
├── docs/
│ ├── MOD_DEV_GUIDE.md # Mod 开发规范与约束
│ ├── AI_KNOWLEDGE_BASE.md # 200+ 建筑/元素/科技 ID 知识库
│ └── batch_example.json # 批量任务示例文件
│
│ ├── AI_KNOWLEDGE_BASE.md # AI 知识库
│ └── MOD_DEV_GUIDE.md # Mod 开发指南
└── skills/
└── oni_agent.md # Agent skill 定义
└── oni_agent.md # Agent skill 定义
```
## 文档索引
| 文档 | 目标读者 | 内容 |
|------|---------|------|
| `SKILL.md` | AI Agent | 坐标系理解、API 用途、场景推理示例、操作表述规范 |
| `docs/AI_KNOWLEDGE_BASE.md` | AI Agent | 建筑 ID 对照表、元素属性、科技树、游戏机制参考 |
| `docs/MOD_DEV_GUIDE.md` | Mod 开发者 | 通信协议、端点规范、安全约束、检查清单 |
| 文档 | 目标 | 内容 |
|------|------|------|
| `SKILL.md` | AI Agent | 完整游玩教程:分阶段目标/材料/可达性/方块/操作协议 |
| `docs/AI_KNOWLEDGE_BASE.md` | AI Agent | 建筑ID/元素属性/科技树/游戏机制参考 |
| `README.md` | 人类用户 | ← 你在看这个 |
## 常见问题
**Q: Mod 连接不上?**
运行 `bash scripts/auto_repair.sh` 诊断。确认:
1. 游戏已启动并加载存档
2. Mod 已在游戏中启用
3. 端口 23876 未被占用
**Q: `buildingId` 从哪查?**
```bash
python3 tools/oni_api.py registry buildings | grep -i electrolyzer
```
或者查看 `docs/AI_KNOWLEDGE_BASE.md`。
**Q: 怎么知道在哪个坐标建造?**
使用 `explore` 命令探索区域:
```bash
python3 tools/oni_api.py explore 40 40 30 20
```
它会告诉你该区域有哪些建筑、复制人、元素分布,帮你决策。
## 许可证
MIT

View File

@ -1,268 +1,189 @@
# ONI Knowledge Base — AI Reference
# ONI AI Knowledge Base — 建筑/元素/科技/机制参考
This file aggregates all building IDs, element IDs, tech IDs, and their semantic metadata
in one structured document. The AI uses this to understand what each entity means and
how to reason about the game.
AI Agent 查询用参考手册。所有 buildingId 可通过 `/api/registry/buildings` 动态查询。
## Coordinate System
## 坐标系
ONI uses a 2D grid. The origin (0,0) is at the **bottom-left** of the map.
- x increases to the right
- y increases upward
- Each cell is 1x1 tile
- Buildings may occupy multiple cells (width x height); the (x,y) is the **bottom-left anchor**
- World size varies by asteroid (default ~256x384 cells)
- 原点 (0,0) = 地图**左下角**,x→右,y→上
- 建筑坐标 = 左下角锚点 (width × height)
- 默认地图大小:256×384
When the AI wants to reference a location:
- Use absolute (x,y) coordinates
- For regions: (x, y, width, height)
- For buildings: reference the bottom-left cell of the building
- For movement: "at (x,y)" or "from (x1,y1) to (x2,y2)"
## 建筑数据库
## Building Categories
### 氧气
| ID | 尺寸 | 材料 | 耗电(W) | 功能 |
|----|------|------|---------|------|
| Electrolyzer | 2×2 | Metal | 120 | 水→O₂+H₂ (1kg/s水) |
| OxygenDiffuser | 2×2 | Metal | 120 | 藻类→O₂ (早期) |
| Deodorizer | 1×2 | Metal | 0 | 污染氧→氧气 (需过滤介质) |
| AlgaeDistillery | 3×4 | Metal | 120 | 藻泥→藻类 |
| AlgaeHabitat | 1×2 | Farmable | 0 | 藻类养殖 |
| Category | Purpose | Examples |
|------------|----------------------------------------|---------------------------------------------------|
| Base | Structure, storage, doors, ladders | Tile, Ladder, StorageBin, InsulatedTile, Door |
| Oxygen | Oxygen production, gas cleaning | Electrolyzer, OxygenDiffuser, Deodorizer |
| Power | Power generation, storage, wiring | CoalGenerator, HydrogenGenerator, Battery |
| Food | Food production, cooking, ranching | PlanterBox, ElectricGrill, MicrobeMusher, Ranch |
| Plumbing | Liquid handling, hygiene | LiquidPump, Lavatory, WaterSiever, Shower |
| Ventilation| Gas handling | GasPump, GasFilter, GasVent |
| Refinement | Material processing | MetalRefinery, RockCrusher, Kiln, Compost |
| Medicine | Health, disease treatment | Apothecary, MassageTable, SickBay |
| Furniture | Decor, morale, stress relief | Cot, MessTable, ArcadeCabinet, FlowerPot |
| Stations | Research, suit docks, crafting | ResearchStation, SuperComputer, AtmoSuitDock |
| Utilities | Temperature management | ThermoAquatuner, SpaceHeater, TempshiftPlate |
| Automation | Logic circuits, sensors | AND Gate, AtmoSensor, AutomationWire |
| Shipping | Conveyor systems | ConveyorLoader, ConveyorRail, SolidFilter |
### 电力
| ID | 尺寸 | 材料 | 发电(W) | 燃料 |
|----|------|------|---------|------|
| ManualGenerator | 2×2 | Metal | 400 | 人力 |
| CoalGenerator | 2×2 | Metal | 600 | 煤 |
| HydrogenGenerator | 2×2 | Metal | 800 | 氢 |
| NaturalGasGenerator | 2×2 | Metal | 800 | 天然气 |
| PetroleumGenerator | 3×2 | Metal | 2000 | 石油 |
| SteamTurbine | 4×2 | Metal | 850 | 蒸汽(热删除) |
| SolarPanel | 2×1 | Metal | 380 | 光照 |
| Battery | 1×1 | Metal | 0 | 储电 10kJ |
| JumboBattery | 2×1 | Metal | 0 | 储电 40kJ |
| Transformer | 2×1 | Metal | 0 | 电路分离 |
## Key Building IDs (frequently used by AI)
### 管道/通风
| ID | 尺寸 | 材料 | 耗电 | 功能 |
|----|------|------|------|------|
| GasPump | 1×2 | Metal | 240W | 抽气 |
| GasFilter | 1×2 | Metal | 120W | 气体分离 |
| GasVent | 1×1 | Metal | 0 | 排气口 |
| LiquidPump | 1×2 | Metal | 240W | 抽液 |
| LiquidFilter | 1×2 | Metal | 120W | 液体分离 |
| LiquidVent | 1×1 | Metal | 0 | 排水口 |
| WaterPurifier | 2×2 | Metal | 120W | 污水→清水 |
```
# Oxygen production
Electrolyzer -> Produces O2 + H2 from water (needs 1kg/s water)
OxygenDiffuser -> Produces O2 from algae (early game)
Deodorizer -> Converts PollutedOxygen to Oxygen (needs filtration medium)
### 食物/农业
| ID | 尺寸 | 材料 | 功能 |
|----|------|------|------|
| PlanterBox | 1×1 | BuildableRaw | 种植(需泥土) |
| FarmTile | 1×1 | BuildableRaw | 种植(需灌溉) |
| HydroponicFarmTile | 1×2 | Metal | 液培(需液体管道) |
| StorageLocker | 1×1 | BuildableRaw | 储物 |
| RationBox | 2×2 | BuildableRaw | 储食(CO₂防腐) |
| Refrigerator | 1×2 | Metal | 冷藏(耗电) |
| ElectricGrill | 2×2 | Metal | 烹饪 |
| MicrobeMusher | 2×2 | BuildableRaw | 初期制食 |
# Power
ManualGenerator -> 400W, duplicant powered
CoalGenerator -> 600W, consumes Coal
HydrogenGenerator -> 800W, consumes H2
NaturalGasGenerator-> 800W, consumes NaturalGas
PetroleumGenerator -> 2000W, consumes Petroleum
SteamTurbine -> Extracts heat from steam, produces power
SolarPanel -> 380W max, needs light
WoodBurner -> 300W, consumes Lumber
### 卫生
| ID | 尺寸 | 材料 | 功能 |
|----|------|------|------|
| Outhouse | 1×2 | BuildableRaw | 初期厕所(需清理) |
| WashBasin | 1×1 | BuildableRaw | 洗手(需水) |
| Lavatory | 1×2 | Metal | 抽水马桶(需水管) |
| WashSink | 1×1 | Metal | 自动洗手(需水管) |
| Shower | 2×1 | Metal | 淋浴(士气) |
# Power storage
Battery -> 10kJ storage, small
JumboBattery -> 40kJ storage
SmartBattery -> 20kJ storage, automation output
### 基地
| ID | 尺寸 | 材料 | 功能 |
|----|------|------|------|
| Tile | 1×1 | BuildableRaw | 地板/墙 |
| InsulationTile | 1×1 | BuildableRaw | 隔热 |
| Ladder | 1×1 | BuildableRaw | 攀爬 |
| FirePole | 1×1 | Metal | 速降 |
| PneumaticDoor | 1×2 | Metal | 自动门 |
| ManualDoor | 1×2 | BuildableRaw | 手动门 |
| Cot | 1×1 | BuildableRaw | 床 |
| ResearchStation | 2×2 | BuildableRaw | 初级科研(60W) |
| SuperComputer | 2×2 | Plastic | 高级科研(120W) |
| TriageCot | 1×2 | BuildableRaw | 医疗床 |
# Food
PlanterBox -> Grows plants, needs dupe delivery
FarmTile -> Grows plants with irrigation
HydroponicFarm -> Grows plants with automatic irrigation
ElectricGrill -> Cooks food (better quality)
MicrobeMusher -> Makes basic mush bars from water + dirt
GasRange -> Advanced cooking with gas
Refrigerator -> Stores food, slows decay
### 精炼
| ID | 尺寸 | 材料 | 功能 |
|----|------|------|------|
| MetalRefinery | 3×2 | Metal | 精炼金属(1200W) |
| RockCrusher | 2×2 | BuildableRaw | 碎矿 |
| Kiln | 1×2 | BuildableRaw | 烧陶瓷/玻璃 |
| PolymerPress | 2×3 | Metal | 石油→塑料(240W) |
| OilRefinery | 3×2 | Metal | 石油→天然气+石油 |
| Compost | 2×2 | BuildableRaw | 污染土→泥土 |
# Plumbing
LiquidPump -> Pumps liquids (240kg/s)
Lavatory -> Produces PollutedWater from dupe use
WaterSiever -> Filters PollutedWater -> Water
Desalinator -> Removes salt from SaltWater/Brine
LiquidVent -> Outputs liquid into world
### 温度控制
| ID | 尺寸 | 材料 | 功能 |
|----|------|------|------|
| Aquatuner | 1×2 | RefinedMetal | 液冷(1200W) |
| SpaceHeater | 1×1 | Metal | 加热(120W) |
| IceFan | 2×1 | BuildableRaw | 降温(耗冰) |
| IceKettle | 1×2 | BuildableRaw | 冰→水 |
| TempshiftPlate | 1×1 | BuildableRaw | 导热板 |
# Ventilation
GasPump -> Pumps gases (500g/s)
GasFilter -> Filters specific gas from mixed pipes
GasVent -> Outputs gas into world
HighPressureGasVent-> 20kg/tile max pressure
### 动物/养殖
| ID | 尺寸 | 材料 | 功能 |
|----|------|------|------|
| RanchStation | 2×2 | BuildableRaw | 养殖站 |
| Incubator | 2×2 | BuildableRaw | 孵化器 |
| CritterFeeder | 1×2 | BuildableRaw | 投喂器 |
| CritterTrap | 1×1 | Metal | 陷阱 |
# Refinement
MetalRefinery -> Refines metal ores into refined metals
RockCrusher -> Crushes rock into sand/power
Kiln -> Burns clay -> ceramic
GlassForge -> Makes glass from sand
Compost -> Converts polluted dirt into dirt
## 材料类别映射
# Base
Tile -> Standard tile, 2 tiles high
Ladder -> Allows vertical movement
InsulatedTile -> Reduces heat transfer (best insulation)
ManualAirlock -> Manual door
PneumaticDoor -> Auto door, lets gas pass
MechanizedAirlock -> Auto door, seals gas/liquid
StorageBin -> Stores solid resources
LiquidReservoir -> Stores 5t of liquid
GasReservoir -> Stores 150kg of gas
| 类别 | 包含元素 | 来源 |
|------|---------|------|
| BuildableRaw | SandStone, Granite, IgneousRock, SedimentaryRock, Obsidian, MaficRock | 挖掘 |
| Metal | Cuprite, IronOre, GoldAmalgam, Wolframite, Cobaltite | 挖掘 |
| RefinedMetal | Copper, Iron, Gold, Steel, Tungsten | 精炼 |
| Plastic | Polypropylene | 聚合压机制造 |
| Glass | MoltenGlass→Glass | 窑炉 |
| BuildingFiber | ReedFiber | 耕种 |
| Transparent | Diamond, Glass | 挖掘/制造 |
| Farmable | Dirt | 挖掘/堆肥 |
# Temperature
ThermoAquatuner -> Cools liquid piped through it (needs steam room)
ThermoRegulator -> Cools gas piped through it
SpaceHeater -> Heats area (inefficient)
LiquidTepidizer -> Heats liquid (up to 85C)
TempshiftPlate -> Distributes heat evenly
## 元素属性参考
# Stations
ResearchStation -> Basic research (needs dirt)
SuperComputer -> Advanced research (needs plastic)
AtmoSuitDock -> Stores atmo suit
GroomingStation -> Grooms critters for happiness/eggs
RanchStation -> Ranching skill station
FarmStation -> Improves farm yield (needs fertilizer)
PowerControlStation-> Improves generator efficiency
| 元素 | 比热容(J/g·K) | 导热(W/m·K) | 熔点(°C) |
|------|--------------|-------------|---------|
| SandStone | 0.800 | 2.000 | - |
| Granite | 0.790 | 3.390 | - |
| IgneousRock | 1.000 | 2.000 | - |
| SedimentaryRock | 0.200 | 2.000 | - |
| Cuprite | 0.600 | 4.500 | - |
| IronOre | 0.440 | 4.000 | - |
| GoldAmalgam | 0.240 | 2.000 | - |
| Water | 4.179 | 0.609 | 0/100 |
| PollutedWater | 4.179 | 0.580 | -0.65/100 |
| Oxygen | 1.005 | 0.024 | -183/-183 |
| Hydrogen | 8.640 | 0.168 | -252/-252 |
| CarbonDioxide | 0.846 | 0.015 | 0/-78 |
| CrudeOil | 1.690 | 2.000 | -40/400 |
# Medicine
MassageTable -> Reduces stress
SickBay -> Cures diseases
TriageCot -> Heals physical damage
Apothecary -> Produces medicine
## 科技树 (常用)
# Automation (common items)
AtmoSensor -> Senses gas pressure
ThermoSensor -> Senses temperature
HydroSensor -> Senses liquid pressure
GasElementSensor -> Senses specific gas type
AND Gate, NOT Gate, FILTER Gate, BUFFER Gate
```
| Tech ID | 名称 | 前置 | 解锁 |
|---------|------|------|------|
| FarmingTech | 农业技术 | - | PlanterBox, FarmTile |
| PowerRegulation | 电力调节 | - | Transformer, HeavyWire |
| Plumbing | 管道 | - | Lavatory, WaterPurifier |
| Ventilation | 通风 | - | GasPump, GasFilter |
| Refinement | 精炼 | - | MetalRefinery, RockCrusher |
| TemperatureModulation | 调温 | - | Aquatuner, SteamTurbine |
| SmartStorage | 智能存储 | - | SmartStorageBin |
| AdvancedPowerRegulation | 高级电力 | PowerRegulation | PowerTransformer |
| LiquidPiping | 液体管道 | Plumbing | LiquidPump, LiquidFilter |
| GasPiping | 气体管道 | Ventilation | GasValve |
| FineDining | 精致餐饮 | FarmingTech | ElectricGrill |
| AnimalControl | 动物控制 | - | CritterTraps |
| Ranching | 畜牧 | AnimalControl | RanchStation |
## Key Element IDs (resources)
## 房间系统
```
# Critical survival
Oxygen -> Breathable gas (needed by dupes)
Water -> Essential for farming, electrolysis, life support
Dirt -> Used in research (early) and farming
Algae -> Consumed by OxygenDiffuser
| 房间 | 要求 | 加成 |
|------|------|------|
| Bedroom(卧室) | 4×床, 封闭 | +1士气 |
| Washroom(卫生间) | 洗手盆+马桶, 封闭 | +1士气 |
| MessHall(餐厅) | 餐桌+配给盒, 封闭 | +2士气 |
| GreatHall(大堂) | 装饰+餐桌+配给盒 | +4士气 |
| Greenhouse(温室) | 种植+光照, 封闭 | 植物生长+50% |
| Hospital(医院) | 医疗床+医生, 封闭 | 治疗加速 |
| Ranch(畜舍) | 养殖站+喂食器 | 动物繁殖加速 |
| PowerPlant(电站) | 发电机×2+电池 | 发电效率+10% |
# Food chain
Calories -> Aggregate food energy for colony
MealLice -> Basic food from mealwood plants
BristleBerry -> Mid-tier food from bristle blossom
Mushroom -> Food from dusk cap (needs CO2 + slime)
RawEgg -> Egg for cooking
Meat -> From ranching
## 电路规则
# Power chain
Coal -> Burned in CoalGenerator
Hydrogen -> Burned in HydrogenGenerator
NaturalGas -> Burned in NaturalGasGenerator
Petroleum -> Burned in PetroleumGenerator
CrudeOil -> Can be refined to Petroleum
- 普通电线最大负载:1000W
- 重导线(Wire) 最大负载:2000W
- 超过负载 → 过载损坏 → 复制人维修
- 使用变压器(Transformer)将重导线电路分成普通导线子电路
- 智能电池可连接自动化电路控制发电机启停
# Construction metals
CopperOre -> Early building material
IronOre -> Mid building material
GoldAmalgam -> High corrosion resistance
Wolframite -> Very high melting point (tungsten source)
Steel -> Strong, high melting point (refined)
RefinedIron -> Mid refined metal
Plastic -> Advanced material (from polymer press or dreckos)
Ceramic -> Best insulation material
## 紧急阈值
# Water / liquids
SaltWater -> Can be desalinated to Water
Brine -> Can be desalinated (more salt per water)
PollutedWater -> Can be filtered to Water (also used by reed fiber)
CrudeOil -> Pumped from oil biome
Petroleum -> Refined from oil (cooking or refinery)
Lumber -> From arbor trees, burned in wood burner
Ethanol -> From lumber, burned in petroleum generator
# Gas handling
PollutedOxygen -> Can be deodorized to Oxygen
CarbonDioxide -> Sinks to bottom, used by mushrooms/soda fountain
ChlorineGas -> Disinfects, used by balm lily
SourGas -> Can be cooled to methane + sulfur
# Rare / advanced
Niobium -> End-game space material
Thermium -> Best heat conductor (space material)
Isoresin -> Used for insulation (space material)
ViscoGel -> Non-mixing liquid (space material)
Radium -> Radioactive, spaced out DLC
```
## Research Tech Tree (simplified path)
```
Tier 0 (start): FarmingTech, PowerRegulation, Plumbing, Ventilation
Tier 1: FoodPreparation (-> ElectricGrill, MicrobeMusher)
InteriorDecor (-> Cot, FlowerPot, various decor)
AdvancedPowerRegulation (-> SmartBattery, PowerTransformer)
LiquidPiping (-> LiquidPump, WaterSiever, Desalinator)
GasPiping (-> GasPump, GasFilter)
FineDining (-> GasRange, Refrigerator)
Tier 2: ImprovedOxygen (-> Electrolyzer)
RefinedObjects (-> MetalRefinery, RockCrusher)
TemperatureModulation (-> ThermoAquatuner, ThermoRegulator)
Ranching (-> GroomingStation, Incubator)
SmartStorage (-> LiquidReservoir, GasReservoir)
Automation (-> first automation buildings)
Tier 3: HighTemperatureForging (-> Steel)
SpaceProgram (-> telescope, rocket platform)
CryoFuelPropulsion (-> hydrogen rocket engine)
Tier 4: MaterialsScience (-> SuperCoolant, ViscoGel)
```
## Building Size Reference (width x height)
```
1x1: Wire, GasPipe, LiquidPipe, AutomationWire, Switch, Sensor
1x2: ManualGenerator, Battery, PlanterBox, FarmTile, RationBox
2x1: GasFilter, LiquidFilter, Incubator, Jukebot
2x2: CoalGenerator, HydrogenGenerator, OxygenDiffuser, Electrolyzer,
GasPump, LiquidPump, AlgaeTerrarium, Deodorizer, WaterSiever,
ElectricGrill, MicrobeMusher, RockCrusher, Kiln, Compost,
MassageTable, Apothecary, ResearchStation, TextileLoom
2x3: MetalRefinery, PolymerPress, OilRefinery, AtmoSuitDock
2x4: Telescope, MolecularForge
3x1: LadderBed, DisplayShelf
3x2: ManualAirlock, PneumaticDoor, MechanizedAirlock, ConveyorLoader,
SmartStorageBin, LiquidReservoir, GasReservoir
3x3: Shower, Sauna, HotTub
3x4: SteamTurbine
4x2: SuperComputer, JumboBattery, StorageBin
4x4: SolarPanel
```
## Common Game Mechanics (AI reference)
### Gas/Liquid Physics
- Gases **layer by density**: CO2 (sinks) < O2 < PollutedO2 < NaturalGas < H2 (rises)
- Liquids **layer by density**: Petroleum < Water/SaltWater/Brine < CrudeOil < Mercury
- Pressure limit for gas vents: GasVent = 2kg/tile, HighPressureGasVent = 20kg/tile
- Buildings overheat above their overheat temperature (default 75C, some higher)
- Insulated Tile reduces heat transfer by ~100x
### Duplicant Needs
- Oxygen: need ~100g/s per dupe
- Food: need ~1000kcal/cycle per dupe
- Stress: > 50% starts causing problems, > 80% mental breaks
- Temperature: comfortable at 18-35C, hypothermia below 10C, hyperthermia above 40C
- Morale: affected by decor, food quality, room bonuses
### Room Types
- Latrine: Outhouse + WashBasin = +1 morale
- Washroom: Lavatory + Sink = +2 morale
- Barracks: Cot/LadderBed + 1 decor = +1 morale
- Bedroom: ComfyBed + 1 decor = +2 morale
- Mess Hall: MessTable + 1 decor = +3 morale
- Great Hall: MessTable + 2+ decor and recreation = +6 morale
- Park: 4+ wild/planted plants = +1 morale
- Nature Reserve: 12+ wild plants = +6 morale
- Stable: GroomingStation + CritterDropOff = ranching room
- Ranch: Incubator + feeder (spaced out)
### SPOM (Self-Powered Oxygen Module)
The classic Rodriguez SPOM:
- 1 Electrolyzer (consumes 1kg/s water -> 888g/s O2 + 112g/s H2)
- 2 GasPumps for O2 extraction
- 1 HydrogenGenerator (burns 100g/s H2, produces 800W)
- 1 GasFilter to separate H2 from O2
- Net power positive (runs on its own hydrogen)
- Standard size: 8x6 tiles
| 指标 | 警告 | 危险 | 应对 |
|------|------|------|------|
| O₂质量 | <2000kg | <500kg | 增加制氧 |
| 食物 | <500kkcal | <200kkcal | 增加农场 |
| 水 | <20000kg | <5000kg | 找水源/净化 |
| 温度 | >35°C | >50°C | 隔热+冷却 |
| CO₂ | 可见积聚 | >2kg/tile | 挖排气管 |
| 藻类 | <2000kg | <500kg | 转电解器 |
| 煤 | <5000kg | <1000kg | 找煤矿/换发电 |

View File

@ -2,348 +2,121 @@
## 概述
本文档规定了一个与外部 Agent(AI 助手)对接的《缺氧》(Oxygen Not Included) Mod 应遵循的接口规范、约束条件和最佳实践。遵循此规范开发的 Mod 可与 `oni-agent` 工具链无缝协作。
---
本文档规定 ONI Agent Bridge Mod 的接口规范和开发约束。
## 1. 通信协议
### 1.1 传输层
- **协议**: HTTP 1.1
- **地址**: `127.0.0.1`(仅本地回环,禁止暴露到外部网络)
- **端口**: 由配置文件指定(默认 `23876`)
- **编码**: 所有请求和响应均为 UTF-8
- **地址**: `127.0.0.1`(仅本地回环,禁止暴露外部网络)
- **端口**: 默认 `23876`,可在 `config.json` 修改
- **编码**: UTF-8
### 1.2 数据格式
- 所有请求和响应使用 `application/json`
- 响应必须包含有效的 JSON
- 错误响应必须包含 `error` 字段
所有请求和响应使用 `application/json`。
**统一响应格式:**
```json
// 成功响应
{ "result": "ok", ... }
// 成功
{ "success": true, "data": { ... } }
// 错误响应
{ "error": "error_message" }
// 错误
{ "success": false, "error": "error_code", "errorMessage": "可读信息" }
```
### 1.3 请求超时
- 服务端应在 5 秒内响应
- 长时间操作应排队后立即返回 `{ "result": "queued" }`
**旧格式兼容**(/health 端点历史版本):
```json
{ "status": "ok" }
```
---
### 1.3 线程模型
- **读操作**可通过 `EnqueueRead(Func<object>)` 排队到主线程执行(`ManualResetEvent` 同步等待)
- **写操作**通过静态 `ConcurrentQueue<Action> cmdQueue` + `QueueProcessor` (MonoBehaviour.Update) 排队到主线程
- **格子数据**(Grid.Element/Mass/Temperature/Objects)可从后台线程直接读取(静态数组)
## 2. API 端点规范
## 2. 端点规范
### 2.1 健康检查
```
GET /health
```
用于 Agent 探测 Mod 是否存活。必须始终可达,不依赖游戏状态。
**响应**:
必须始终可达,不依赖游戏状态。
```json
{ "status": "ok", "service": "mod_name" }
{ "success": true, "data": { "status": "ok", "service": "oni-agent-bridge", "version": "2.0.0" } }
```
### 2.2 状态查询端点
### 2.2 状态查询 (GET /api/state/)
| 端点 | 说明 | 实现方式 |
|------|------|---------|
| game | 周期/复制人/世界尺寸/暂停/速度 | EnqueueRead |
| resources | 资源列表(含物态/存量) | EnqueueRead |
| buildings | 建筑列表(含位置/尺寸) | EnqueueRead |
| duplicants | 复制人(位置/血量) | EnqueueRead |
| research | 科技进度 | EnqueueRead |
| rooms | 房间类型 | EnqueueRead |
| events | 事件日志(支持since分页) | 直接读取(eventLock) |
| storage | 储物建筑内容 | EnqueueRead |
| saves | 存档列表 | EnqueueRead |
| alert | 游戏警报 | EnqueueRead |
| camera | 相机位置 | EnqueueRead |
所有状态查询为 `GET` 请求,路径前缀 `/api/state/`。
| 端点 | 返回内容 | 必需 | 新增字段 |
|------|---------|------|---------|
| `/api/state/game` | 周期、复制人、世界尺寸 | **是** | `gridWidth`, `gridHeight` |
| `/api/state/resources` | 资源列表(含分类/物态) | **是** | `id`, `state`, `category` |
| `/api/state/duplicants` | 复制人详情 | **是** | `x`, `y`, `cell`, `currentChore` |
| `/api/state/buildings` | 建筑列表 | 推荐 | `cell`, `category`, `powerWatt` |
| `/api/state/research` | 科技树(含解锁列表) | 推荐 | `requiredTechs`, `unlockedBuildings` |
| `/api/state/geysers` | 喷泉详情 | 可选 | `cell`, `isActive`, `isDormant` |
| `/api/state/alert` | 当前警报 | 推荐 | `clickable` |
| `/api/state/critters` | 小动物详情 | 可选 | `cell`, `calories` |
| `/api/state/plants` | 植物列表 | 可选 | `isGrown`, `progress`, `isWilting` |
| `/api/state/rooms` | 房间列表 | 可选 | 类型/格数/建筑/生物/植物 |
### 2.3 地图/格子数据端点
这是 AI 理解游戏世界最重要的端点。格子级数据让 AI 知道每个具体位置的状态。
| 端点 | 说明 | 参数 |
### 2.3 格子数据 (GET, 可后台线程)
| 端点 | 参数 | 说明 |
|------|------|------|
| `GET /api/state/cell` | 单格详情 | `?x=&y=` |
| `GET /api/state/cells` | 矩形区域(批量) | `?x=&y=&width=&height=` |
| `GET /api/state/cells/slice` | 行或列扫描 | `?axis=x&index=&start=&end=` |
| `GET /api/state/gas` | 气体分布分析 | `?x=&y=&radius=` |
| cell | x, y | 单格详情 |
| cells | x, y, width, height | 矩形区域 |
| cells/slice | axis, index, start, end | 行列扫描 |
| gas | x, y, radius | 气体分布 |
#### `GET /api/state/cell?x=10&y=5`
### 2.4 注册表 (GET /api/registry/)
| 端点 | 说明 |
|------|------|
| buildings | 所有建筑定义(含尺寸/材料类别) |
| elements | 所有元素定义 |
| techs | 科技树(含前置) |
```json
{
"x": 10, "y": 5, "cell": 4523,
"element": "Oxygen",
"elementId": "Oxygen",
"elementState": "gas",
"massKg": 1.8,
"temperatureC": 23.5,
"isSolid": false, "isLiquid": false, "isGas": true,
"hasBuilding": true, "buildingName": "GasPump",
"hasDuplicant": false, "duplicantName": null,
"isVacuum": false, "isVisible": true
}
### 2.5 操作 (POST /api/action/)
所有操作执行前**自动拉视角**到目标坐标。
| 端点 | 请求体 | 说明 |
|------|--------|------|
| pause | {reason?} | 暂停(通过SpeedControlScreen) |
| unpause | {speed?} | 恢复 |
| speed | {speed} | 设速度 |
| dig | {x,y,width,height} | 挖掘(使用DigTool.PlaceDig) |
| build | {buildingId,x,y} | 建造(使用BuildingDef.Instantiate) |
| deconstruct | {x,y} | 拆除(使用Deconstructable.QueueDeconstruction) |
| prioritize | {x,y,priority} | 设优先级(1-9) |
| research | {techId} | 研究(SetActiveResearch) |
| mop | {x,y} | 清理液体 |
| harvest | {x,y} | 收获植物 |
| batch | {actions} | 批量操作 |
| save | {name?} | 存档 |
| load | {name} | 读档 |
| camera | {x,y,zoom?} | 移动视角 |
| priority_global | {target,priority} | 全局默认优先级 |
| priority_type | {buildingType,priority} | 按类型优先级 |
### 2.6 截图
```
#### `GET /api/state/cells?x=0&y=0&width=5&height=5`
```json
{
"region": { "x": 0, "y": 0, "width": 5, "height": 5 },
"cells": [ /* array of cell objects */ ]
}
GET /api/screenshot/latest
```
返回 PNG 图片。通过 `ScreenCapture.CaptureScreenshot` 异步生成。
### 2.4 实体注册表端点 (AI 参考)
## 3. 事件系统
用于 AI 在运行时查询游戏实体的元数据。所有为 `GET` 请求。
Mod 内部维护事件列表 (`List<AgentEvent> + lock`)。
事件可通过 `GET /api/state/events?since=N` 轮询。
事件自动记录操作日志。
| 端点 | 返回内容 |
|------|---------|
| `/api/registry/buildings` | 全部建筑定义(尺寸/功耗/发热/材料) |
| `/api/registry/elements` | 全部元素定义(比热容/导热/熔沸点) |
| `/api/registry/techs` | 全部科技定义(前置/解锁建筑) |
## 4. Mod 开发检查清单
#### `GET /api/registry/buildings`
```json
[
{
"id": "Electrolyzer",
"name": "Electrolyzer",
"category": "Oxygen",
"width": 2, "height": 2,
"powerCost": 120,
"heatGeneration": 1.25,
"constructionMass": ["IronOre", "IronOre"]
}
]
```
### 2.5 操作端点
所有操作为 `POST` 请求,路径前缀 `/api/action/`。
| 端点 | 作用 | 必需 |
|------|------|------|
| `/api/action/dig` | 挖掘指定区域 | **是** |
| `/api/action/build` | 建造建筑 | **是** |
| `/api/action/deconstruct` | 拆除建筑 | 推荐 |
| `/api/action/prioritize` | 设置优先级 | 可选 |
| `/api/action/research` | 选择研究方向 | 推荐 |
| `/api/action/schedule` | 修改复制人日程 | 可选 |
| `/api/action/wardrobe` | 修改复制人装备 | 可选 |
| `/api/action/mop` | 清理液体 | 推荐 |
| `/api/action/harvest` | 收获植物 | 推荐 |
| `/api/action/cancel` | 取消操作 | 可选 |
#### `GET /api/state/game`
```json
{
"cycle": 42,
"duplicantCount": 6,
"worldName": "Terra",
"worldSize": 256
}
```
#### `GET /api/state/duplicants`
```json
[
{
"name": "Dup1",
"stress": 12.5,
"calories": 850000,
"stamina": 98.2,
"oxygen": 85.0,
"diseases": 0,
"skillLevels": 3
}
]
```
#### `GET /api/state/resources`
```json
[
{ "name": "Oxygen", "tag": "Oxygen", "amount": 12345.6, "unit": "kg" }
]
```
#### `GET /api/state/buildings`
```json
[
{
"name": "Manual Generator",
"id": "ManualGenerator",
"x": 10,
"y": 5,
"isOperational": true
}
]
```
### 2.3 操作端点
所有操作为 `POST` 请求,路径前缀 `/api/action/`。
| 端点 | 作用 | 必需 |
|------|------|------|
| `/api/action/dig` | 挖掘指定区域 | **是** |
| `/api/action/build` | 建造建筑 | **是** |
| `/api/action/deconstruct` | 拆除建筑 | 推荐 |
| `/api/action/prioritize` | 设置优先级 | 可选 |
| `/api/action/research` | 选择研究方向 | 推荐 |
| `/api/action/schedule` | 修改复制人日程 | 可选 |
| `/api/action/wardrobe` | 修改复制人装备 | 可选 |
#### `POST /api/action/dig`
**请求体**:
```json
{ "x": 10, "y": 5, "width": 8, "height": 6 }
```
**响应**:
```json
{ "result": "dig_queued", "x": 10, "y": 5, "width": 8, "height": 6 }
```
#### `POST /api/action/build`
**请求体**:
```json
{ "buildingId": "Electrolyzer", "x": 10, "y": 5, "rotation": null }
```
**响应**:
```json
{ "result": "build_queued", "buildingId": "Electrolyzer", "x": 10, "y": 5 }
```
---
## 3. Mod 约束
### 3.1 安全性
1. **仅绑定本地回环地址** `127.0.0.1`,不得监听 `0.0.0.0`
2. **不得实现认证/授权**——回环地址默认安全
3. **不得执行文件 I/O**(读取 Mod 自带配置除外)
4. **输入校验**——所有用户输入必须校验类型和范围
### 3.2 性能
1. 状态查询必须是**只读操作**,不得持有锁
2. 资源列表等大数据量接口应考虑分页(未来扩展)
3. 建造/挖掘等操作应返回 `queued` 后异步执行
4. HTTP 服务器应在**单独线程**运行,不得阻塞游戏主线程
### 3.3 兼容性
1. 使用 `KMod.UserMod2` 基类
2. 使用 `Harmony` 进行补丁(如果使用)
3. 引用 `UnityEngine` 和 `Assembly-CSharp` 程序集
4. 最小支持游戏版本应在 `mod_info.yaml` 中声明(当前推荐 `612000`)
### 3.4 错误处理
```json
// Mod 内部错误的通用格式
{ "error": "error_type", "details": "human readable message" }
// 常见错误类型
{ "error": "not_found" } // 404 端点不存在
{ "error": "invalid_request" } // 请求体解析失败
{ "error": "not_implemented" } // 功能尚未实现
{ "error": "unknown_building", "buildingId": "..." } // 建筑 ID 不识别
{ "error": "unknown_tech", "techId": "..." } // 科技 ID 不识别
```
---
## 4. 配置文件规范
Agent 侧通过 `config.json` 定位 Mod:
```json
{
"modHost": "127.0.0.1",
"modPort": 23876,
"timeout": 10
}
```
- `modHost`: 始终为 `127.0.0.1`
- `modPort`: 应与 Mod 中监听的端口一致
- `timeout`: HTTP 请求超时秒数
---
## 5. AI-Friendly 数据设计原则
### 5.1 数据可读性
所有暴露的数据应满足 AI 可直接理解的三个条件:
1. **命名语义化** — 使用自然语言字段名(如 `temperatureC` 而非 `tempK`)
2. **数据类型合理** — 使用数字而非枚举字符串(温度用 `float` 而非 `string`)
3. **上下文完整** — 每个实体包含足够的位置和状态信息(坐标、类别、是否可运行)
### 5.2 坐标系统
- 统一使用 `(x, y)` 整数坐标,对应游戏网格
- 原点在左下角:`(0, 0)`
- 建筑使用其左下角锚点坐标
- 返回数据中同时提供 `cell` 索引(Grid 内部使用)和 `(x, y)` 坐标
### 5.3 实体分类
每个实体(建筑、元素、科技)必须包含分类标签:
- 建筑: `category`(Base/Oxygen/Power/Food/...)
- 元素: `state`(solid/liquid/gas)+ `category`(metal/water/fuel/...)
- 资源: 带 `state` 和 `category` 帮助 AI 推理用途
### 5.4 AI 推理辅助
- `/api/registry/*` 端点提供完整的实体元数据查询
- `GET /api/state/gas` 提供区域气体分布统计(AI 无法逐格遍历)
- `/api/state/rooms` 提供房间判定结果(AI 无法自行判断房间类型)
### 5.5 操作设计
操作设计遵循以下原则:
- **幂等性** — 同个操作重复执行不产生副作用
- **非阻塞** — 操作立即返回 `queued`,异步执行
- **确定性** — 使用绝对坐标 `(x, y)`,不支持"在某个建筑旁边"这类模糊表述
- **输入校验** — 拒绝未知的 `buildingId` 或越界坐标
## 6. 扩展建议
### 5.1 添加新端点
1. 在 `ProcessRequest` 中添加路由匹配
2. 实现对应的处理方法
3. 更新本指南和 `SKILL.md`
### 5.2 蓝图系统
预置的建造方案(蓝图)应满足:
- 坐标相对于原点,便于偏移
- 包含预先挖掘区域
- 建筑顺序隐含依赖关系
### 5.3 事件推送(未来)
考虑支持 WebSocket 或 SSE,用于游戏事件实时推送(如警报触发)。
---
## 6. 开发检查清单
- [ ] Mod 继承 `UserMod2`,在 `OnLoad` 中启动 HTTP 服务
- [ ] 在 `OnUnload` 中停止 HTTP 服务
- [ ] 实现全部必需端点(health, game, resources, duplicants, dig, build)
- [ ] 错误响应包含 `error` 字段
- [ ] 端口号与 `config.json` 一致
- [ ] 仅绑定 `127.0.0.1`
- [ ] 使用 `Newtonsoft.Json`(游戏自带,无需额外依赖)
- [ ] `mod_info.yaml` 声明了正确的游戏版本
- [ ] Mod 类继承 `UserMod2`,重写 `OnLoad(Harmony)`
- [ ] 用 `GameObject + MonoBehaviour` 处理队列,`DontDestroyOnLoad`
- [ ] 用 `HttpListener` 暴露 HTTP 服务,`BeginGetContext` 异步处理
- [ ] 格子数据安全读取:`Grid.Element[]`、`Grid.Mass[]`、`Grid.Solid[]`、`Grid.Objects[,]`
- [ ] 读操作用 `EnqueueRead` 同步到主线程
- [ ] 写操作用 `cmdQueue` 排队到主线程的 `Update()` 中执行
- [ ] 响应统一 `{success, data}` 或 `{success, error, errorMessage}`
- [ ] 所有操作自动 `QWithCamera(x,y,action)` 拉视角

View File

@ -1,5 +1,4 @@
{
"name": "Build SPOM - Step 1: Dig and Electrolyzer",
"actions": [
{
"type": "dig",
@ -27,11 +26,13 @@
"y": 40
},
{
"type": "wait",
"delayMs": 100
"type": "build",
"buildingId": "GasFilter",
"x": 44,
"y": 40
},
{
"type": "priority",
"type": "prioritize",
"x": 45,
"y": 42,
"priority": 9