Translate all project documentation into English

This commit is contained in:
Emil
2026-09-12 23:43:10 +03:00
parent 6682668c16
commit 54af124a6d
8 changed files with 477 additions and 475 deletions
+37 -37
View File
@@ -1,73 +1,73 @@
# Протокол прототипа
# Prototype protocol
Версия: 1. Точный реализованный каталог инструментов доступен через MCP `tools/list`, а возможности установленного Paper — через `project_context`.
Version: 1. The exact implemented tool catalog is available through MCP `tools/list`, and the capabilities of the installed Paper plugin through `project_context`.
## Соединение с Paper
## Paper connection
Сервис слушает только loopback, по умолчанию `127.0.0.1:8765`. `GET /health` возвращает состояние и версию без приватных данных. `POST /v1/rpc` принимает JSON и заголовок `Authorization: Bearer <token>`.
The service listens on loopback only, at `127.0.0.1:8765` by default. `GET /health` returns status and version information without private data. `POST /v1/rpc` accepts JSON and an `Authorization: Bearer <token>` header.
Запрос: `{ "method": "project_context", "params": { "player_id": "UUID", "project_id": "default" }, "requestId": "correlation-id" }`.
Request: `{ "method": "project_context", "params": { "player_id": "UUID", "project_id": "default" }, "requestId": "correlation-id" }`.
Успех: `{ "ok": true, "result": { ... } }`. Ошибка: `{ "ok": false, "error": { "code": "...", "message": "..." } }`. Ошибка может сопровождаться HTTP 400/403; клиент обязан читать структурированное тело. Токены в результатах не возвращаются.
Success: `{ "ok": true, "result": { ... } }`. Error: `{ "ok": false, "error": { "code": "...", "message": "..." } }`. An error may come with HTTP 400/403; clients must read the structured body. Tokens are never returned in results.
Административный ключ обязателен для `chat_poll`, `chat_reply`, `recovery_review` и `recovery_abandon`. Ключ агента допускает инструменты мира в проекте связанного владельца, но не административное восстановление. `player_id/project_id` добавляются MCP-процессом из настроек, а не предлагаются модели. Плагин повторно проверяет владельца и его действующие права. Для изолированного тестового мира есть явно включаемый `allow-local-automation` и принципал `console`; административные операции восстановления также проходят проверку этой области полномочий.
The administrator key is required for `chat_poll`, `chat_reply`, `recovery_review`, and `recovery_abandon`. The agent key permits world tools within the bound owner's project, but not administrative recovery. The MCP process injects `player_id/project_id` from its configuration; the model is not asked to supply them. The plugin rechecks the owner and their current permissions. An isolated test world can explicitly enable `allow-local-automation` with the `console` principal; administrative recovery operations also pass through this scope check.
## Чтение и запись
## Reading and writing
`region_inspect` требует `min/max` как `{x,y,z}` и `detail: "summary" | "blocks"`. Координаты включительные, целочисленные. Лимит прототипа — 4096 позиций. Ответ содержит палитру с количеством, а для `blocks` — точные состояния. Данные берутся из загруженных чанков без неявной генерации мира.
`region_inspect` requires `min/max` as `{x,y,z}` and `detail: "summary" | "blocks"`. Coordinates are inclusive integers. The prototype limit is 4096 positions. The response contains a palette with counts and, for `blocks`, exact states. Data comes from loaded chunks without implicit world generation.
`build_prepare` принимает `recipe: {version: 1, operations: [...]}`, необязательный массив `dependencies` и необязательный `part_id` для точной маски части. Геометрия: `box(min,max,block,hollow?)`, `line(from,to,block)`, `cylinder(center,radius,height,block,hollow?)`, `repeat(count,offset,operations)`. Используется JSON-описание, не исполняемый JavaScript.
`build_prepare` accepts `recipe: {version: 1, operations: [...]}`, an optional `dependencies` array, and an optional `part_id` for an exact part mask. Geometry: `box(min,max,block,hollow?)`, `line(from,to,block)`, `cylinder(center,radius,height,block,hollow?)`, `repeat(count,offset,operations)`. This is a JSON description, not executable JavaScript.
Результат подготовки: `plan_id`, `plan_hash`, `changed_blocks`, `region`, `expires_at`. Полный план и исходные блоки остаются в журнале. `build_apply` принимает этот ID, хеш и постоянный для данного вызова `idempotency_key`. Повтор того же вызова возвращает ту же операцию. Для другого плана нужен другой ключ.
Preparation returns `plan_id`, `plan_hash`, `changed_blocks`, `region`, and `expires_at`. The full plan and original blocks stay in the journal. `build_apply` accepts this ID, hash, and an `idempotency_key` that remains constant for that logical call. Repeating the same call returns the same operation. A different plan requires a different key.
`operation_status(operation_id)` возвращает состояние, счётчики и ограниченные примеры конфликтов. `operation_cancel` останавливает следующие порции. `operation_undo_prepare` создаёт обратный план; он проходит обычный `build_apply` и проверки. Потеря ответа на применение не даёт права создать другой ключ и повторить запись: сначала проверить `project_context` или повторить исходный вызов с тем же ключом.
`operation_status(operation_id)` returns status, counters, and a bounded sample of conflicts. `operation_cancel` stops subsequent slices. `operation_undo_prepare` creates a reverse plan; it goes through the normal `build_apply` and checks. Losing the response to an apply request does not justify creating a different key and repeating the write: first check `project_context` or repeat the original call with the same key.
`part_define(name,operation_id)` регистрирует только фактически записанные блоки завершённой операции. `part_get(part_id)` возвращает имя, границы, количество и защиту. Границы не равны маске: `build_prepare(part_id)` проверяет каждый блок по точной маске. Расширение создаётся отдельной частью.
`part_define(name,operation_id)` registers only blocks actually written by a completed operation. `part_get(part_id)` returns the name, bounds, count, and protection settings. Bounds are not the mask: `build_prepare(part_id)` checks every block against the exact mask. Extensions are created as separate parts.
Перед записью проверяются реальные состояния целевых блоков и объявленных зависимостей; проверка повторяется после сохранения намерения. Несовпадение не перезаписывается автоматически. Для undo также учитываются известные последующие записи наших операций, даже когда значение блока снова совпадает с прежним результатом.
Before a write, the actual states of target blocks and declared dependencies are checked; the check runs again after the intent is persisted. A mismatch is never overwritten automatically. Undo also accounts for known subsequent writes by our operations, even when a block's value again matches the earlier result.
Плагин наблюдает неотменённые `BlockPlaceEvent` и `BlockBreakEvent` в настроенном мире. Такое событие лишает прежнюю операцию права на undo данного блока, включая случай «изменили и вернули обратно» (ABA). Эти уведомления хранятся только в памяти текущего процесса. После перезапуска и для внешних путей без наблюдаемого события остаётся проверка текущего содержимого; полная история действий других плагинов не обещается.
The plugin observes uncancelled `BlockPlaceEvent` and `BlockBreakEvent` events in the configured world. Such an event revokes the earlier operation's right to undo that block, including an edit followed by a change back to the original state (ABA). These notifications are held only in the current process's memory. After a restart, and for external paths without an observed event, current-content checks remain in place; a complete history of other plugins' actions is not promised.
Полный серверный журнал внешних изменений пока не реализован. `region_changes` отвечает `resync_required`; агент использует свежие ограниченные чтения. Это явное ограничение прототипа.
A full server-side journal of external changes is not implemented yet. `region_changes` returns `resync_required`; the agent uses fresh, bounded reads. This is an explicit prototype limitation.
## Восстановление после сбоя
## Crash recovery
Незавершённая операция после перезапуска получает `recovery_required` и запрещает начало новых записей. Автоматического повторения незавершённых порций нет. Административные RPC ниже не входят в MCP-инструменты агента и не являются откатом мира.
After a restart, an unfinished operation receives `recovery_required` and prevents new writes from starting. Unfinished slices are not replayed automatically. The administrative RPCs below are not exposed as agent MCP tools and do not roll back the world.
`recovery_review` принимает `operation_id`. Результат использует имена полей Java-записи: `operationId`, `planId`, `positions`, `matchesBefore`, `matchesAfter`, `foreignStates`, `currentDigest`, `sampledAtMillis`. Проверяемая маска объединяет фактически подтверждённые записи предыдущих порций и потенциальные записи незавершённой порции; пропуски без записи не включаются. Счётчики описывают совпадение текущих значений с `before/after`, а `currentDigest` — SHA-256 для этого снимка. Совпадение содержимого не доказывает авторство изменения.
`recovery_review` accepts `operation_id`. Its result uses the Java record's field names: `operationId`, `planId`, `positions`, `matchesBefore`, `matchesAfter`, `foreignStates`, `currentDigest`, `sampledAtMillis`. The reviewed mask combines confirmed writes from earlier slices with potential writes from the unfinished slice; skipped positions that were not written are excluded. The counters describe how current values match `before/after`, while `currentDigest` is the SHA-256 digest of this snapshot. Matching content does not prove who made a change.
`recovery_abandon` принимает `operation_id` и `expected_digest`, полученный из `currentDigest` последнего обзора. Сервер заново читает маску и отклоняет запрос, если её содержимое изменилось. При совпадении он оставляет все блоки мира на месте, переводит операцию в `failed` и сохраняет решение до успешного ответа. Ответ имеет обычную форму `operation_status`.
`recovery_abandon` accepts `operation_id` and `expected_digest`, taken from the latest review's `currentDigest`. The server rereads the mask and rejects the request if its contents have changed. If they match, it leaves all world blocks in place, changes the operation to `failed`, and persists the decision before returning success. The response has the usual `operation_status` shape.
Отказ от неопределённой истории навсегда запрещает undo этой операции и сохраняет аннулирование прежнего права на undo для блоков затронутой маски. Новые записи разрешаются только после постоянного сохранения решения по всем незавершённым операциям. Сбой до сохранения оставляет необходимость восстановления; потеря ответа требует проверки `operation_status`, а не предположения, что произошёл откат. Устаревший или неверный digest возвращается как RPC-ошибка `invalid_request` с причиной.
Abandoning uncertain history permanently disables undo for that operation and preserves the invalidation of earlier undo ownership for blocks in the affected mask. New writes are permitted only after the decisions for all unfinished operations have been durably saved. A failure before persistence leaves recovery required; a lost response requires checking `operation_status`, not assuming that a rollback occurred. A stale or incorrect digest is returned as an `invalid_request` RPC error with a reason.
Статус `applied` подтверждает наблюдавшийся результат записи и проверки в работающем сервере. Файлы чанков и журнал не образуют общую транзакцию; автоматической проверки сохранности всех ранее завершённых операций после аварии пока нет.
The `applied` status confirms the write and verification result observed by the running server. Chunk files and the journal do not form a shared transaction; automatic verification that all previously completed operations survived a crash is not implemented yet.
## Локальные схемы
## Local schematics
Реализованные имена RPC — `asset_list`, `schematic_export` и `schematic_import_prepare`. Отдельных маршрутов `schematic_list` и немедленного `schematic_import` нет. Наличие этих возможностей проверяется через `project_context`.
The implemented RPC names are `asset_list`, `schematic_export`, and `schematic_import_prepare`. There are no separate `schematic_list` or immediate `schematic_import` routes. Check `project_context` for these capabilities.
`asset_list` принимает необязательный `query` для поиска по имени без учёта регистра и возвращает `{ "assets": [...] }`. Каждый элемент содержит `assetId`, `name`, `width`, `height`, `length`, `blockCount`, `dataVersion`, `offset`, `sha256`, `bytes`. Каталог содержит до 64 файлов; каждый файл проверяется при чтении, поэтому повреждённая схема может привести к отказу всего запроса списка.
`asset_list` accepts an optional `query` for case-insensitive name search and returns `{ "assets": [...] }`. Each entry contains `assetId`, `name`, `width`, `height`, `length`, `blockCount`, `dataVersion`, `offset`, `sha256`, and `bytes`. The catalog holds up to 64 files; every file is validated when read, so a corrupt schematic may cause the entire list request to fail.
`schematic_export` принимает `name`, включительные `min/max` и необязательный `origin`. Имя содержит 1–64 печатных символа. `origin` задаёт точку привязки схемы; по умолчанию она равна `min`. Сервер читает плотный прямоугольный участок, включая воздух, в текущей области проекта и в пределах `max_plan_blocks` (не более 4096). Неподдерживаемые блоки и сущности, кроме игроков, приводят к отказу; игроки в схему не записываются. Результат — один объект с теми же полями метаданных, что у `asset_list`. Файл остаётся в подкаталоге `schematics` каталога данных плагина; RPC не возвращает его содержимое или произвольный путь.
`schematic_export` accepts `name`, inclusive `min/max`, and an optional `origin`. The name contains 1–64 printable characters. `origin` defines the schematic's anchor point and defaults to `min`. The server reads a dense rectangular region, including air, within the current project area and the `max_plan_blocks` limit (at most 4096). Unsupported blocks and entities other than players cause rejection; players are not written to the schematic. The result is one object with the same metadata fields as `asset_list`. The file remains in the `schematics` subdirectory of the plugin's data directory; the RPC returns neither its contents nor an arbitrary path.
`schematic_import_prepare` принимает `asset_id`, `target: {x,y,z}` и необязательный `rotation: 0 | 90 | 180 | 270` (по умолчанию 0). Поворот выполняется по часовой стрелке при взгляде сверху вокруг точки привязки `target`; сохранённый `offset` учитывается. Изменяются также поддерживаемые направления ступеней и оси брёвен/столбов. Результат — обычный `plan_id/plan_hash/changed_blocks/region/expires_at`; для записи нужен отдельный `build_apply`. Воздух схемы входит в план и может удалять существующие поддерживаемые блоки. Область, исходное содержимое, окружение, политика блоков и конфликты проверяются обычным путём подготовки и применения.
`schematic_import_prepare` accepts `asset_id`, `target: {x,y,z}`, and an optional `rotation: 0 | 90 | 180 | 270` (default 0). Rotation is clockwise when viewed from above, around the `target` anchor; the saved `offset` is taken into account. Supported stair directions and log/pillar axes are also transformed. The result is the usual `plan_id/plan_hash/changed_blocks/region/expires_at`; writing requires a separate `build_apply`. Air in the schematic is part of the plan and can remove existing supported blocks. The area, original contents, surroundings, block policy, and conflicts are checked through the normal preparation and application path.
Поддерживается ограниченное подмножество Sponge Schematic v2: gzip и NBT с палитрой ванильных строительных состояний. Лимиты — 4096 позиций, 1 МиБ сжатого файла и 4 МиБ распакованного NBT. Сущности, block entities, биомы, неизвестные поля верхнего уровня, требуемые модификации и другие версии формата отклоняются. `DataVersion` новее текущего сервера не принимается; преобразования через DataFixer нет. Полная совместимость со всеми схемами WorldEdit не заявляется.
A limited subset of Sponge Schematic v2 is supported: gzip and NBT with a palette of vanilla building block states. Limits are 4096 positions, a 1 MiB compressed file, and 4 MiB of decompressed NBT. Entities, block entities, biomes, unknown top-level fields, required mods, and other format versions are rejected. A `DataVersion` newer than the current server is not accepted; there is no DataFixer conversion. Full compatibility with every WorldEdit schematic is not claimed.
Внешний `.schem` можно заранее поместить локально в каталог схем под именем `[A-Za-z0-9][A-Za-z0-9_-]{0,63}.schem`, после чего его основание используется как `asset_id`. Произвольные пути, сетевые URL и символические ссылки не принимаются. Загрузки файла через RPC в прототипе нет.
An external `.schem` can be placed in the local schematic directory in advance with a name matching `[A-Za-z0-9][A-Za-z0-9_-]{0,63}.schem`; its filename stem then serves as `asset_id`. Arbitrary paths, network URLs, and symbolic links are not accepted. The prototype does not support file uploads through RPC.
## Чат
## Chat
`chat_poll` принимает стабильный на время жизни Bridge `client_id`. Ответ — `messages` с полями `id`, `playerId`, `projectId`, `text`, `type`, сведениями о положении и блоке под прицелом при наличии. `type` — `prompt` либо `cancel`. Ключ администратора обязателен.
`chat_poll` accepts a `client_id` that remains stable throughout the Bridge process's lifetime. The response is `messages` with `id`, `playerId`, `projectId`, `text`, `type`, and position and targeted-block information when available. `type` is either `prompt` or `cancel`. The administrator key is required.
`chat_reply` принимает `id`, `playerId`, `text`, `done`, необязательный `error`. Ответ маршрутизируется только инициатору исходного запроса. На смену Bridge-процесса незавершённые запросы не проигрываются автоматически: плагин останавливает изменения и просит проверить мир. `/ai stop` приостанавливает новые записи независимо от того, успел ли завершиться ACP-ход.
`chat_reply` accepts `id`, `playerId`, `text`, `done`, and an optional `error`. The response is routed only to the initiator of the original request. When the Bridge process changes, unfinished requests are not replayed automatically: the plugin stops changes and asks the user to inspect the world. `/ai stop` pauses new writes regardless of whether the ACP turn has finished.
## Камера
## Camera
`camera_capture` принимает `camera_id` либо `pose: {x,y,z,yaw,pitch,fov?,width?,height?}`. Позиция соответствует ногам наблюдателя; Worker отдельно возвращает координаты глаз. `after_operation_id` проверяет завершение серверной операции, но не гарантирует получения её всех пакетов клиентом.
`camera_capture` accepts `camera_id` or `pose: {x,y,z,yaw,pitch,fov?,width?,height?}`. The position refers to the observer's feet; the Worker returns eye coordinates separately. `after_operation_id` checks that the server operation has completed, but does not guarantee that the client has received all of its packets.
Paper сериализует запросы, перемещает настроенного spectator-наблюдателя и отправляет запрос локальному Camera Worker на `127.0.0.1:8766` с отдельным ключом. Pending-ответ содержит `captureId`; для проверки вызывается `camera_capture` с `capture_id`. Готовый результат содержит `imageBase64` и `mimeType`, которые Bridge превращает в MCP image content, не в текстовую base64-строку.
Paper serializes requests, moves the configured spectator observer, and sends a request to the local Camera Worker at `127.0.0.1:8766` with a separate key. A pending response contains `captureId`; poll by calling `camera_capture` with `capture_id`. A completed result contains `imageBase64` and `mimeType`, which the Bridge converts into MCP image content rather than a textual base64 string.
Снимок имеет эвристическую оценку готовности чанков/кадров. `serverRevisionVerified: false` сохраняется до реализации строгого клиентского подтверждения. Отсутствие камеры, таймаут и невозможность получить свежий кадр не считаются визуальным успехом.
Captures include a heuristic assessment of chunk/frame readiness. `serverRevisionVerified: false` remains in place until strict client acknowledgement is implemented. A missing camera, a timeout, or failure to obtain a fresh frame never counts as visual success.
Подробности Worker: [camera-mod/README.md](../camera-mod/README.md). Потоки и журнал: [world-core/README.md](../world-core/README.md). ACP и изоляция: [bridge/README.md](../bridge/README.md).
Worker details: [camera-mod/README.md](../camera-mod/README.md). Threading and journal: [world-core/README.md](../world-core/README.md). ACP and isolation: [bridge/README.md](../bridge/README.md).