Erinaldordso commited on
Commit
8f6b7b7
·
verified ·
1 Parent(s): 04681ce

Run Naldo on AltoClef with Muse supervision

Browse files

Replace default Voyager controller with upstream AltoClef 0.19 gamer, retain current world and inventory, correct client startup and telemetry, Survival/Normal, and Muse-only OpenCode coaching. Verified Java17 bridge build and 57 targeted tests.

README.md CHANGED
@@ -1,290 +1,304 @@
1
- ---
2
- title: Minecraft Friends AI ZeroGPU
3
- emoji: 🧠
4
- colorFrom: blue
5
- colorTo: green
6
- sdk: gradio
7
- sdk_version: 6.27.0
8
- python_version: '3.12'
9
- app_file: app.py
10
- pinned: false
11
- ---
12
-
13
- # Programa — endpoint CPU para Voyager
14
-
15
- Endpoint OpenAI-compatible dedicado ao projeto original MineDojo/Voyager.
16
-
17
- ## Endpoint local de compatibilidade (Granite)
18
-
19
- O endpoint OpenAI-compatible público continua disponível para clientes antigos e
20
- para os componentes locais auxiliares. Ele não é mais o cérebro generativo do
21
- `Naldo_Bot`; o Naldo usa OpenCode conforme a seção seguinte.
22
-
23
- - GGUF oficial: `ibm-granite/granite-4.0-h-tiny-GGUF`
24
- - Arquivo: `granite-4.0-h-tiny-Q4_K_M.gguf`
25
- - Revisão fixada: `08d5a8a9741dd5c1a95d2d39e25253226aa1464e`
26
- - Quantização: `Q4_K_M`
27
- - Arquitetura: Granite 4.0 H-Tiny MoE/Mamba2, 7B totais e ~1B parâmetros ativos
28
- - Contexto operacional do Voyager: 8.192 tokens
29
- - Saída padrão: 384 tokens
30
- - Saída máxima: 512 tokens
31
- - Alias principal: `granite-4.0-h-tiny`
32
- - CPU: 16 threads de decode e 16 threads de prefill/batch
33
-
34
- Os aliases antigos permanecem aceitos apenas para compatibilidade de clientes e
35
- continuam roteando para o Granite local. O Voyager do Naldo não usa esses aliases
36
- para geração.
37
-
38
- ## Cérebro do Naldo_Bot: OpenCode
39
-
40
- Action, Curriculum, Critic e Skill Manager do `Naldo_Bot` usam uma ponte
41
- OpenAI-compatible local em `127.0.0.1:7864`, que traduz as chamadas do Voyager
42
- para um servidor `opencode serve` preso ao loopback em `127.0.0.1:7865`.
43
-
44
- - OpenCode pinado: `opencode-ai@1.18.33`, instalado localmente no runtime sem `npm -g`.
45
- - Provider: `opencode`.
46
- - Modelo principal: `muse-spark-1.3-contributor-free`.
47
- - Fallbacks: `fledge-alpha-free` e `nemotron-3-ultra-free`, somente do provider OpenCode gratuito.
48
- - Nenhuma credencial do usuário é copiada; o processo recebe HOME/XDG próprios no runtime.
49
- - As mensagens de inferência enviam `tools: {}`. No OpenCode 1.18.33 isso foi validado
50
- sem execução de bash/arquivos; permissões customizadas de sessão não são usadas porque
51
- o Zen gratuito as rejeita com `FreeTierError`.
52
- - O bridge não inventa suporte a `temperature`/`max_tokens`: registra os valores pedidos
53
- e preserva a resposta integral, evitando cortar JavaScript do Action Agent.
54
- - Embeddings continuam locais em `127.0.0.1:7860/v1/embeddings`.
55
- - Se OpenCode ou bridge morrerem, o supervisor interrompe o Naldo e recupera o cérebro
56
- antes de religar o bot; não existe fallback generativo para Granite ou Gemini.
57
-
58
- O Curriculum em Creative continua usando o estado real e os checkpoints persistentes.
59
- A conclusão da tarefa continua exigindo verificação independente do mundo.
60
-
61
- Referência do modelo:
62
- https://huggingface.co/ibm-granite/granite-4.0-h-tiny-GGUF
63
-
64
- ## Embeddings
65
-
66
- O Voyager original usa embeddings no SkillManager e no cache de QA do CurriculumAgent.
67
-
68
- - Modelo oficial: `Qwen/Qwen3-Embedding-0.6B-GGUF`
69
- - Arquivo: `Qwen3-Embedding-0.6B-Q8_0.gguf`
70
- - Revisão fixada: `370f27d7550e0def9b39c1f16d3fbaa13aa67728`
71
- - Pooling: LAST, conforme documentação do Qwen3 Embedding para llama.cpp
72
- - Vetores normalizados
73
- - Alias OpenAI-compatible: `text-embedding-ada-002`
74
-
75
- Referência:
76
- https://huggingface.co/Qwen/Qwen3-Embedding-0.6B-GGUF
77
-
78
- ## Inferência local somente em CPU
79
-
80
- A inferência Granite e os embeddings locais não usam GPU:
81
-
82
- - `CUDA_VISIBLE_DEVICES=""`
83
- - `HIP_VISIBLE_DEVICES=""`
84
- - `ROCR_VISIBLE_DEVICES=""`
85
- - `GGML_VK_VISIBLE_DEVICES=""`
86
- - `n_gpu_layers=0`
87
- - `offload_kqv=False`
88
- - `op_offload=False`
89
- - wheel CPU do `llama-cpp-python==0.3.35`
90
- - threads detectadas por affinity/cgroup
91
- - mmap ativado
92
- - chamadas de geração serializadas para evitar disputa de CPU
93
-
94
- O decorador `@spaces.GPU` existente é somente a sentinela exigida pelo host ZeroGPU;
95
- a função não é chamada pela API.
96
-
97
- ## Compatibilidade Voyager
98
-
99
- Por padrão `PLAYER_MODE=0`. O servidor não injeta o antigo prompt Bedrock.
100
- Os dois Voyagers jogam em Creative: mineração, colocação, equipamento e inventário
101
- são verificados a partir da observação real. O `placeBlocks` recebe o ID exato
102
- da tarefa canônica; o agente não pode substituir `bricks` por `brick`.
103
-
104
- O endpoint aceita temperatura 0.0, que coincide com os defaults do Voyager para
105
- ActionAgent, CurriculumAgent, CriticAgent e SkillManager.
106
-
107
- O endpoint mantém a compatibilidade HTTP de chat e embeddings para os clientes.
108
-
109
- ## API
110
-
111
- - `GET /`
112
- - `GET /health`
113
- - `GET /status`
114
- - `GET /v1/models`
115
- - `POST /v1/chat/completions`
116
- - `POST /v1/embeddings`
117
- - `GET /minecraft/status`
118
- - `GET /voyager/status`
119
- - `GET /gemini-bot/status`
120
-
121
- ## Segundo jogador: Gemini_Bot
122
-
123
- `Gemini_Bot` executa uma segunda instância completa do Voyager no mesmo servidor
124
- Java 1.19, com processo Mineflayer e checkpoint próprios. Curriculum, Action,
125
- Critic e Skill Manager consultam o Gemini CLI por um proxy local exclusivo;
126
- somente os embeddings usam o modelo local. `Naldo_Bot` usa exclusivamente o
127
- bridge OpenCode descrito acima para geração. Ambos validam tarefas Creative pela
128
- mudança real no mundo ou pelo inventário.
129
-
130
- O Curriculum permanece no modo automático do Voyager: cada IA observa o estado
131
- atual, consulta seu checkpoint e decide o próximo objetivo. Não existe sequência
132
- fixa nem fallback circular. Objetivos e projetos já concluídos ou falhados são
133
- rejeitados semanticamente; a IA recebe o motivo e precisa escolher algo novo.
134
- Se o provedor não produzir uma decisão válida, o bot permanece conectado e
135
- aguarda com backoff, sem construir estruturas por roteiro.
136
-
137
- Projetos suportados continuam verificáveis (`wall`, `bridge`, `room`, `tower`,
138
- `road`, `arch`, `monument`, `shelter`, `courtyard` e `gate`). Quando a IA escolhe
139
- um deles, a geometria é executada por `buildProject`, que usa `placeItem` e
140
- registra todas as coordenadas físicas para o Critic. Um projeto concluído não
141
- pode ser escolhido novamente. Naldo_Bot e Gemini_Bot tomam decisões separadas e
142
- mantêm checkpoints independentes.
143
-
144
- O adaptador `/pause` não envia o comando global do mod: os dois bots e os
145
- jogadores Xbox compartilham um mundo que continua rodando durante a inferência.
146
- `placeBlocks` prioriza destinos com linha de visão e usa a face encontrada por
147
- `GoalPlaceBlock`, mantendo a confirmação do bloco no mundo. A física está fixada
148
- em `prismarine-physics@1.6.0`, que inclui a correção oficial de água no Minecraft
149
- 1.19; os quatro pins do protocolo permanecem inalterados.
150
- Os logs `[llm_metric]` registram bot, papel, latência e tokens reais por chamada
151
- de Curriculum, Action, Critic e Skill Manager. No Gemini CLI, a temperatura zero
152
- é aplicada por `modelConfigs.customOverrides`, além do cliente Voyager.
153
-
154
- Se as construções cercarem o bot, o helper procura uma área de superfície já
155
- carregada e livre, a 8–12 blocos por eixo. O voo Creative de recuperação verifica
156
- o volume do jogador em toda a rota, usa segmentos de até 0,4 bloco, sobe no máximo
157
- 4 blocos para ultrapassar a construção e pousa em solo confirmado. Não destrói
158
- blocos, não teleporta e não altera a exploração horizontal do Curriculum.
159
-
160
- - CLI fixado em `@google/gemini-cli@0.61.0`, modelo efetivo `gemini-3.5-flash-lite`.
161
- - Segredos privados do Space: `GEMINI_BOT_KEY_1` a `GEMINI_BOT_KEY_6`.
162
- - Nenhuma chave deve ser salva no Git, no checkpoint ou nas saídas de status.
163
- - Status: `/gemini-bot/status` (conexão, tarefas, métricas e falhas por posição
164
- da chave; nunca revela valores de chaves).
165
- - Controle de inicialização: `GEMINI_BOT_AUTOSTART=0` desativa somente o
166
- segundo bot. O Naldo_Bot e o mundo persistente seguem independentes.
167
-
168
- API pública de compatibilidade:
169
-
170
- `https://erinaldordso-minecraft-friends-ai-zerogpu.hf.space/v1`
171
-
172
- Modelo de chat público (não é o cérebro do Naldo):
173
-
174
- `granite-4.0-h-tiny`
175
-
176
- Cérebro interno do Naldo:
177
-
178
- `opencode/muse-spark-1.3-contributor-free` via `127.0.0.1:7864/v1`
179
-
180
- Modelo de embeddings:
181
-
182
- `text-embedding-ada-002`
183
-
184
- ## Upstream Voyager
185
-
186
- Os dois processos instanciam as classes de currículo, Action, Critic, Skill
187
- Manager e o loop `Voyager.learn()` do mesmo checkout MineDojo/Voyager fixado em
188
- `55e45a880755d0c8c66ca7fb5fe7962ac8974f89`. Cada runner verifica o HEAD
189
- do checkout e a origem das cinco classes antes de aprender; os endpoints de
190
- status expõem `engine_runtime` apenas para o PID validado. Os adaptadores
191
- Creative e os parsers necessários aos modelos não são código byte a byte igual
192
- ao upstream. Checkpoints e mundo ficam em `/persist` e não são substituídos
193
- pela atualização do código.
194
-
195
- Projeto original:
196
- https://github.com/MineDojo/Voyager
197
-
198
- Este Space executa o Voyager fixado em `55e45a880755d0c8c66ca7fb5fe7962ac8974f89`
199
- com correções de reconexão, observações nulas e exploração horizontal limitada.
200
- O `mineBlock` só aceita blocos até dois níveis abaixo dos pés, para o bot cavar
201
- um poço de onde consegue sair, e o pathfinder mantém a escavação do upstream
202
- justamente por isso.
203
-
204
- ## Instalação conforme a página oficial
205
-
206
- O `README.md`, `installation/minecraft_instance_install.md` e
207
- `installation/fabric_mods_install.md` do upstream são o contrato de instalação.
208
- `tests/test_installation_conformance.py` trava o que é possível automatizar.
209
-
210
- | Passo oficial | Onde está neste Space |
211
- | --- | --- |
212
- | Python >= 3.9 | `voyager_stack.MIN_PYTHON`, verificado no boot |
213
- | Node.js >= 16.13.0 | `voyager_stack.MIN_NODE`, verificado no boot |
214
- | `git clone` | `VoyagerStack._ensure_source`, no commit fixado |
215
- | `pip install -e .` | `VoyagerStack._ensure_python_package`, com verificação posterior |
216
- | `npm install` + `npx tsc` em `mineflayer-collectblock`, depois `npm install` em `voyager/env/mineflayer` | `VoyagerStack._ensure_node` |
217
- | Dependências de `requirements.txt` | `requirements.txt` deste repositório |
218
- | `Voyager(ckpt_dir=..., resume=True)` para retomar | `voyager_runner.py` deriva `resume` dos arquivos do checkpoint e o passa ao construtor |
219
- | Mundo em Creative + Peaceful | `server.properties` |
220
- | `fabric-loader-0.14.18-1.19` | instalador Fabric pinado em `minecraft_stack.py` |
221
-
222
- Desvios, todos deliberados:
223
-
224
- - **`mc_port` em vez de `azure_login`.** O README aceita os dois ("You can also
225
- use mc_port instead of azure_login"). Este Space sobe um servidor Bedrock
226
- dedicado em `127.0.0.1:25565` com Geyser/ViaProxy para os amigos Xbox, então
227
- não existe `MinecraftInstance` local para o `azure_login` abrir. A
228
- reconexão automática do upstream é substituída pela supervisor do Space e
229
- pelos patches de recuperação não destrutivos.
230
- - **Subconjunto de mods do Fabric.** A lista de 5 mods da página é para um
231
- *cliente* (o próprio README diz para abrir o mundo em LAN). Um servidor
232
- dedicado recebe o subconjunto de servidor: Fabric API 0.58.0+1.19,
233
- Complete Config 2.0.0 e Multiplayer Server Pause 1.1.0. **Mod Menu** é
234
- exclusivamente de cliente e **Better Respawn** crasha o servidor ao salvar um
235
- jogador Creative recém-conectado (mixin dereferenciando `respawnDimension`
236
- não inicializado), então o jar é removido em `_ensure_voyager_mods`.
237
- - **`pip install -e . --no-deps`.** A distribuição é instalada e verificada, mas
238
- a resolução de dependências fica por conta de `requirements.txt` deste Space:
239
- deixar o pip re-resolver em boot moveria a pilha de inferência de um Space já
240
- em execução.
241
- - **Versões pinadas.** `chromadb==0.4.22` (o upstream fixa 0.3.29, anterior ao
242
- `langchain==0.0.350`) e `langchain-community==0.0.2` (exigido pelo
243
- `ChatOpenAI` usado pelo upstream). `cchardet` fica de fora de propósito: é um
244
- acelerador opcional do `chromadb` e compilá-lo no build do Space quebraria a
245
- build inteira.
246
- - **Modelo local.** `granite-4.0-h-tiny` no lugar do GPT-4, servido por
247
- `app.py` como endpoint OpenAI-compatible em `127.0.0.1:7860`.
248
- - **`learn(reset_env=False)`.** O reset do upstream é um hard reset do ambiente
249
- do Mineflayer; sem `azure_login` ele derrubaria a conexão a cada tarefa. O
250
- `Voyager.learn()` do upstream continua sendo o loop, só sem o reset.
251
-
252
- ## Mapa
253
-
254
- O mundo é um superflat de farm, com superfície em Y=64 (fixa em
255
- `minecraft_stack.WORLD_SURFACE_Y` e validada por `tests/test_world_map.py`): grama
256
- no topo, três camadas de terra, cascalho e uma faixa de minério de carvão até
257
- esmeralda entre 6 e 24 blocos abaixo da superfície, repetida na banda de
258
- deepslate no fundo da coluna. Sem lagos, sem features e sem estruturas, para a
259
- superfície continuar previsível para o pathfinder e para quem constrói.
260
-
261
- O mapa vive em `/persist/minecraft-friends/world-20260928-ores-y64-v1`. Como
262
- `generator-settings` só é lido quando o mundo é criado, trocar o mapa exige um
263
- diretório novo; os saves dos jogadores humanos são carregados para o mundo novo
264
- (`_carry_player_saves`) e o save do bot não é, para o Curriculum oficial sair do
265
- seu ramo de inventário cheio. O token OAuth da Xbox fica em
266
- `/persist/minecraft-friends/relay` e não é tocado pela troca de mapa.
267
-
268
- Os checkpoints continuam em
269
- `/persist/minecraft-friends/voyager/ckpt-20260927-flat-y64-v1` e
270
- `/persist/minecraft-friends/gemini-voyager/ckpt-20260927-flat-y64-v1`, porque a
271
- superfície continua plana em Y=64 e as skills aprendidas foram preservadas.
272
-
273
- Validação offline, sem iniciar modelos ou servidor de jogo:
274
- `python -m pytest tests -q --ignore=tests/test_player_save_diagnostics.py`
275
-
276
- O contrato do runtime (decisões upstream, adaptação declarada do retry do
277
- curriculum e patch aplicado sobre a árvore oficial) é verificado por
278
- `tests/test_voyager_official_contract.py` e `tests/test_voyager_patch_application.py`.
279
-
280
- ## Mapa normal 20261003 (Naldo)
281
-
282
- - Mundo novo de terreno normal: `/persist/minecraft-friends/world-20261003-normal-v1`
283
- (`minecraft:normal` com estruturas; sem camadas flat). Todos entram no spawn
284
- natural do mapa novo: nenhuma playerdata antiga e importada na troca
285
- flat->normal (posicao antiga enterraria o jogador na montanha, longe do Naldo).
286
- - Checkpoint novo e vazio: `/persist/minecraft-friends/voyager/ckpt-20261003-normal-v1`
287
- (resume=False; sem herdar skills, tasks ou posicoes do mapa antigo).
288
- - Antigos mantidos, nunca apagados: `world-20260928-ores-y64-v1`,
289
- `world-20260927-flat-y64-v1`, checkpoints `ckpt-20260927-flat-y64-v1` e o
290
- `relay/token.json` da Xbox (sem novo login).
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Minecraft Friends AI ZeroGPU
3
+ emoji: 🧠
4
+ colorFrom: blue
5
+ colorTo: green
6
+ sdk: gradio
7
+ sdk_version: 6.27.0
8
+ python_version: '3.12'
9
+ app_file: app.py
10
+ pinned: false
11
+ ---
12
+
13
+ # Programa — Naldo autônomo + endpoint CPU
14
+
15
+ O controlador padrão do `Naldo_Bot` é o **AltoClef 0.19** (comando `@gamer`,
16
+ speedrun survival real: equipamento, stronghold, dragão) com supervisão de
17
+ alto nível via **OpenCode Muse** (`muse-spark-1.3-contributor-free`). Mundo
18
+ **Survival / Normal**, mapa atual inalterado; o inventário existente do Naldo
19
+ é mantido (run assistida, sem itens dados nem teleporte). Status ao vivo em
20
+ `GET /opencode-bot/status` e log em `GET /opencode-bot/log`. O Voyager antigo
21
+ continua disponível apenas como alternativa manual (`VOYAGER_AUTOSTART=0` por
22
+ padrão); as seções Voyager abaixo são o legado manual.
23
+
24
+ ## Endpoint local de compatibilidade (Granite)
25
+
26
+ O endpoint OpenAI-compatible público continua disponível para clientes antigos e
27
+ para os componentes locais auxiliares. Ele não é mais o cérebro generativo do
28
+ `Naldo_Bot`; o Naldo usa OpenCode conforme a seção seguinte.
29
+
30
+ - GGUF oficial: `ibm-granite/granite-4.0-h-tiny-GGUF`
31
+ - Arquivo: `granite-4.0-h-tiny-Q4_K_M.gguf`
32
+ - Revisão fixada: `08d5a8a9741dd5c1a95d2d39e25253226aa1464e`
33
+ - Quantização: `Q4_K_M`
34
+ - Arquitetura: Granite 4.0 H-Tiny MoE/Mamba2, 7B totais e ~1B parâmetros ativos
35
+ - Contexto operacional do Voyager: 8.192 tokens
36
+ - Saída padrão: 384 tokens
37
+ - Saída máxima: 512 tokens
38
+ - Alias principal: `granite-4.0-h-tiny`
39
+ - CPU: 16 threads de decode e 16 threads de prefill/batch
40
+
41
+ Os aliases antigos permanecem aceitos apenas para compatibilidade de clientes e
42
+ continuam roteando para o Granite local. O Voyager do Naldo não usa esses aliases
43
+ para geração.
44
+
45
+ ## Cérebro do Naldo_Bot: OpenCode Muse + AltoClef (legado manual Voyager abaixo)
46
+
47
+ O Naldo ativo é o AltoClef 0.19 (`@gamer`) supervisionado pelo OpenCode Muse;
48
+ o restante desta seção descreve o legado manual do Voyager (alternativa
49
+ manual, `VOYAGER_AUTOSTART=0` por padrão).
50
+
51
+ Action, Curriculum, Critic e Skill Manager do `Naldo_Bot` usam uma ponte
52
+ OpenAI-compatible local em `127.0.0.1:7864`, que traduz as chamadas do Voyager
53
+ para um servidor `opencode serve` preso ao loopback em `127.0.0.1:7865`.
54
+
55
+ - OpenCode pinado: `opencode-ai@1.18.33`, instalado localmente no runtime sem `npm -g`.
56
+ - Provider: `opencode`.
57
+ - Modelo principal: `muse-spark-1.3-contributor-free`.
58
+ - Fallbacks: `fledge-alpha-free` e `nemotron-3-ultra-free`, somente do provider OpenCode gratuito.
59
+ - Nenhuma credencial do usuário é copiada; o processo recebe HOME/XDG próprios no runtime.
60
+ - As mensagens de inferência enviam `tools: {}`. No OpenCode 1.18.33 isso foi validado
61
+ sem execução de bash/arquivos; permissões customizadas de sessão não são usadas porque
62
+ o Zen gratuito as rejeita com `FreeTierError`.
63
+ - O bridge não inventa suporte a `temperature`/`max_tokens`: registra os valores pedidos
64
+ e preserva a resposta integral, evitando cortar JavaScript do Action Agent.
65
+ - Embeddings continuam locais em `127.0.0.1:7860/v1/embeddings`.
66
+ - Se OpenCode ou bridge morrerem, o supervisor interrompe o Naldo e recupera o cérebro
67
+ antes de religar o bot; não existe fallback generativo para Granite ou Gemini.
68
+
69
+ O Curriculum em Creative continua usando o estado real e os checkpoints persistentes.
70
+ A conclusão da tarefa continua exigindo verificação independente do mundo.
71
+
72
+ Referência do modelo:
73
+ https://huggingface.co/ibm-granite/granite-4.0-h-tiny-GGUF
74
+
75
+ ## Embeddings
76
+
77
+ O Voyager original usa embeddings no SkillManager e no cache de QA do CurriculumAgent.
78
+
79
+ - Modelo oficial: `Qwen/Qwen3-Embedding-0.6B-GGUF`
80
+ - Arquivo: `Qwen3-Embedding-0.6B-Q8_0.gguf`
81
+ - Revisão fixada: `370f27d7550e0def9b39c1f16d3fbaa13aa67728`
82
+ - Pooling: LAST, conforme documentação do Qwen3 Embedding para llama.cpp
83
+ - Vetores normalizados
84
+ - Alias OpenAI-compatible: `text-embedding-ada-002`
85
+
86
+ Referência:
87
+ https://huggingface.co/Qwen/Qwen3-Embedding-0.6B-GGUF
88
+
89
+ ## Inferência local somente em CPU
90
+
91
+ A inferência Granite e os embeddings locais não usam GPU:
92
+
93
+ - `CUDA_VISIBLE_DEVICES=""`
94
+ - `HIP_VISIBLE_DEVICES=""`
95
+ - `ROCR_VISIBLE_DEVICES=""`
96
+ - `GGML_VK_VISIBLE_DEVICES=""`
97
+ - `n_gpu_layers=0`
98
+ - `offload_kqv=False`
99
+ - `op_offload=False`
100
+ - wheel CPU do `llama-cpp-python==0.3.35`
101
+ - threads detectadas por affinity/cgroup
102
+ - mmap ativado
103
+ - chamadas de geração serializadas para evitar disputa de CPU
104
+
105
+ O decorador `@spaces.GPU` existente é somente a sentinela exigida pelo host ZeroGPU;
106
+ a função não é chamada pela API.
107
+
108
+ ## Compatibilidade Voyager (legado manual)
109
+
110
+ Por padrão o Voyager não inicia sozinho. `PLAYER_MODE=0`. O servidor não injeta o antigo prompt Bedrock.
111
+ Os dois Voyagers jogam em Creative: mineração, colocação, equipamento e inventário
112
+ são verificados a partir da observação real. O `placeBlocks` recebe o ID exato
113
+ da tarefa canônica; o agente não pode substituir `bricks` por `brick`.
114
+
115
+ O endpoint aceita temperatura 0.0, que coincide com os defaults do Voyager para
116
+ ActionAgent, CurriculumAgent, CriticAgent e SkillManager.
117
+
118
+ O endpoint mantém a compatibilidade HTTP de chat e embeddings para os clientes.
119
+
120
+ ## API
121
+
122
+ - `GET /`
123
+ - `GET /health`
124
+ - `GET /status`
125
+ - `GET /v1/models`
126
+ - `POST /v1/chat/completions`
127
+ - `POST /v1/embeddings`
128
+ - `GET /minecraft/status`
129
+ - `GET /opencode-bot/status` (Naldo ativo — AltoClef)
130
+ - `GET /opencode-bot/log`
131
+ - `GET /voyager/status` (alternativa manual)
132
+ - `GET /gemini-bot/status`
133
+
134
+ ## Segundo jogador: Gemini_Bot
135
+
136
+ `Gemini_Bot` executa uma segunda instância completa do Voyager no mesmo servidor
137
+ Java 1.19, com processo Mineflayer e checkpoint próprios. Curriculum, Action,
138
+ Critic e Skill Manager consultam o Gemini CLI por um proxy local exclusivo;
139
+ somente os embeddings usam o modelo local. O `Naldo_Bot` ativo é o AltoClef,
140
+ supervisionado pelo OpenCode Muse; o bridge OpenCode descrito acima serve
141
+ apenas à supervisão. Ambos validam tarefas Creative pela
142
+ mudança real no mundo ou pelo inventário.
143
+
144
+ O Curriculum permanece no modo automático do Voyager: cada IA observa o estado
145
+ atual, consulta seu checkpoint e decide o próximo objetivo. Não existe sequência
146
+ fixa nem fallback circular. Objetivos e projetos já concluídos ou falhados são
147
+ rejeitados semanticamente; a IA recebe o motivo e precisa escolher algo novo.
148
+ Se o provedor não produzir uma decisão válida, o bot permanece conectado e
149
+ aguarda com backoff, sem construir estruturas por roteiro.
150
+
151
+ Projetos suportados continuam verificáveis (`wall`, `bridge`, `room`, `tower`,
152
+ `road`, `arch`, `monument`, `shelter`, `courtyard` e `gate`). Quando a IA escolhe
153
+ um deles, a geometria é executada por `buildProject`, que usa `placeItem` e
154
+ registra todas as coordenadas físicas para o Critic. Um projeto concluído não
155
+ pode ser escolhido novamente. Naldo_Bot e Gemini_Bot tomam decisões separadas e
156
+ mantêm checkpoints independentes.
157
+
158
+ O adaptador `/pause` não envia o comando global do mod: os dois bots e os
159
+ jogadores Xbox compartilham um mundo que continua rodando durante a inferência.
160
+ `placeBlocks` prioriza destinos com linha de visão e usa a face encontrada por
161
+ `GoalPlaceBlock`, mantendo a confirmação do bloco no mundo. A física está fixada
162
+ em `prismarine-physics@1.6.0`, que inclui a correção oficial de água no Minecraft
163
+ 1.19; os quatro pins do protocolo permanecem inalterados.
164
+ Os logs `[llm_metric]` registram bot, papel, latência e tokens reais por chamada
165
+ de Curriculum, Action, Critic e Skill Manager. No Gemini CLI, a temperatura zero
166
+ é aplicada por `modelConfigs.customOverrides`, além do cliente Voyager.
167
+
168
+ Se as construções cercarem o bot, o helper procura uma área de superfície já
169
+ carregada e livre, a 8–12 blocos por eixo. O voo Creative de recuperação verifica
170
+ o volume do jogador em toda a rota, usa segmentos de até 0,4 bloco, sobe no máximo
171
+ 4 blocos para ultrapassar a construção e pousa em solo confirmado. Não destrói
172
+ blocos, não teleporta e não altera a exploração horizontal do Curriculum.
173
+
174
+ - CLI fixado em `@google/gemini-cli@0.61.0`, modelo efetivo `gemini-3.5-flash-lite`.
175
+ - Segredos privados do Space: `GEMINI_BOT_KEY_1` a `GEMINI_BOT_KEY_6`.
176
+ - Nenhuma chave deve ser salva no Git, no checkpoint ou nas saídas de status.
177
+ - Status: `/gemini-bot/status` (conexão, tarefas, métricas e falhas por posição
178
+ da chave; nunca revela valores de chaves).
179
+ - Controle de inicialização: `GEMINI_BOT_AUTOSTART=0` desativa somente o
180
+ segundo bot. O Naldo_Bot e o mundo persistente seguem independentes.
181
+
182
+ API pública de compatibilidade:
183
+
184
+ `https://erinaldordso-minecraft-friends-ai-zerogpu.hf.space/v1`
185
+
186
+ Modelo de chat público (não é o cérebro do Naldo):
187
+
188
+ `granite-4.0-h-tiny`
189
+
190
+ Cérebro interno do Naldo:
191
+
192
+ `opencode/muse-spark-1.3-contributor-free` via `127.0.0.1:7864/v1`
193
+
194
+ Modelo de embeddings:
195
+
196
+ `text-embedding-ada-002`
197
+
198
+ ## Upstream Voyager
199
+
200
+ Os dois processos instanciam as classes de currículo, Action, Critic, Skill
201
+ Manager e o loop `Voyager.learn()` do mesmo checkout MineDojo/Voyager fixado em
202
+ `55e45a880755d0c8c66ca7fb5fe7962ac8974f89`. Cada runner verifica o HEAD
203
+ do checkout e a origem das cinco classes antes de aprender; os endpoints de
204
+ status expõem `engine_runtime` apenas para o PID validado. Os adaptadores
205
+ Creative e os parsers necessários aos modelos não são código byte a byte igual
206
+ ao upstream. Checkpoints e mundo ficam em `/persist` e não são substituídos
207
+ pela atualização do código.
208
+
209
+ Projeto original:
210
+ https://github.com/MineDojo/Voyager
211
+
212
+ Este Space executa o Voyager fixado em `55e45a880755d0c8c66ca7fb5fe7962ac8974f89`
213
+ com correções de reconexão, observações nulas e exploração horizontal limitada.
214
+ O `mineBlock` só aceita blocos até dois níveis abaixo dos pés, para o bot cavar
215
+ um poço de onde consegue sair, e o pathfinder mantém a escavação do upstream
216
+ justamente por isso.
217
+
218
+ ## Instalação conforme a página oficial
219
+
220
+ O `README.md`, `installation/minecraft_instance_install.md` e
221
+ `installation/fabric_mods_install.md` do upstream são o contrato de instalação.
222
+ `tests/test_installation_conformance.py` trava o que é possível automatizar.
223
+
224
+ | Passo oficial | Onde está neste Space |
225
+ | --- | --- |
226
+ | Python >= 3.9 | `voyager_stack.MIN_PYTHON`, verificado no boot |
227
+ | Node.js >= 16.13.0 | `voyager_stack.MIN_NODE`, verificado no boot |
228
+ | `git clone` | `VoyagerStack._ensure_source`, no commit fixado |
229
+ | `pip install -e .` | `VoyagerStack._ensure_python_package`, com verificação posterior |
230
+ | `npm install` + `npx tsc` em `mineflayer-collectblock`, depois `npm install` em `voyager/env/mineflayer` | `VoyagerStack._ensure_node` |
231
+ | Dependências de `requirements.txt` | `requirements.txt` deste repositório |
232
+ | `Voyager(ckpt_dir=..., resume=True)` para retomar | `voyager_runner.py` deriva `resume` dos arquivos do checkpoint e o passa ao construtor |
233
+ | Mundo em Creative + Peaceful | `server.properties` |
234
+ | `fabric-loader-0.14.18-1.19` | instalador Fabric pinado em `minecraft_stack.py` |
235
+
236
+ Desvios, todos deliberados:
237
+
238
+ - **`mc_port` em vez de `azure_login`.** O README aceita os dois ("You can also
239
+ use mc_port instead of azure_login"). Este Space sobe um servidor Bedrock
240
+ dedicado em `127.0.0.1:25565` com Geyser/ViaProxy para os amigos Xbox, então
241
+ não existe `MinecraftInstance` local para o `azure_login` abrir. A
242
+ reconexão automática do upstream é substituída pela supervisor do Space e
243
+ pelos patches de recuperação não destrutivos.
244
+ - **Subconjunto de mods do Fabric.** A lista de 5 mods da página é para um
245
+ *cliente* (o próprio README diz para abrir o mundo em LAN). Um servidor
246
+ dedicado recebe o subconjunto de servidor: Fabric API 0.58.0+1.19,
247
+ Complete Config 2.0.0 e Multiplayer Server Pause 1.1.0. **Mod Menu** é
248
+ exclusivamente de cliente e **Better Respawn** crasha o servidor ao salvar um
249
+ jogador Creative recém-conectado (mixin dereferenciando `respawnDimension`
250
+ não inicializado), então o jar é removido em `_ensure_voyager_mods`.
251
+ - **`pip install -e . --no-deps`.** A distribuição é instalada e verificada, mas
252
+ a resolução de dependências fica por conta de `requirements.txt` deste Space:
253
+ deixar o pip re-resolver em boot moveria a pilha de inferência de um Space já
254
+ em execução.
255
+ - **Versões pinadas.** `chromadb==0.4.22` (o upstream fixa 0.3.29, anterior ao
256
+ `langchain==0.0.350`) e `langchain-community==0.0.2` (exigido pelo
257
+ `ChatOpenAI` usado pelo upstream). `cchardet` fica de fora de propósito: é um
258
+ acelerador opcional do `chromadb` e compilá-lo no build do Space quebraria a
259
+ build inteira.
260
+ - **Modelo local.** `granite-4.0-h-tiny` no lugar do GPT-4, servido por
261
+ `app.py` como endpoint OpenAI-compatible em `127.0.0.1:7860`.
262
+ - **`learn(reset_env=False)`.** O reset do upstream é um hard reset do ambiente
263
+ do Mineflayer; sem `azure_login` ele derrubaria a conexão a cada tarefa. O
264
+ `Voyager.learn()` do upstream continua sendo o loop, só sem o reset.
265
+
266
+ ## Mapa
267
+
268
+ O mundo é um superflat de farm, com superfície em Y=64 (fixa em
269
+ `minecraft_stack.WORLD_SURFACE_Y` e validada por `tests/test_world_map.py`): grama
270
+ no topo, três camadas de terra, cascalho e uma faixa de minério de carvão até
271
+ esmeralda entre 6 e 24 blocos abaixo da superfície, repetida na banda de
272
+ deepslate no fundo da coluna. Sem lagos, sem features e sem estruturas, para a
273
+ superfície continuar previsível para o pathfinder e para quem constrói.
274
+
275
+ O mapa vive em `/persist/minecraft-friends/world-20260928-ores-y64-v1`. Como
276
+ `generator-settings` só é lido quando o mundo é criado, trocar o mapa exige um
277
+ diretório novo; os saves dos jogadores humanos são carregados para o mundo novo
278
+ (`_carry_player_saves`) e o save do bot não é, para o Curriculum oficial sair do
279
+ seu ramo de inventário cheio. O token OAuth da Xbox fica em
280
+ `/persist/minecraft-friends/relay` e não é tocado pela troca de mapa.
281
+
282
+ Os checkpoints continuam em
283
+ `/persist/minecraft-friends/voyager/ckpt-20260927-flat-y64-v1` e
284
+ `/persist/minecraft-friends/gemini-voyager/ckpt-20260927-flat-y64-v1`, porque a
285
+ superfície continua plana em Y=64 e as skills aprendidas foram preservadas.
286
+
287
+ Validação offline, sem iniciar modelos ou servidor de jogo:
288
+ `python -m pytest tests -q --ignore=tests/test_player_save_diagnostics.py`
289
+
290
+ O contrato do runtime (decisões upstream, adaptação declarada do retry do
291
+ curriculum e patch aplicado sobre a árvore oficial) é verificado por
292
+ `tests/test_voyager_official_contract.py` e `tests/test_voyager_patch_application.py`.
293
+
294
+ ## Mapa normal 20261003 (Naldo)
295
+
296
+ - Mundo novo de terreno normal: `/persist/minecraft-friends/world-20261003-normal-v1`
297
+ (`minecraft:normal` com estruturas; sem camadas flat). Todos entram no spawn
298
+ natural do mapa novo: nenhuma playerdata antiga e importada na troca
299
+ flat->normal (posicao antiga enterraria o jogador na montanha, longe do Naldo).
300
+ - Checkpoint novo e vazio: `/persist/minecraft-friends/voyager/ckpt-20261003-normal-v1`
301
+ (resume=False; sem herdar skills, tasks ou posicoes do mapa antigo).
302
+ - Antigos mantidos, nunca apagados: `world-20260928-ores-y64-v1`,
303
+ `world-20260927-flat-y64-v1`, checkpoints `ckpt-20260927-flat-y64-v1` e o
304
+ `relay/token.json` da Xbox (sem novo login).
altoclef/SpaceBridge.java CHANGED
@@ -10,13 +10,30 @@ import java.net.InetSocketAddress;
10
  import java.nio.charset.StandardCharsets;
11
  import java.util.*;
12
  import java.util.concurrent.*;
 
13
 
14
- /** Local telemetry/control adapter. Gameplay remains in the upstream AltoClef mod. */
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
  public final class SpaceBridge implements ClientModInitializer {
16
  private static final MappingResolver MAP = FabricLoader.getInstance().getMappingResolver();
17
- private volatile String state = "{\"connected\":false,\"loading\":true}";
18
  private volatile String lastError = "";
19
  private volatile String lastCommand = "";
 
20
  private long connectAttempt;
21
  private long creditsSince;
22
  private boolean creditsObserved;
@@ -26,20 +43,46 @@ public final class SpaceBridge implements ClientModInitializer {
26
  private static Class<?> mc(String intermediary) throws Exception {
27
  return Class.forName(MAP.mapClassName("intermediary", "net.minecraft." + intermediary));
28
  }
 
 
 
 
 
 
 
 
 
29
  private static Object method(Object obj, String owner, String id, String desc,
30
  Class<?>[] types, Object... args) throws Exception {
31
  String name = MAP.mapMethodName("intermediary", "net.minecraft." + owner, id, desc);
32
- return mc(owner).getMethod(name, types).invoke(obj, args);
 
 
 
33
  }
34
  private static Object call(Object obj, String name) throws Exception {
35
- return obj.getClass().getMethod(name).invoke(obj);
36
  }
37
  private static Object client() throws Exception {
38
  return method(null, "class_310", "method_1551", "()Lnet/minecraft/class_310;", new Class<?>[0]);
39
  }
 
 
 
 
 
 
 
 
40
  private static Object screen(Object client) throws Exception {
41
  String name = MAP.mapFieldName("intermediary", "net.minecraft.class_310", "field_1755", "Lnet/minecraft/class_437;");
42
- return mc("class_310").getField(name).get(client);
 
 
 
 
 
 
43
  }
44
  private static void respond(HttpExchange ex, int code, String body) throws Exception {
45
  byte[] data = body.getBytes(StandardCharsets.UTF_8);
@@ -48,6 +91,43 @@ public final class SpaceBridge implements ClientModInitializer {
48
  ex.getResponseBody().write(data);
49
  ex.close();
50
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51
  @Override public void onInitializeClient() {
52
  try {
53
  int port = Integer.parseInt(System.getenv().getOrDefault("ALTOCLEF_BRIDGE_PORT", "3002"));
@@ -62,17 +142,23 @@ public final class SpaceBridge implements ClientModInitializer {
62
  if (!Set.of("gamer", "stop", "status").contains(command)) {
63
  respond(ex, 400, "{\"error\":\"unsupported command\"}"); return;
64
  }
65
- ((Executor) client()).execute(() -> {
66
- try {
67
- Class<?> alto = Class.forName("adris.altoclef.AltoClef");
68
- Object executor = alto.getMethod("getCommandExecutor").invoke(null);
69
- if (executor == null) throw new IllegalStateException("AltoClef is not initialized");
70
- executor.getClass().getMethod("executeWithPrefix", String.class).invoke(executor, command);
71
- lastCommand = command;
72
- lastError = "";
73
- System.out.println("[space-altoclef] command=" + command);
74
- } catch (Exception err) { lastError = err.toString(); }
75
- });
 
 
 
 
 
 
76
  respond(ex, 202, "{\"accepted\":true}");
77
  } catch (Exception err) {
78
  try { respond(ex, 503, json(Map.of("error", err.toString()))); } catch (Exception ignored) { ex.close(); }
@@ -83,8 +169,12 @@ public final class SpaceBridge implements ClientModInitializer {
83
  Executors.newSingleThreadScheduledExecutor(r -> {
84
  Thread t = new Thread(r, "space-altoclef-telemetry"); t.setDaemon(true); return t;
85
  }).scheduleWithFixedDelay(() -> {
86
- try { ((Executor) client()).execute(this::snapshot); }
87
- catch (Exception err) { lastError = err.toString(); }
 
 
 
 
88
  }, 2, 1, TimeUnit.SECONDS);
89
  System.out.println("[space-altoclef] local bridge ready on 127.0.0.1:" + port);
90
  } catch (Exception err) { throw new RuntimeException("Space bridge failed", err); }
@@ -103,6 +193,13 @@ public final class SpaceBridge implements ClientModInitializer {
103
  screen(client), client, parsed, info);
104
  System.out.println("[space-altoclef] connecting to " + address);
105
  }
 
 
 
 
 
 
 
106
  private void snapshot() {
107
  Map<String,Object> data = new LinkedHashMap<>();
108
  try {
@@ -130,8 +227,7 @@ public final class SpaceBridge implements ClientModInitializer {
130
  if (player == null) {
131
  if (executor != null && !credits) connect(client);
132
  } else {
133
- String dimension = String.valueOf(Class.forName("adris.altoclef.util.helpers.WorldHelper")
134
- .getMethod("getCurrentDimension").invoke(null));
135
  if ("END".equals(dimension)) enteredEnd = true;
136
  data.put("dimension", dimension);
137
  data.put("returned_from_end", enteredEnd && "OVERWORLD".equals(dimension));
@@ -164,6 +260,7 @@ public final class SpaceBridge implements ClientModInitializer {
164
  lastError = err.toString();
165
  data.put("error", lastError);
166
  }
 
167
  data.put("observed_at", System.currentTimeMillis() / 1000.0);
168
  state = json(data);
169
  }
 
10
  import java.nio.charset.StandardCharsets;
11
  import java.util.*;
12
  import java.util.concurrent.*;
13
+ import java.util.concurrent.atomic.AtomicBoolean;
14
 
15
+ /** Local telemetry/control adapter. Gameplay remains in the upstream AltoClef mod.
16
+ *
17
+ * <p>Threading contract: every read or mutation of Minecraft client state
18
+ * ({@link #snapshot}, {@link #connect}, AltoClef commands) runs ONLY on the
19
+ * Minecraft client thread, reached through {@code Executor} dispatch (the
20
+ * client implements {@code java.util.concurrent.Executor}) with a reflective
21
+ * {@code execute(Runnable)} fallback. Dispatch is never run inline on a
22
+ * telemetry or HTTP thread: a failed dispatch records a diagnostic and the
23
+ * bridge keeps reporting a loading/error heartbeat WITHOUT claiming fresh
24
+ * connected world observations.
25
+ *
26
+ * <p>Freshness contract for /state: {@code heartbeat_at} is refreshed by the
27
+ * scheduler tick itself (bridge alive), while {@code observed_at} is refreshed
28
+ * only by a snapshot that actually ran on the client thread. At most one
29
+ * snapshot is ever queued, so rendering load cannot build a backlog.
30
+ */
31
  public final class SpaceBridge implements ClientModInitializer {
32
  private static final MappingResolver MAP = FabricLoader.getInstance().getMappingResolver();
33
+ private volatile String state = "{\"connected\":false,\"loading\":true,\"heartbeat_at\":0}";
34
  private volatile String lastError = "";
35
  private volatile String lastCommand = "";
36
+ private final AtomicBoolean snapshotPending = new AtomicBoolean(false);
37
  private long connectAttempt;
38
  private long creditsSince;
39
  private boolean creditsObserved;
 
43
  private static Class<?> mc(String intermediary) throws Exception {
44
  return Class.forName(MAP.mapClassName("intermediary", "net.minecraft." + intermediary));
45
  }
46
+ private static Method accessibleMethod(Class<?> owner, String name, Class<?>[] types) throws Exception {
47
+ try {
48
+ return owner.getMethod(name, types);
49
+ } catch (NoSuchMethodException missing) {
50
+ Method fallback = owner.getDeclaredMethod(name, types);
51
+ fallback.setAccessible(true);
52
+ return fallback;
53
+ }
54
+ }
55
  private static Object method(Object obj, String owner, String id, String desc,
56
  Class<?>[] types, Object... args) throws Exception {
57
  String name = MAP.mapMethodName("intermediary", "net.minecraft." + owner, id, desc);
58
+ return accessibleMethod(mc(owner), name, types).invoke(obj, args);
59
+ }
60
+ private static Object call(Object obj, String name, Class<?>[] types, Object... args) throws Exception {
61
+ return accessibleMethod(obj.getClass(), name, types).invoke(obj, args);
62
  }
63
  private static Object call(Object obj, String name) throws Exception {
64
+ return call(obj, name, new Class<?>[0]);
65
  }
66
  private static Object client() throws Exception {
67
  return method(null, "class_310", "method_1551", "()Lnet/minecraft/class_310;", new Class<?>[0]);
68
  }
69
+ /** Enqueue on the client thread. Never runs the task inline: throws on failure. */
70
+ private static void dispatchToClient(Object client, Runnable task) throws Exception {
71
+ if (client instanceof Executor) {
72
+ ((Executor) client).execute(task);
73
+ return;
74
+ }
75
+ accessibleMethod(client.getClass(), "execute", new Class<?>[]{Runnable.class}).invoke(client, task);
76
+ }
77
  private static Object screen(Object client) throws Exception {
78
  String name = MAP.mapFieldName("intermediary", "net.minecraft.class_310", "field_1755", "Lnet/minecraft/class_437;");
79
+ try {
80
+ return mc("class_310").getField(name).get(client);
81
+ } catch (NoSuchFieldException missing) {
82
+ Field fallback = mc("class_310").getDeclaredField(name);
83
+ fallback.setAccessible(true);
84
+ return fallback.get(client);
85
+ }
86
  }
87
  private static void respond(HttpExchange ex, int code, String body) throws Exception {
88
  byte[] data = body.getBytes(StandardCharsets.UTF_8);
 
91
  ex.getResponseBody().write(data);
92
  ex.close();
93
  }
94
+ /** Loading/error heartbeat: fresh heartbeat_at, no connected observations claimed. */
95
+ private void heartbeat(String detail) {
96
+ Map<String, Object> data = new LinkedHashMap<>();
97
+ data.put("connected", false);
98
+ data.put("loading", true);
99
+ data.put("heartbeat_at", System.currentTimeMillis() / 1000.0);
100
+ data.put("dispatch_error", detail == null ? "" : detail);
101
+ data.put("error", lastError);
102
+ data.put("last_command", lastCommand);
103
+ state = json(data);
104
+ }
105
+ private void queueSnapshot() {
106
+ // At most one pending snapshot: skip the tick when the client thread
107
+ // has not drained the previous one (e.g. under rendering load).
108
+ if (!snapshotPending.compareAndSet(false, true)) {
109
+ heartbeat("snapshot still queued on client thread");
110
+ return;
111
+ }
112
+ boolean queued = false;
113
+ try {
114
+ dispatchToClient(client(), () -> {
115
+ try {
116
+ snapshot();
117
+ } finally {
118
+ snapshotPending.set(false);
119
+ }
120
+ });
121
+ queued = true;
122
+ } catch (Exception err) {
123
+ lastError = "client dispatch failed: " + err;
124
+ } finally {
125
+ if (!queued) {
126
+ snapshotPending.set(false);
127
+ heartbeat(lastError);
128
+ }
129
+ }
130
+ }
131
  @Override public void onInitializeClient() {
132
  try {
133
  int port = Integer.parseInt(System.getenv().getOrDefault("ALTOCLEF_BRIDGE_PORT", "3002"));
 
142
  if (!Set.of("gamer", "stop", "status").contains(command)) {
143
  respond(ex, 400, "{\"error\":\"unsupported command\"}"); return;
144
  }
145
+ try {
146
+ dispatchToClient(client(), () -> {
147
+ try {
148
+ Class<?> alto = Class.forName("adris.altoclef.AltoClef");
149
+ Object executor = alto.getMethod("getCommandExecutor").invoke(null);
150
+ if (executor == null) throw new IllegalStateException("AltoClef is not initialized");
151
+ executor.getClass().getMethod("executeWithPrefix", String.class).invoke(executor, command);
152
+ lastCommand = command;
153
+ lastError = "";
154
+ System.out.println("[space-altoclef] command=" + command);
155
+ } catch (Exception err) { lastError = err.toString(); }
156
+ });
157
+ } catch (Exception err) {
158
+ lastError = "command dispatch failed: " + err;
159
+ respond(ex, 503, json(Map.of("error", lastError)));
160
+ return;
161
+ }
162
  respond(ex, 202, "{\"accepted\":true}");
163
  } catch (Exception err) {
164
  try { respond(ex, 503, json(Map.of("error", err.toString()))); } catch (Exception ignored) { ex.close(); }
 
169
  Executors.newSingleThreadScheduledExecutor(r -> {
170
  Thread t = new Thread(r, "space-altoclef-telemetry"); t.setDaemon(true); return t;
171
  }).scheduleWithFixedDelay(() -> {
172
+ try {
173
+ queueSnapshot();
174
+ } catch (Throwable err) {
175
+ lastError = "telemetry scheduler: " + err;
176
+ heartbeat(lastError);
177
+ }
178
  }, 2, 1, TimeUnit.SECONDS);
179
  System.out.println("[space-altoclef] local bridge ready on 127.0.0.1:" + port);
180
  } catch (Exception err) { throw new RuntimeException("Space bridge failed", err); }
 
193
  screen(client), client, parsed, info);
194
  System.out.println("[space-altoclef] connecting to " + address);
195
  }
196
+ private String currentDimension() throws Exception {
197
+ // Upstream WorldHelper.getCurrentDimension is package-private static;
198
+ // resolve it as a declared method so snapshots survive visibility.
199
+ Class<?> helper = Class.forName("adris.altoclef.util.helpers.WorldHelper");
200
+ return String.valueOf(accessibleMethod(helper, "getCurrentDimension", new Class<?>[0]).invoke(null));
201
+ }
202
+ /** Runs ONLY on the Minecraft client thread. Refreshes observed_at. */
203
  private void snapshot() {
204
  Map<String,Object> data = new LinkedHashMap<>();
205
  try {
 
227
  if (player == null) {
228
  if (executor != null && !credits) connect(client);
229
  } else {
230
+ String dimension = currentDimension();
 
231
  if ("END".equals(dimension)) enteredEnd = true;
232
  data.put("dimension", dimension);
233
  data.put("returned_from_end", enteredEnd && "OVERWORLD".equals(dimension));
 
260
  lastError = err.toString();
261
  data.put("error", lastError);
262
  }
263
+ data.put("heartbeat_at", System.currentTimeMillis() / 1000.0);
264
  data.put("observed_at", System.currentTimeMillis() / 1000.0);
265
  state = json(data);
266
  }
altoclef/build.py CHANGED
@@ -2,6 +2,7 @@
2
  from pathlib import Path
3
  import hashlib
4
  import json
 
5
  import subprocess
6
  import tempfile
7
  import urllib.request
@@ -10,21 +11,48 @@ import zipfile
10
  ROOT = Path(__file__).resolve().parent
11
  LOADER_URL = "https://maven.fabricmc.net/net/fabricmc/fabric-loader/0.16.2/fabric-loader-0.16.2.jar"
12
  LOADER_SHA256 = "e24de359a5ea3b3b9f9fd20f2fe064197cf0f8165e9ae868d25e813b1cd87593"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
 
14
  def build():
 
15
  with tempfile.TemporaryDirectory() as tmp:
16
  tmp = Path(tmp)
17
  loader = tmp / "fabric-loader.jar"
18
- with urllib.request.urlopen(LOADER_URL, timeout=60) as response:
19
- raw = response.read()
20
- if hashlib.sha256(raw).hexdigest() != LOADER_SHA256:
21
- raise RuntimeError("Fabric loader checksum mismatch")
22
- loader.write_bytes(raw)
23
- subprocess.run([
24
- "java", "-m", "jdk.compiler/com.sun.tools.javac.Main", "--release", "17",
25
- "-cp", str(loader), "-d", str(tmp), str(ROOT / "SpaceBridge.java"),
26
- ], check=True)
27
- metadata = {"schemaVersion": 1, "id": "space_altoclef_bridge", "version": "1.0.1",
 
 
 
 
 
28
  "name": "Space AltoClef Bridge", "environment": "client",
29
  "entrypoints": {"client": ["space.minecraft.SpaceBridge"]},
30
  "depends": {"fabricloader": ">=0.16.2", "minecraft": "1.19.4",
 
2
  from pathlib import Path
3
  import hashlib
4
  import json
5
+ import os
6
  import subprocess
7
  import tempfile
8
  import urllib.request
 
11
  ROOT = Path(__file__).resolve().parent
12
  LOADER_URL = "https://maven.fabricmc.net/net/fabricmc/fabric-loader/0.16.2/fabric-loader-0.16.2.jar"
13
  LOADER_SHA256 = "e24de359a5ea3b3b9f9fd20f2fe064197cf0f8165e9ae868d25e813b1cd87593"
14
+ # Reproducible local build: point at an already-downloaded loader jar instead
15
+ # of the network (e.g. a copy kept under .deploy-validation).
16
+ LOADER_JAR_OVERRIDE = os.environ.get("FABRIC_LOADER_JAR", "")
17
+
18
+ def _loader_bytes() -> bytes:
19
+ if LOADER_JAR_OVERRIDE:
20
+ raw = Path(LOADER_JAR_OVERRIDE).read_bytes()
21
+ else:
22
+ with urllib.request.urlopen(LOADER_URL, timeout=60) as response:
23
+ raw = response.read()
24
+ if hashlib.sha256(raw).hexdigest() != LOADER_SHA256:
25
+ raise RuntimeError("Fabric loader checksum mismatch")
26
+ return raw
27
+
28
+ def _javac(java_home: str = "") -> list[str]:
29
+ exe = "java.exe" if os.name == "nt" else "java"
30
+ if java_home:
31
+ java = str(Path(java_home) / "bin" / exe)
32
+ else:
33
+ java = exe
34
+ return [java, "-m", "jdk.compiler/com.sun.tools.javac.Main"]
35
 
36
  def build():
37
+ java_home = os.environ.get("JAVA_HOME", "")
38
  with tempfile.TemporaryDirectory() as tmp:
39
  tmp = Path(tmp)
40
  loader = tmp / "fabric-loader.jar"
41
+ loader.write_bytes(_loader_bytes())
42
+ subprocess.run(
43
+ _javac(java_home)
44
+ + [
45
+ "--release",
46
+ "17",
47
+ "-cp",
48
+ str(loader),
49
+ "-d",
50
+ str(tmp),
51
+ str(ROOT / "SpaceBridge.java"),
52
+ ],
53
+ check=True,
54
+ )
55
+ metadata = {"schemaVersion": 1, "id": "space_altoclef_bridge", "version": "1.0.2",
56
  "name": "Space AltoClef Bridge", "environment": "client",
57
  "entrypoints": {"client": ["space.minecraft.SpaceBridge"]},
58
  "depends": {"fabricloader": ">=0.16.2", "minecraft": "1.19.4",
altoclef/space-altoclef-bridge.jar CHANGED
Binary files a/altoclef/space-altoclef-bridge.jar and b/altoclef/space-altoclef-bridge.jar differ
 
altoclef_stack.py CHANGED
@@ -15,35 +15,52 @@ from typing import Any
15
  import requests
16
 
17
  from minecraft_stack import STACK, PERSIST_ROOT, _download, _wait_tcp
18
- from opencode_config import (OPENCODE_VERSION, MAIN_MODEL, MINE_BASE, configuration,
19
  child_environment, parse_decision, goal_completed)
20
  from voyager_processes import stop_runner
21
 
22
  SOURCE = Path(__file__).resolve().parent
23
  ROOT = Path(os.environ.get("ALTOCLEF_HOME", str(PERSIST_ROOT / "altoclef")))
24
- CLIENT = ROOT / "minecraft-client"
 
 
 
 
25
  COACH = ROOT / "opencode"
26
  MC_VERSION = "1.19.4"
27
  LOADER_VERSION = "0.16.2"
28
- USERNAME = "OpenCode_Bot"
 
 
29
  BRIDGE_PORT = 3002
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
  ALTOCLEF_URL = "https://github.com/MiranCZ/altoclef/releases/download/0.19/altoclef-1.19.4-0.19.jar"
31
  ALTOCLEF_SHA256 = "fe6f6f8b52ed8a8d8a382f1b0e8c85145f038d2c5ec831710eb4f74a6db489b8"
32
  FABRIC_API_URL = "https://maven.fabricmc.net/net/fabricmc/fabric-api/fabric-api/0.87.2+1.19.4/fabric-api-0.87.2+1.19.4.jar"
33
 
34
- # The server remains Creative/Peaceful. Missing resources are supplied only to
35
- # this player's inventory; no world reset, teleport, portal construction or
36
- # dragon-kill command is used. AltoClef discovers/uses the actual stronghold.
37
- CREATIVE_LOADOUT = {
38
- "diamond_pickaxe": 1, "diamond_sword": 1,
39
- "diamond_helmet": 1, "diamond_chestplate": 1,
40
- "diamond_leggings": 1, "diamond_boots": 1,
41
- "shield": 1, "water_bucket": 1, "flint_and_steel": 1,
42
- "ender_eye": 64, "cooked_beef": 64, "cobblestone": 128,
43
- "oak_log": 32, "oak_planks": 64, "crafting_table": 1,
44
- "furnace": 1, "smoker": 1, "white_bed": 10,
45
- "iron_ingot": 32, "bow": 1, "arrow": 64,
46
- }
47
 
48
 
49
  class AltoClefStack:
@@ -62,9 +79,13 @@ class AltoClefStack:
62
  self.model_errors = 0
63
  self.last_decision: dict[str, Any] = {}
64
  self.opencode_version = ""
65
- self.opencode_model = os.environ.get("ALTOCLEF_OPENCODE_MODEL", f"mine/{MAIN_MODEL}")
66
  self.last_started_at: float | None = None
67
  self.next_retry_at = 0.0
 
 
 
 
68
  saved = ROOT / "status.json"
69
  if saved.exists():
70
  try:
@@ -108,7 +129,7 @@ class AltoClefStack:
108
  self.opencode_version = report.stdout.strip()
109
  if self.opencode_version != OPENCODE_VERSION:
110
  raise RuntimeError("Installed OpenCode version differs from reviewed version")
111
- (COACH / "opencode.json").write_text(json.dumps(configuration(os.environ.get("VOYAGER_BRAIN_BASE_URL", MINE_BASE)), indent=2))
112
  return shim
113
 
114
  def _ensure_client(self, java: Path) -> list[str]:
@@ -116,13 +137,19 @@ class AltoClefStack:
116
  CLIENT.mkdir(parents=True, exist_ok=True)
117
  version = f"fabric-loader-{LOADER_VERSION}-{MC_VERSION}"
118
  if not (CLIENT / "versions" / version / (version + ".json")).exists():
119
- self._log("installing official Minecraft client " + MC_VERSION + " and Fabric " + LOADER_VERSION)
 
120
  launcher.fabric.install_fabric(MC_VERSION, str(CLIENT), loader_version=LOADER_VERSION, java=str(java),
121
- callback={"setStatus": lambda text: self._log("installer: " + text)})
122
  mods = CLIENT / "mods"
123
  mods.mkdir(exist_ok=True)
124
- _download(ALTOCLEF_URL, mods / "altoclef-1.19.4-0.19.jar", ALTOCLEF_SHA256)
125
- _download(FABRIC_API_URL, mods / "fabric-api-0.87.2+1.19.4.jar")
 
 
 
 
 
126
  shutil.copyfile(SOURCE / "altoclef/space-altoclef-bridge.jar", mods / "space-altoclef-bridge.jar")
127
  settings = CLIENT / "options.txt"
128
  if not settings.exists():
@@ -143,14 +170,50 @@ class AltoClefStack:
143
  "customResolution":True, "resolutionWidth":"640", "resolutionHeight":"360",
144
  })
145
 
 
 
 
 
 
 
 
 
 
146
  def _observe(self) -> dict[str, Any]:
147
  response = requests.get(f"http://127.0.0.1:{BRIDGE_PORT}/state", timeout=5)
148
  response.raise_for_status()
149
  data = response.json()
150
  if not isinstance(data, dict):
151
  raise RuntimeError("Invalid AltoClef telemetry")
152
- if time.time() - float(data.get("observed_at") or 0) > 30:
153
- raise RuntimeError("AltoClef client telemetry stopped updating")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
154
  self.observation = data
155
  self._checkpoint()
156
  return data
@@ -168,26 +231,20 @@ class AltoClefStack:
168
  response.raise_for_status()
169
  self._log("AltoClef command: @" + command)
170
 
171
- def _supply_creative(self, data: dict[str, Any]) -> None:
172
- if not data.get("creative"):
173
- return
174
- counts: dict[str,int] = {}
175
- for item in data.get("inventory") or []:
176
- name = str(item.get("item") or "").removeprefix("minecraft:")
177
- counts[name] = counts.get(name, 0) + int(item.get("count") or 0)
178
- missing = [(name, count - counts.get(name, 0)) for name, count in CREATIVE_LOADOUT.items()
179
- if count > counts.get(name, 0)]
180
- # Wait until initial loadout has been consumed/recognized. Do not refill
181
- # after every block: AltoClef retains its own inventory/gear management.
182
  server = STACK.processes.get("minecraft")
183
  if server is None or server.poll() is not None or server.stdin is None:
184
- raise RuntimeError("Minecraft console unavailable for Creative equipment")
185
- if missing:
186
- with STACK.lock:
187
- for name, count in missing:
188
- server.stdin.write(f"give {USERNAME} minecraft:{name} {count}\n")
189
- server.stdin.flush()
190
- self._log("Creative loadout: refilled " + str(len(missing)) + " missing item types")
191
 
192
  def _consult(self, exe: Path, data: dict[str, Any]) -> None:
193
  compact = {key:data.get(key) for key in ["connected","dimension","position","creative","task_active","tasks",
@@ -196,10 +253,12 @@ class AltoClefStack:
196
  env = child_environment(COACH)
197
  self.coach = subprocess.Popen([str(exe), "run", "--format", "json", "--agent", "minecraft-coach",
198
  "--model", self.opencode_model, prompt], cwd=str(COACH), env=env,
199
- stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True,
200
  start_new_session=True)
201
  try:
202
- output, error = self.coach.communicate(timeout=300)
 
 
203
  if self.coach.returncode:
204
  raise RuntimeError("OpenCode failed: " + (error or output)[-300:])
205
  decision = parse_decision(output)
@@ -219,9 +278,63 @@ class AltoClefStack:
219
  self.coach = None
220
  self._checkpoint()
221
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
222
  def _boot(self) -> None:
223
  try:
224
  ROOT.mkdir(parents=True, exist_ok=True)
 
225
  if not STACK.minecraft_ready.wait(timeout=600) or self.cancel.is_set():
226
  raise RuntimeError("Minecraft server did not become ready")
227
  exe = self._ensure_opencode()
@@ -245,33 +358,61 @@ class AltoClefStack:
245
  threading.Thread(target=self._pump,args=(self.client,"client"),daemon=True).start()
246
  self.last_started_at = time.time()
247
  self._log("starting upstream AltoClef 0.19 player " + USERNAME + " using CPU rendering")
248
- if not _wait_tcp("127.0.0.1",BRIDGE_PORT,180):
249
- raise RuntimeError("AltoClef telemetry bridge did not start")
250
- deadline = time.time() + 180
 
 
 
 
 
 
251
  while not self.cancel.is_set():
252
  data = self._observe()
253
- if data.get("connected") and data.get("creative") and not data.get("error"):
254
  break
255
  if self.client.poll() is not None or time.time() > deadline:
256
  raise RuntimeError("AltoClef could not connect: " + str(data.get("error")))
257
  self.cancel.wait(3)
258
  if self.cancel.is_set():
259
  return
260
- self._supply_creative(data)
 
 
261
  self.cancel.wait(4)
 
 
 
 
 
 
 
 
 
262
  self.state = "running"
263
  self._command("gamer")
 
264
  next_coach = 0.0
265
  while not self.cancel.wait(5):
266
  if self.client.poll() is not None:
267
- raise RuntimeError("AltoClef client exited with " + str(self.client.returncode))
 
268
  data = self._observe()
269
  if goal_completed(data):
270
  self.state = "completed"
271
  self._log("Verified completion: entered End and observed Minecraft credits")
272
  break
273
- if data.get("connected") and not data.get("task_active"):
274
- self._command("gamer")
 
 
 
 
 
 
 
 
 
275
  if time.time() >= next_coach:
276
  self._consult(exe, data)
277
  next_coach = time.time() + 600
@@ -322,7 +463,7 @@ class AltoClefStack:
322
  "client_version":MC_VERSION,"server_version":"1.19","connection":"127.0.0.1:25568 (ViaProxy)",
323
  "opencode_version":self.opencode_version,"model":self.opencode_model,"api_key_required":False,
324
  "model_checks":self.model_checks,"model_errors":self.model_errors,"last_decision":self.last_decision,
325
- "goal_completed":goal_completed(self.observation),"world_mode":"Creative / Peaceful",
326
  "restart_count":self.restart_count,"started_at":self.last_started_at,"checkpoint":str(ROOT),
327
  "next_retry_at":self.next_retry_at,
328
  "cpu_only":True,"rendering":"Mesa llvmpipe (software)","observation":self.observation}
 
15
  import requests
16
 
17
  from minecraft_stack import STACK, PERSIST_ROOT, _download, _wait_tcp
18
+ from opencode_config import (OPENCODE_VERSION, MUSE_MODEL, configuration,
19
  child_environment, parse_decision, goal_completed)
20
  from voyager_processes import stop_runner
21
 
22
  SOURCE = Path(__file__).resolve().parent
23
  ROOT = Path(os.environ.get("ALTOCLEF_HOME", str(PERSIST_ROOT / "altoclef")))
24
+ # Runtime-only client dir: Fabric remap, assets and libraries are slow on the
25
+ # persistent bucket mount, so they live in /tmp while status/log/checkpoint
26
+ # stay in ROOT. Jars are cached in ROOT and copied in (see _ensure_client).
27
+ CLIENT = Path(os.environ.get("ALTOCLEF_CLIENT_HOME", "/tmp/altoclef-client")) / "minecraft-client"
28
+ MOD_CACHE = ROOT / "mod-cache"
29
  COACH = ROOT / "opencode"
30
  MC_VERSION = "1.19.4"
31
  LOADER_VERSION = "0.16.2"
32
+ # Single autonomous account. minecraft_stack, voyager_stack and this module all
33
+ # resolve the same default so no second duplicate AltoClef account can appear.
34
+ USERNAME = os.environ.get("MC_USERNAME", "Naldo_Bot")
35
  BRIDGE_PORT = 3002
36
+ BRIDGE_READY_TIMEOUT = float(os.environ.get("ALTOCLEF_BRIDGE_TIMEOUT", "1800"))
37
+ CONNECT_TIMEOUT = float(os.environ.get("ALTOCLEF_CONNECT_TIMEOUT", "600"))
38
+ GAMER_COOLDOWN = float(os.environ.get("ALTOCLEF_GAMER_COOLDOWN", "60"))
39
+ # Loading grace: the bridge heartbeat (bridge alive) is accepted while the
40
+ # client remaps/loads, but connected telemetry must always be fresh (see _observe).
41
+ LOADING_GRACE = float(os.environ.get("ALTOCLEF_LOADING_GRACE", "900"))
42
+ # /state is reachable before the first 2s scheduler tick publishes a
43
+ # heartbeat (exact initial payload has heartbeat_at 0). Accept that payload
44
+ # only inside this short window measured from first bridge contact.
45
+ FIRST_HEARTBEAT_WINDOW = float(os.environ.get("ALTOCLEF_FIRST_HEARTBEAT_WINDOW", "30"))
46
+ # After play started, a respawn/dimension change shows loading briefly; allow
47
+ # disconnected-with-heartbeat for up to this long before failing the run.
48
+ # Kept short on purpose: a truly frozen Naldo must fail fast, not wait out a
49
+ # 15-minute budget. Initial warmup budgets above stay generous instead.
50
+ RECONNECT_GRACE = float(os.environ.get("ALTOCLEF_RECONNECT_GRACE", "120"))
51
+ # High-level supervision only, via the free OpenCode Muse model. Deterministic
52
+ # AltoClef gameplay continues between (and without) model calls.
53
+ COACH_MODEL = MUSE_MODEL
54
  ALTOCLEF_URL = "https://github.com/MiranCZ/altoclef/releases/download/0.19/altoclef-1.19.4-0.19.jar"
55
  ALTOCLEF_SHA256 = "fe6f6f8b52ed8a8d8a382f1b0e8c85145f038d2c5ec831710eb4f74a6db489b8"
56
  FABRIC_API_URL = "https://maven.fabricmc.net/net/fabricmc/fabric-api/fabric-api/0.87.2+1.19.4/fabric-api-0.87.2+1.19.4.jar"
57
 
58
+ # Assisted survival run: no creative equipment is ever given to this player, no
59
+ # teleport, no portal construction and no dragon-kill command. AltoClef plays
60
+ # the real upstream survival speedrun (BeatMinecraftTask) on the natural map.
61
+ # The existing player inventory is retained untouched (never cleared, given or
62
+ # archived away); completion is therefore quicker than a fresh speedrun and is
63
+ # reported honestly as assisted.
 
 
 
 
 
 
 
64
 
65
 
66
  class AltoClefStack:
 
79
  self.model_errors = 0
80
  self.last_decision: dict[str, Any] = {}
81
  self.opencode_version = ""
82
+ self.opencode_model = os.environ.get("ALTOCLEF_OPENCODE_MODEL", COACH_MODEL)
83
  self.last_started_at: float | None = None
84
  self.next_retry_at = 0.0
85
+ self._last_gamer_at = 0.0
86
+ self._last_mode_set = 0.0
87
+ self._bridge_seen_at: float | None = None
88
+ self._last_connected_at: float | None = None
89
  saved = ROOT / "status.json"
90
  if saved.exists():
91
  try:
 
129
  self.opencode_version = report.stdout.strip()
130
  if self.opencode_version != OPENCODE_VERSION:
131
  raise RuntimeError("Installed OpenCode version differs from reviewed version")
132
+ (COACH / "opencode.json").write_text(json.dumps(configuration(), indent=2))
133
  return shim
134
 
135
  def _ensure_client(self, java: Path) -> list[str]:
 
137
  CLIENT.mkdir(parents=True, exist_ok=True)
138
  version = f"fabric-loader-{LOADER_VERSION}-{MC_VERSION}"
139
  if not (CLIENT / "versions" / version / (version + ".json")).exists():
140
+ self._log("installing official Minecraft client " + MC_VERSION + " and Fabric " + LOADER_VERSION
141
+ + " into runtime-only " + str(CLIENT))
142
  launcher.fabric.install_fabric(MC_VERSION, str(CLIENT), loader_version=LOADER_VERSION, java=str(java),
143
+ callback={"setStatus": lambda text: self._log("installer: " + text)})
144
  mods = CLIENT / "mods"
145
  mods.mkdir(exist_ok=True)
146
+ # Jars are verified once into the persistent cache, then copied into
147
+ # the runtime-only client so a /tmp wipe costs a copy, not a download.
148
+ MOD_CACHE.mkdir(parents=True, exist_ok=True)
149
+ _download(ALTOCLEF_URL, MOD_CACHE / "altoclef-1.19.4-0.19.jar", ALTOCLEF_SHA256)
150
+ _download(FABRIC_API_URL, MOD_CACHE / "fabric-api-0.87.2+1.19.4.jar")
151
+ shutil.copyfile(MOD_CACHE / "altoclef-1.19.4-0.19.jar", mods / "altoclef-1.19.4-0.19.jar")
152
+ shutil.copyfile(MOD_CACHE / "fabric-api-0.87.2+1.19.4.jar", mods / "fabric-api-0.87.2+1.19.4.jar")
153
  shutil.copyfile(SOURCE / "altoclef/space-altoclef-bridge.jar", mods / "space-altoclef-bridge.jar")
154
  settings = CLIENT / "options.txt"
155
  if not settings.exists():
 
170
  "customResolution":True, "resolutionWidth":"640", "resolutionHeight":"360",
171
  })
172
 
173
+ def _loading_grace(self) -> bool:
174
+ return self.last_started_at is not None and time.time() - self.last_started_at < LOADING_GRACE
175
+
176
+ @staticmethod
177
+ def _survival_verified(data: dict[str, Any]) -> bool:
178
+ # Connected, clean, and creative EXPLICITLY false. A loading payload
179
+ # without a creative flag never counts as Survival.
180
+ return bool(data.get("connected")) and not data.get("error") and data.get("creative") is False
181
+
182
  def _observe(self) -> dict[str, Any]:
183
  response = requests.get(f"http://127.0.0.1:{BRIDGE_PORT}/state", timeout=5)
184
  response.raise_for_status()
185
  data = response.json()
186
  if not isinstance(data, dict):
187
  raise RuntimeError("Invalid AltoClef telemetry")
188
+ now = time.time()
189
+ if self._bridge_seen_at is None:
190
+ self._bridge_seen_at = now
191
+ if data.get("connected"):
192
+ # Connected world observations must always be fresh; a stale
193
+ # connected payload is never accepted as alive.
194
+ if now - float(data.get("observed_at") or 0) > 30:
195
+ raise RuntimeError("AltoClef client telemetry stopped updating: "
196
+ + str(data.get("error") or "no fresh snapshot from client thread"))
197
+ self._last_connected_at = now
198
+ else:
199
+ heartbeat = float(data.get("heartbeat_at") or 0)
200
+ if heartbeat <= 0:
201
+ # Exact initial payload before the first scheduler tick:
202
+ # accept only inside the short first-heartbeat window.
203
+ if now - self._bridge_seen_at > FIRST_HEARTBEAT_WINDOW:
204
+ raise RuntimeError("AltoClef bridge never published a heartbeat")
205
+ elif now - heartbeat > 60:
206
+ raise RuntimeError("AltoClef bridge heartbeat stopped updating")
207
+ if self._last_connected_at is None:
208
+ # Startup: loading grace is anchored at bridge readiness (see
209
+ # _boot), so a slow remap never consumes the connect budget.
210
+ if not self._loading_grace():
211
+ raise RuntimeError("AltoClef client still not connected after loading grace: "
212
+ + str(data.get("dispatch_error") or data.get("error") or "no diagnosis"))
213
+ elif now - self._last_connected_at > RECONNECT_GRACE:
214
+ raise RuntimeError("AltoClef client did not reconnect after "
215
+ + str(int(RECONNECT_GRACE)) + "s: "
216
+ + str(data.get("dispatch_error") or data.get("error") or "no diagnosis"))
217
  self.observation = data
218
  self._checkpoint()
219
  return data
 
231
  response.raise_for_status()
232
  self._log("AltoClef command: @" + command)
233
 
234
+ def _ensure_survival_mode(self) -> None:
235
+ """Bootstrap/respawn mode assignment: Naldo plays Survival, nothing given.
236
+
237
+ Only a console gamemode assignment; the existing inventory is retained
238
+ untouched and no item, teleport or effect is ever granted.
239
+ """
 
 
 
 
 
240
  server = STACK.processes.get("minecraft")
241
  if server is None or server.poll() is not None or server.stdin is None:
242
+ raise RuntimeError("Minecraft console unavailable for gamemode assignment")
243
+ with STACK.lock:
244
+ server.stdin.write(f"gamemode survival {USERNAME}\n")
245
+ server.stdin.flush()
246
+ self._last_mode_set = time.time()
247
+ self._log(f"mode assignment: gamemode survival {USERNAME} (existing inventory retained)")
 
248
 
249
  def _consult(self, exe: Path, data: dict[str, Any]) -> None:
250
  compact = {key:data.get(key) for key in ["connected","dimension","position","creative","task_active","tasks",
 
253
  env = child_environment(COACH)
254
  self.coach = subprocess.Popen([str(exe), "run", "--format", "json", "--agent", "minecraft-coach",
255
  "--model", self.opencode_model, prompt], cwd=str(COACH), env=env,
256
+ stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True,
257
  start_new_session=True)
258
  try:
259
+ # Empty stdin provides EOF: a non-TTY child that waits on stdin
260
+ # would otherwise park here until the timeout.
261
+ output, error = self.coach.communicate(input="", timeout=300)
262
  if self.coach.returncode:
263
  raise RuntimeError("OpenCode failed: " + (error or output)[-300:])
264
  decision = parse_decision(output)
 
278
  self.coach = None
279
  self._checkpoint()
280
 
281
+ def _client_tree_size(self) -> int:
282
+ total = 0
283
+ try:
284
+ for path in CLIENT.rglob("*"):
285
+ try:
286
+ if path.is_file():
287
+ total += path.stat().st_size
288
+ except OSError:
289
+ pass
290
+ except OSError:
291
+ pass
292
+ return total
293
+
294
+ def _wait_bridge_ready(self) -> None:
295
+ """Bounded warmup that never kills a healthy growing process.
296
+
297
+ The first Fabric remap plus asset download can take tens of minutes on
298
+ a slow mount. While the client process is alive we wait up to
299
+ BRIDGE_READY_TIMEOUT, logging live progress (runtime dir growth). A
300
+ client exit fails fast with the log tail instead of a bare timeout.
301
+ """
302
+ deadline = time.time() + BRIDGE_READY_TIMEOUT
303
+ last_size = -1
304
+ last_note = 0.0
305
+ while time.time() < deadline:
306
+ if self.cancel.is_set():
307
+ return
308
+ code = self.client.poll() if self.client else None
309
+ if code is not None:
310
+ raise RuntimeError("AltoClef client exited during startup rc=" + str(code)
311
+ + "; log tail:\n" + self.tail(30))
312
+ if _wait_tcp("127.0.0.1", BRIDGE_PORT, 5):
313
+ return
314
+ size = self._client_tree_size()
315
+ if size != last_size and time.time() - last_note > 120:
316
+ last_size = size
317
+ last_note = time.time()
318
+ self._log(f"client warmup in progress: runtime dir {size // 1024 // 1024} MiB, "
319
+ f"bridge not up yet (budget {int(deadline - time.time())}s left)")
320
+ self.cancel.wait(5)
321
+ raise RuntimeError(f"AltoClef telemetry bridge did not start within {int(BRIDGE_READY_TIMEOUT)}s; "
322
+ "client still alive, log tail:\n" + self.tail(30))
323
+
324
+ def _reset_launch_clocks(self) -> None:
325
+ # Per-launch reset: a second boot after a crash must not reuse the
326
+ # previous launch's clocks, or the new initial loading payload is
327
+ # rejected against expired grace/heartbeat timestamps.
328
+ self._bridge_seen_at = None
329
+ self._last_connected_at = None
330
+ self.last_started_at = None
331
+ self._last_gamer_at = 0.0
332
+ self._last_mode_set = 0.0
333
+
334
  def _boot(self) -> None:
335
  try:
336
  ROOT.mkdir(parents=True, exist_ok=True)
337
+ self._reset_launch_clocks()
338
  if not STACK.minecraft_ready.wait(timeout=600) or self.cancel.is_set():
339
  raise RuntimeError("Minecraft server did not become ready")
340
  exe = self._ensure_opencode()
 
358
  threading.Thread(target=self._pump,args=(self.client,"client"),daemon=True).start()
359
  self.last_started_at = time.time()
360
  self._log("starting upstream AltoClef 0.19 player " + USERNAME + " using CPU rendering")
361
+ self._wait_bridge_ready()
362
+ if self.cancel.is_set():
363
+ return
364
+ # Re-anchor startup clocks at bridge readiness: the warmup budget
365
+ # above must not consume the loading/connect budgets below.
366
+ self.last_started_at = time.time()
367
+ self._log("bridge ready; loading grace and connect budget start now")
368
+ deadline = time.time() + CONNECT_TIMEOUT
369
+ data: dict[str, Any] = {}
370
  while not self.cancel.is_set():
371
  data = self._observe()
372
+ if data.get("connected") and not data.get("error"):
373
  break
374
  if self.client.poll() is not None or time.time() > deadline:
375
  raise RuntimeError("AltoClef could not connect: " + str(data.get("error")))
376
  self.cancel.wait(3)
377
  if self.cancel.is_set():
378
  return
379
+ # Coherent mode assignment BEFORE gamer: Naldo must be Survival
380
+ # (upstream speedrun needs hostile mobs/loot); humans keep theirs.
381
+ self._ensure_survival_mode()
382
  self.cancel.wait(4)
383
+ data = self._observe()
384
+ # Strict verification: connected, no error, and creative EXPLICITLY
385
+ # false. A loading payload without a creative flag is not Survival.
386
+ if not self._survival_verified(data):
387
+ raise RuntimeError("mode verification failed: connected=" + str(data.get("connected"))
388
+ + " error=" + str(data.get("error"))
389
+ + " creative=" + str(data.get("creative"))
390
+ + "; gamer not started")
391
+ self._log("mode verified: " + USERNAME + " is Survival; existing inventory retained")
392
  self.state = "running"
393
  self._command("gamer")
394
+ self._last_gamer_at = time.time()
395
  next_coach = 0.0
396
  while not self.cancel.wait(5):
397
  if self.client.poll() is not None:
398
+ raise RuntimeError("AltoClef client exited with " + str(self.client.returncode)
399
+ + "; log tail:\n" + self.tail(30))
400
  data = self._observe()
401
  if goal_completed(data):
402
  self.state = "completed"
403
  self._log("Verified completion: entered End and observed Minecraft credits")
404
  break
405
+ now = time.time()
406
+ if data.get("creative"):
407
+ # Respawn/mode drift: re-assign Survival instead of gaming Creative.
408
+ if now - self._last_mode_set > 300:
409
+ self._ensure_survival_mode()
410
+ elif data.get("connected") and not data.get("task_active") and not goal_completed(data):
411
+ # Cooldown: re-issuing gamer while the task boots would
412
+ # restart it every poll instead of letting it run.
413
+ if now - self._last_gamer_at >= GAMER_COOLDOWN:
414
+ self._command("gamer")
415
+ self._last_gamer_at = now
416
  if time.time() >= next_coach:
417
  self._consult(exe, data)
418
  next_coach = time.time() + 600
 
463
  "client_version":MC_VERSION,"server_version":"1.19","connection":"127.0.0.1:25568 (ViaProxy)",
464
  "opencode_version":self.opencode_version,"model":self.opencode_model,"api_key_required":False,
465
  "model_checks":self.model_checks,"model_errors":self.model_errors,"last_decision":self.last_decision,
466
+ "goal_completed":goal_completed(self.observation),"world_mode":"Survival / Normal (assisted: existing inventory retained)",
467
  "restart_count":self.restart_count,"started_at":self.last_started_at,"checkpoint":str(ROOT),
468
  "next_retry_at":self.next_retry_at,
469
  "cpu_only":True,"rendering":"Mesa llvmpipe (software)","observation":self.observation}
app.py CHANGED
@@ -748,7 +748,12 @@ def _service_supervisor() -> None:
748
  if _supervisor_stop.wait(backoff):
749
  break
750
  STACK.start_async()
751
- VOYAGER.start_async()
 
 
 
 
 
752
  if os.environ.get("GEMINI_BOT_AUTOSTART", "1") == "1":
753
  GEMINI_BOT.start_async()
754
  if os.environ.get("ALTOCLEF_AUTOSTART", "1") == "1":
@@ -757,7 +762,8 @@ def _service_supervisor() -> None:
757
  continue
758
 
759
  vs = VOYAGER.status()
760
- if mc.get("state") == "running" and vs.get("state") in {"error", "exited", "stopped"} and not vs.get("running"):
 
761
  with _supervisor_lock:
762
  _supervisor_recoveries += 1
763
  _supervisor_last_action = f"voyager recovery #{_supervisor_recoveries}: state={vs.get('state')}"
@@ -809,7 +815,7 @@ def _startup() -> None:
809
  threading.Thread(target=_load_aux_model, daemon=True, name="cpu-aux-model-preload").start()
810
  if os.environ.get("MINECRAFT_AUTOSTART", "1") == "1":
811
  STACK.start_async()
812
- if os.environ.get("VOYAGER_AUTOSTART", "1") == "1":
813
  VOYAGER.start_async()
814
  if os.environ.get("GEMINI_BOT_AUTOSTART", "1") == "1":
815
  GEMINI_BOT.start_async()
@@ -1161,19 +1167,19 @@ with gr.Blocks(title="Programa Voyager LLM Endpoint") as demo:
1161
  gr.Button("Status Minecraft").click(STACK.status, outputs=mc_output)
1162
  gr.Button("Iniciar Minecraft", variant="primary").click(STACK.start_async, outputs=mc_output)
1163
  gr.Button("Parar Minecraft").click(STACK.stop, outputs=mc_output)
1164
- gr.Markdown("## Voyager autonomo")
1165
  voyager_output = gr.JSON(label="Voyager")
1166
  with gr.Row():
1167
  gr.Button("Status Voyager").click(VOYAGER.status, outputs=voyager_output)
1168
- gr.Button("Iniciar Voyager", variant="primary").click(VOYAGER.start_async, outputs=voyager_output)
1169
  gr.Button("Parar Voyager").click(VOYAGER.stop, outputs=voyager_output)
1170
 
1171
- gr.Markdown("## OpenCode_Bot — AltoClef / Baritone\nTerceiro jogador, focado em concluir o jogo. Creative / Peaceful.")
1172
- altoclef_output = gr.JSON(label="AltoClef / OpenCode")
1173
  with gr.Row():
1174
- gr.Button("Status terceiro bot").click(ALTOCLEF.status, outputs=altoclef_output)
1175
- gr.Button("Iniciar terceiro bot", variant="primary").click(ALTOCLEF.start_async, outputs=altoclef_output)
1176
- gr.Button("Parar terceiro bot").click(ALTOCLEF.stop, outputs=altoclef_output)
1177
 
1178
  if __name__ == "__main__":
1179
  print(
 
748
  if _supervisor_stop.wait(backoff):
749
  break
750
  STACK.start_async()
751
+ # Voyager stays available on demand but never auto-starts:
752
+ # VOYAGER_AUTOSTART defaults to 0 (AltoClef is the default
753
+ # controller). The recovery path must respect the same
754
+ # flag, otherwise a restart silently re-enables it.
755
+ if os.environ.get("VOYAGER_AUTOSTART", "0") == "1":
756
+ VOYAGER.start_async()
757
  if os.environ.get("GEMINI_BOT_AUTOSTART", "1") == "1":
758
  GEMINI_BOT.start_async()
759
  if os.environ.get("ALTOCLEF_AUTOSTART", "1") == "1":
 
762
  continue
763
 
764
  vs = VOYAGER.status()
765
+ if (os.environ.get("VOYAGER_AUTOSTART", "0") == "1"
766
+ and mc.get("state") == "running" and vs.get("state") in {"error", "exited", "stopped"} and not vs.get("running")):
767
  with _supervisor_lock:
768
  _supervisor_recoveries += 1
769
  _supervisor_last_action = f"voyager recovery #{_supervisor_recoveries}: state={vs.get('state')}"
 
815
  threading.Thread(target=_load_aux_model, daemon=True, name="cpu-aux-model-preload").start()
816
  if os.environ.get("MINECRAFT_AUTOSTART", "1") == "1":
817
  STACK.start_async()
818
+ if os.environ.get("VOYAGER_AUTOSTART", "0") == "1":
819
  VOYAGER.start_async()
820
  if os.environ.get("GEMINI_BOT_AUTOSTART", "1") == "1":
821
  GEMINI_BOT.start_async()
 
1167
  gr.Button("Status Minecraft").click(STACK.status, outputs=mc_output)
1168
  gr.Button("Iniciar Minecraft", variant="primary").click(STACK.start_async, outputs=mc_output)
1169
  gr.Button("Parar Minecraft").click(STACK.stop, outputs=mc_output)
1170
+ gr.Markdown("## Voyager (alternativa manual)\nO Voyager continua disponível se você quiser ligar manualmente; o Naldo usa o AltoClef.")
1171
  voyager_output = gr.JSON(label="Voyager")
1172
  with gr.Row():
1173
  gr.Button("Status Voyager").click(VOYAGER.status, outputs=voyager_output)
1174
+ gr.Button("Iniciar Voyager").click(VOYAGER.start_async, outputs=voyager_output)
1175
  gr.Button("Parar Voyager").click(VOYAGER.stop, outputs=voyager_output)
1176
 
1177
+ gr.Markdown("## Naldo — jogador autônomo\nO Naldo joga survival sozinho para zerar o jogo (mapa e inventário atual mantidos).")
1178
+ altoclef_output = gr.JSON(label="Naldo")
1179
  with gr.Row():
1180
+ gr.Button("Status Naldo").click(ALTOCLEF.status, outputs=altoclef_output)
1181
+ gr.Button("Iniciar Naldo", variant="primary").click(ALTOCLEF.start_async, outputs=altoclef_output)
1182
+ gr.Button("Parar Naldo").click(ALTOCLEF.stop, outputs=altoclef_output)
1183
 
1184
  if __name__ == "__main__":
1185
  print(
minecraft_stack.py CHANGED
@@ -104,9 +104,14 @@ def _server_properties() -> dict[str, str]:
104
  "enable-command-block": "true",
105
  "spawn-protection": "0",
106
  "allow-flight": "true",
 
 
 
 
 
107
  "gamemode": "creative",
108
- "force-gamemode": "true",
109
- "difficulty": "peaceful",
110
  "max-players": str(MAX_PLAYERS),
111
  "op-permission-level": "4",
112
  "view-distance": "8",
@@ -693,10 +698,14 @@ class MinecraftStack:
693
  if proc.stdin:
694
  for cmd in (
695
  f"op {BOT_USERNAME}",
696
- f"gamemode creative {BOT_USERNAME}",
 
 
 
 
697
  "gamerule keepInventory true",
698
- "gamerule doDaylightCycle false",
699
- "difficulty peaceful",
700
  ):
701
  proc.stdin.write(cmd + "\n")
702
  proc.stdin.flush()
 
104
  "enable-command-block": "true",
105
  "spawn-protection": "0",
106
  "allow-flight": "true",
107
+ # Default gamemode is Creative so human Bedrock players keep a
108
+ # building-friendly mode, but force-gamemode is false so Naldo_Bot
109
+ # keeps its assigned Survival mode (set at bootstrap/respawn by the
110
+ # AltoClef supervisor). Difficulty Normal: blazes/endermen must exist
111
+ # for the survival speedrun (eyes, rods, pearls).
112
  "gamemode": "creative",
113
+ "force-gamemode": "false",
114
+ "difficulty": "normal",
115
  "max-players": str(MAX_PLAYERS),
116
  "op-permission-level": "4",
117
  "view-distance": "8",
 
698
  if proc.stdin:
699
  for cmd in (
700
  f"op {BOT_USERNAME}",
701
+ # Naldo plays Survival on Normal; humans keep their own mode
702
+ # because force-gamemode is false. Daylight cycle stays on:
703
+ # endermen (pearls) only spawn at night. keepInventory stays as
704
+ # configured (existing setting, retained on request).
705
+ f"gamemode survival {BOT_USERNAME}",
706
  "gamerule keepInventory true",
707
+ "gamerule doDaylightCycle true",
708
+ "difficulty normal",
709
  ):
710
  proc.stdin.write(cmd + "\n")
711
  proc.stdin.flush()
opencode_config.py CHANGED
@@ -10,37 +10,37 @@ OPENCODE_VERSION = "1.18.34"
10
  MINE_BASE = "https://erinaldordso-mine.hf.space/v1"
11
  MAIN_MODEL = "qwen3-coder-30b-a3b-instruct"
12
  AUX_MODEL = "granite-4.0-h-tiny"
13
- COACH_PROMPT = """You supervise the original AltoClef Minecraft completion bot.
14
- AltoClef performs real movement, stronghold search, portal activation and dragon
15
- combat. Observe the supplied telemetry. Reply ONLY with one compact JSON object:
 
 
 
 
 
 
16
  {"action":"continue","reason":"brief factual explanation"}.
17
  Allowed actions: start, continue, resume. Start/resume runs AltoClef @gamer only
18
  when its task is inactive. Prefer continue while a task is active. Never invent
19
- world observations, success or a survival speedrun. This world is Creative and
20
- Peaceful. No shell commands or source edits are necessary. Credits observed
21
- after entering the End are required to claim completion. Keep reason under 25 words.
 
22
  """
23
 
24
 
25
- def configuration(base: str = MINE_BASE) -> dict[str, Any]:
 
 
 
 
26
  return {
27
  "$schema": "https://opencode.ai/config.json",
28
- "enabled_providers": ["mine", "opencode"],
29
- "model": f"mine/{MAIN_MODEL}",
30
- "small_model": f"mine/{AUX_MODEL}",
31
  "share": "disabled",
32
  "autoupdate": False,
33
- "provider": {
34
- "mine": {
35
- "npm": "@ai-sdk/openai-compatible",
36
- "name": "Mine CPU (sem API key)",
37
- "options": {"baseURL": base, "headers": {"X-Voyager-Role": "action"}},
38
- "models": {
39
- MAIN_MODEL: {"name": "Qwen3 Coder CPU", "limit": {"context": 16384, "output": 256}},
40
- AUX_MODEL: {"name": "Granite CPU", "limit": {"context": 8192, "output": 256}},
41
- },
42
- }
43
- },
44
  "default_agent": "minecraft-coach",
45
  "agent": {
46
  "minecraft-coach": {
 
10
  MINE_BASE = "https://erinaldordso-mine.hf.space/v1"
11
  MAIN_MODEL = "qwen3-coder-30b-a3b-instruct"
12
  AUX_MODEL = "granite-4.0-h-tiny"
13
+ # Coach-only model: high-level supervision runs SOLELY on the free OpenCode
14
+ # Muse model. No Mine provider is configured here; other bots/Spaces that use
15
+ # the Mine Space keep their own wiring and are unaffected.
16
+ MUSE_MODEL_ID = "muse-spark-1.3-contributor-free"
17
+ MUSE_MODEL = "opencode/" + MUSE_MODEL_ID
18
+ COACH_PROMPT = """You supervise the upstream AltoClef Minecraft survival speedrun bot.
19
+ AltoClef performs real movement, gear progression, stronghold search, portal
20
+ activation and dragon combat on difficulty Normal. Observe the supplied
21
+ telemetry. Reply ONLY with one compact JSON object:
22
  {"action":"continue","reason":"brief factual explanation"}.
23
  Allowed actions: start, continue, resume. Start/resume runs AltoClef @gamer only
24
  when its task is inactive. Prefer continue while a task is active. Never invent
25
+ world observations or success. Naldo plays Survival with a retained pre-existing
26
+ inventory (assisted run): no shell commands or source edits are necessary.
27
+ Credits observed after entering the End are required to claim completion.
28
+ Keep reason under 25 words.
29
  """
30
 
31
 
32
+ def configuration() -> dict[str, Any]:
33
+ # Muse ONLY: the default and small models are the free OpenCode Muse
34
+ # model. There is intentionally no Mine provider here, so title/small
35
+ # tasks cannot fall back to Mine/Qwen. The built-in "opencode" provider
36
+ # needs no key for free models in a clean HOME (see child_environment).
37
  return {
38
  "$schema": "https://opencode.ai/config.json",
39
+ "enabled_providers": ["opencode"],
40
+ "model": MUSE_MODEL,
41
+ "small_model": MUSE_MODEL,
42
  "share": "disabled",
43
  "autoupdate": False,
 
 
 
 
 
 
 
 
 
 
 
44
  "default_agent": "minecraft-coach",
45
  "agent": {
46
  "minecraft-coach": {
tests/test_altoclef_stack.py CHANGED
@@ -13,19 +13,101 @@ import altoclef_stack as module
13
  @pytest.fixture
14
  def runner(monkeypatch, tmp_path):
15
  monkeypatch.setattr(module, "ROOT", tmp_path)
 
 
16
  return module.AltoClefStack()
17
 
18
  def response(data):
19
  return SimpleNamespace(raise_for_status=lambda: None, json=lambda: data)
20
 
21
- def test_stale_telemetry_is_an_error(runner, monkeypatch):
22
  monkeypatch.setattr(module.requests, "get", lambda *a, **k:
23
- response({"connected": True, "observed_at": time.time() - 60}))
 
24
  with pytest.raises(RuntimeError, match="stopped updating"):
25
  runner._observe()
26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
  def test_credits_evidence_survives_restart(runner, monkeypatch):
28
- state = {"entered_end": True, "credits_observed": True, "observed_at": time.time()}
 
29
  monkeypatch.setattr(module.requests, "get", lambda *a, **k: response(state))
30
  runner._observe()
31
  restored = module.AltoClefStack()
@@ -55,18 +137,50 @@ def test_boot_failures_respect_backoff(runner, monkeypatch):
55
  assert runner.start_async()["state"] == "error"
56
  assert runner.restart_count == 0
57
 
58
- def test_equipment_only_targets_this_creative_player(runner, monkeypatch):
 
 
 
 
 
 
 
 
59
  console = io.StringIO()
60
  server = SimpleNamespace(stdin=console, poll=lambda: None)
61
  monkeypatch.setattr(module.STACK, "processes", {"minecraft": server})
62
- monkeypatch.setattr(module, "CREATIVE_LOADOUT", {"ender_eye": 64, "bow": 1})
63
- runner._supply_creative({"creative": True, "inventory": [
64
- {"item": "minecraft:ender_eye", "count": 15}, {"item": "bow", "count": 1}]})
65
- assert console.getvalue() == "give OpenCode_Bot minecraft:ender_eye 49\n"
66
-
67
- def test_survival_inventory_is_never_supplied(runner, monkeypatch):
68
- monkeypatch.setattr(module.STACK, "processes", {})
69
- runner._supply_creative({"creative": False, "inventory": []})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70
 
71
  def test_provider_failure_does_not_stop_gameplay(runner, monkeypatch):
72
  process = SimpleNamespace(returncode=1, communicate=lambda **k: ("", "provider unavailable"))
 
13
  @pytest.fixture
14
  def runner(monkeypatch, tmp_path):
15
  monkeypatch.setattr(module, "ROOT", tmp_path)
16
+ monkeypatch.delenv("ALTOCLEF_OPENCODE_MODEL", raising=False)
17
+ monkeypatch.delenv("MC_USERNAME", raising=False)
18
  return module.AltoClefStack()
19
 
20
  def response(data):
21
  return SimpleNamespace(raise_for_status=lambda: None, json=lambda: data)
22
 
23
+ def test_stale_connected_telemetry_is_an_error(runner, monkeypatch):
24
  monkeypatch.setattr(module.requests, "get", lambda *a, **k:
25
+ response({"connected": True, "observed_at": time.time() - 60,
26
+ "heartbeat_at": time.time()}))
27
  with pytest.raises(RuntimeError, match="stopped updating"):
28
  runner._observe()
29
 
30
+ def test_loading_heartbeat_accepted_inside_grace(runner, monkeypatch):
31
+ now = time.time()
32
+ runner.last_started_at = now
33
+ monkeypatch.setattr(module.requests, "get", lambda *a, **k:
34
+ response({"connected": False, "loading": True, "heartbeat_at": now}))
35
+ assert runner._observe()["loading"] is True
36
+
37
+ def test_loading_without_heartbeat_is_an_error(runner, monkeypatch):
38
+ runner.last_started_at = time.time()
39
+ monkeypatch.setattr(module.requests, "get", lambda *a, **k:
40
+ response({"connected": False, "loading": True, "heartbeat_at": time.time() - 120}))
41
+ with pytest.raises(RuntimeError, match="heartbeat stopped"):
42
+ runner._observe()
43
+
44
+ def test_exact_initial_payload_accepted_only_in_first_window(runner, monkeypatch):
45
+ # Java's initial /state before the first 2s scheduler tick.
46
+ runner.last_started_at = time.time()
47
+ monkeypatch.setattr(module.requests, "get", lambda *a, **k:
48
+ response({"connected": False, "loading": True, "heartbeat_at": 0}))
49
+ assert runner._observe()["loading"] is True
50
+ runner._bridge_seen_at = time.time() - module.FIRST_HEARTBEAT_WINDOW - 1
51
+ with pytest.raises(RuntimeError, match="never published a heartbeat"):
52
+ runner._observe()
53
+
54
+ def test_reconnect_allowed_bounded_after_play(runner, monkeypatch):
55
+ now = time.time()
56
+ runner.last_started_at = now - module.LOADING_GRACE - 10
57
+ runner._last_connected_at = now - 60
58
+ monkeypatch.setattr(module.requests, "get", lambda *a, **k:
59
+ response({"connected": False, "loading": True, "heartbeat_at": now}))
60
+ assert runner._observe()["loading"] is True
61
+ runner._last_connected_at = now - module.RECONNECT_GRACE - 1
62
+ with pytest.raises(RuntimeError, match="did not reconnect"):
63
+ runner._observe()
64
+
65
+ def test_second_boot_resets_launch_clocks(runner, monkeypatch):
66
+ # Regression: after a crash, the previous launch leaves an old connected
67
+ # timestamp, a stale first-heartbeat clock and an expired grace anchor.
68
+ # The new boot must accept its fresh initial loading payload.
69
+ now = time.time()
70
+ runner._last_connected_at = now - module.RECONNECT_GRACE - 60
71
+ runner._bridge_seen_at = now - module.FIRST_HEARTBEAT_WINDOW - 60
72
+ runner.last_started_at = now - module.LOADING_GRACE - 60
73
+ runner._last_gamer_at = now
74
+ runner._last_mode_set = now
75
+ runner._reset_launch_clocks()
76
+ assert runner._bridge_seen_at is None
77
+ assert runner._last_connected_at is None
78
+ assert runner.last_started_at is None
79
+ assert runner._last_gamer_at == 0.0 and runner._last_mode_set == 0.0
80
+ runner.last_started_at = time.time()
81
+ monkeypatch.setattr(module.requests, "get", lambda *a, **k:
82
+ response({"connected": False, "loading": True, "heartbeat_at": 0}))
83
+ assert runner._observe()["loading"] is True
84
+
85
+ def test_boot_resets_launch_clocks_before_startup():
86
+ import inspect
87
+ source = inspect.getsource(module.AltoClefStack._boot)
88
+ assert "_reset_launch_clocks()" in source
89
+ assert source.index("_reset_launch_clocks()") < source.index("minecraft_ready.wait")
90
+
91
+ def test_survival_verified_requires_explicit_survival():
92
+ good = {"connected": True, "error": "", "creative": False}
93
+ assert module.AltoClefStack._survival_verified(good) is True
94
+ # Loading payload without a creative flag is NOT Survival.
95
+ assert module.AltoClefStack._survival_verified({"connected": False, "loading": True}) is False
96
+ assert module.AltoClefStack._survival_verified({"connected": True, "error": "", "creative": True}) is False
97
+ assert module.AltoClefStack._survival_verified({"connected": True, "error": "boom", "creative": False}) is False
98
+
99
+ def test_loading_past_grace_is_an_error(runner, monkeypatch):
100
+ now = time.time()
101
+ runner.last_started_at = now - module.LOADING_GRACE - 10
102
+ monkeypatch.setattr(module.requests, "get", lambda *a, **k:
103
+ response({"connected": False, "loading": True, "heartbeat_at": now,
104
+ "dispatch_error": "client thread stalled"}))
105
+ with pytest.raises(RuntimeError, match="still not connected"):
106
+ runner._observe()
107
+
108
  def test_credits_evidence_survives_restart(runner, monkeypatch):
109
+ state = {"connected": True, "entered_end": True, "credits_observed": True,
110
+ "observed_at": time.time(), "heartbeat_at": time.time()}
111
  monkeypatch.setattr(module.requests, "get", lambda *a, **k: response(state))
112
  runner._observe()
113
  restored = module.AltoClefStack()
 
137
  assert runner.start_async()["state"] == "error"
138
  assert runner.restart_count == 0
139
 
140
+ def test_single_username_is_naldo_bot():
141
+ assert module.USERNAME == "Naldo_Bot"
142
+
143
+ def test_default_coach_model_is_muse_spark_only(runner):
144
+ import opencode_config
145
+ assert runner.opencode_model == "opencode/muse-spark-1.3-contributor-free"
146
+ assert module.COACH_MODEL == runner.opencode_model == opencode_config.MUSE_MODEL
147
+
148
+ def test_mode_assignment_only_sets_survival_for_this_player(runner, monkeypatch):
149
  console = io.StringIO()
150
  server = SimpleNamespace(stdin=console, poll=lambda: None)
151
  monkeypatch.setattr(module.STACK, "processes", {"minecraft": server})
152
+ runner._ensure_survival_mode()
153
+ written = console.getvalue()
154
+ assert written == f"gamemode survival {module.USERNAME}\n"
155
+ assert "give " not in written and "clear" not in written
156
+
157
+ def test_existing_inventory_is_never_touched():
158
+ # Assisted run: no give/clear/supply helper may exist on the supervisor.
159
+ assert not hasattr(module.AltoClefStack, "_supply_creative")
160
+ source = Path(module.__file__).read_text(encoding="utf-8")
161
+ assert "minecraft:{name}" not in source
162
+ assert "CREATIVE_LOADOUT" not in source
163
+
164
+ def test_mode_is_verified_survival_in_status(runner):
165
+ assert "Survival" in runner.status()["world_mode"]
166
+ assert "Normal" in runner.status()["world_mode"]
167
+
168
+ def test_consult_provides_stdin_eof(runner, monkeypatch):
169
+ seen = {}
170
+ def fake_popen(*a, **k):
171
+ seen.update(k)
172
+ return SimpleNamespace(returncode=1,
173
+ communicate=lambda input=None, timeout=None: ("", "provider unavailable"))
174
+ monkeypatch.setattr(module.subprocess, "Popen", fake_popen)
175
+ monkeypatch.setattr(module, "stop_runner", lambda p, **k: None)
176
+ client = object()
177
+ runner.client = client
178
+ runner._consult(Path("opencode"), {"connected": True, "task_active": True})
179
+ assert runner.client is client
180
+ assert runner.model_errors == 1
181
+ assert runner.model_checks == 0
182
+ import subprocess as stdlib_subprocess
183
+ assert seen.get("stdin") == stdlib_subprocess.PIPE
184
 
185
  def test_provider_failure_does_not_stop_gameplay(runner, monkeypatch):
186
  process = SimpleNamespace(returncode=1, communicate=lambda **k: ("", "provider unavailable"))
tests/test_opencode_config.py CHANGED
@@ -11,15 +11,20 @@ module = importlib.util.module_from_spec(spec)
11
  spec.loader.exec_module(module)
12
 
13
 
14
- def test_preserves_real_model_contexts_without_authentication():
 
 
 
15
  config = module.configuration()
16
- options = config["provider"]["mine"]["options"]
17
- assert options["baseURL"] == "https://erinaldordso-mine.hf.space/v1"
18
- assert "apiKey" not in options
19
- assert "Authorization" not in options["headers"]
20
- models = config["provider"]["mine"]["models"]
21
- assert models[module.MAIN_MODEL]["limit"]["context"] == 16384
22
- assert models[module.AUX_MODEL]["limit"]["context"] == 8192
 
 
23
 
24
 
25
  def test_credentials_are_not_inherited(monkeypatch, tmp_path):
 
11
  spec.loader.exec_module(module)
12
 
13
 
14
+ def test_coach_uses_muse_only_without_authentication():
15
+ # The AltoClef coach runs SOLELY on the free OpenCode Muse model: default
16
+ # and small models are Muse, and no Mine/Qwen provider exists here, so no
17
+ # title/small task can fall back to Mine. No key material anywhere.
18
  config = module.configuration()
19
+ assert config["enabled_providers"] == ["opencode"]
20
+ assert config["model"] == "opencode/muse-spark-1.3-contributor-free"
21
+ assert config["small_model"] == "opencode/muse-spark-1.3-contributor-free"
22
+ assert module.MUSE_MODEL == config["model"]
23
+ assert "mine" not in config.get("provider", {})
24
+ dumped = json.dumps(config)
25
+ assert "apiKey" not in dumped
26
+ assert "Authorization" not in dumped
27
+ assert "qwen" not in dumped.lower() and "granite" not in dumped.lower()
28
 
29
 
30
  def test_credentials_are_not_inherited(monkeypatch, tmp_path):
tests/test_voyager_documentation_conformance.py CHANGED
@@ -65,12 +65,14 @@ def test_readme_fabric_versions_match_the_installation_guide():
65
 
66
 
67
  def test_readme_world_setup_is_creative_and_peaceful():
68
- # README: "Set Game Mode to `Creative` and Difficulty to `Peaceful`."
69
- # minecraft_stack writes server.properties; read the values it writes.
 
 
70
  source = (ROOT / "minecraft_stack.py").read_text(encoding="utf-8")
71
  assert '"gamemode": "creative"' in source
72
- assert '"force-gamemode": "true"' in source
73
- assert '"difficulty": "peaceful"' in source
74
 
75
 
76
  def test_readme_fabric_mods_are_the_documented_set():
 
65
 
66
 
67
  def test_readme_world_setup_is_creative_and_peaceful():
68
+ # The AltoClef survival speedrun needs hostile mobs and loot, so the live
69
+ # server moved off the Voyager README default: default gamemode stays
70
+ # Creative for human builders, but force-gamemode is false so Naldo_Bot
71
+ # keeps Survival, and difficulty is Normal (blazes/endermen must exist).
72
  source = (ROOT / "minecraft_stack.py").read_text(encoding="utf-8")
73
  assert '"gamemode": "creative"' in source
74
+ assert '"force-gamemode": "false"' in source
75
+ assert '"difficulty": "normal"' in source
76
 
77
 
78
  def test_readme_fabric_mods_are_the_documented_set():