-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
3427 lines (3039 loc) · 129 KB
/
server.js
File metadata and controls
3427 lines (3039 loc) · 129 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const mineflayer = require('mineflayer')
const { pathfinder, Movements, goals } = require('mineflayer-pathfinder')
const { Vec3 } = require('vec3')
const express = require('express')
require('dotenv').config()
// ============================================
// CONFIG (from .env)
// ============================================
const BOT_CONFIG = {
host: process.env.BOT_HOST || 'localhost',
port: parseInt(process.env.BOT_PORT) || 57823,
username: process.env.BOT_USERNAME || 'AIBot',
version: process.env.BOT_VERSION || '1.21.4',
auth: process.env.BOT_AUTH || 'offline',
disableChatSigning: true
}
const API_PORT = parseInt(process.env.API_PORT) || 3001
// ============================================
// CREATE BOT
// ============================================
const bot = mineflayer.createBot(BOT_CONFIG)
bot.loadPlugin(pathfinder)
let botReady = false
let lastChatMessages = []
let lastReadChatIndex = 0 // Track which messages agent has seen
// ── Abort Flag (Python timeout → cancel long-running loops) ──
let abortFlag = false
// ── Death Tracking ──
let deathLog = []
let lastHealthSnapshot = { health: 20, food: 20, position: null, entities: [], time: null }
let lastDeathMessage = '' // Capture actual Minecraft death message
// ── Combat Tracking ──
let combatState = {
isUnderAttack: false, // Currently being hit
lastHitTime: 0, // timestamp of last damage taken
lastAttacker: null, // { type, distance, position }
healthBefore: 20, // health before last hit
healthDelta: 0, // damage taken in last hit
recentAttacks: [], // last 10 attacks [{type, damage, time, position}]
combatStartTime: 0, // when combat began (0 = not in combat)
}
// ── Drop Collection Tracking ──
let pendingDrops = []
// ── Lava Scan Helper ──
function scanForLava(pos, radius = 3) {
if (!botReady) return []
const lavaBlocks = bot.findBlocks({
matching: b => b.name === 'lava' || b.name === 'flowing_lava',
maxDistance: radius,
count: 20,
point: pos
})
return lavaBlocks.map(p => ({
position: { x: p.x, y: p.y, z: p.z },
distance: pos.distanceTo(p)
}))
}
// ── Lava Safety: try to use water bucket to neutralize lava ──
async function tryWaterBucketOnLava(lavaPos) {
const waterBucket = bot.inventory.items().find(i => i.name === 'water_bucket')
if (!waterBucket) return false
try {
await bot.equip(waterBucket, 'hand')
const lavaBlock = bot.blockAt(lavaPos)
if (lavaBlock) {
await bot.activateBlock(lavaBlock)
await new Promise(r => setTimeout(r, 500))
// Pick water back up (it should be a water source now turned to obsidian)
const bucket = bot.inventory.items().find(i => i.name === 'bucket')
if (bucket) {
await bot.equip(bucket, 'hand')
const waterBlock = bot.blockAt(lavaPos)
if (waterBlock && (waterBlock.name === 'water' || waterBlock.name === 'flowing_water')) {
await bot.activateBlock(waterBlock)
}
}
console.log(`[lava-safety] Neutralized lava at ${lavaPos.x}, ${lavaPos.y}, ${lavaPos.z}`)
return true
}
} catch (e) {
console.log(`[lava-safety] Failed to neutralize lava: ${e.message}`)
}
return false
}
// ============================================
// EXPRESS API SERVER
// ============================================
const app = express()
app.use(express.json())
// ── ABORT ENDPOINT ──
app.post('/abort', (req, res) => {
console.log('[abort] Abort requested by Python agent')
abortFlag = true
try { bot.pathfinder.setGoal(null) } catch (e) {}
res.json({ success: true, message: 'Abort flag set' })
})
// Clear stale abort flag on new action requests (prevents race condition
// where a previous timeout's abort flag blocks the next request)
app.use('/action', (req, res, next) => {
if (abortFlag) {
console.log('[abort] Clearing stale abort flag before new action')
abortFlag = false
}
next()
})
// ── STATE ENDPOINTS ──
// ── Auto-equip best tool helper (used by mine, dig_down, dig_tunnel, dig_shelter) ──
async function autoEquipBestTool(blockName) {
if (!blockName) blockName = 'stone'
const pickaxeBlocks = ['stone', 'cobblestone', 'iron_ore', 'coal_ore', 'gold_ore',
'diamond_ore', 'copper_ore', 'redstone_ore', 'lapis_ore', 'emerald_ore',
'deepslate', 'andesite', 'diorite', 'granite', 'netherrack', 'obsidian',
'nether_quartz_ore', 'nether_gold_ore', 'sandstone', 'blackstone', 'basalt',
'end_stone', 'terracotta', 'bricks', 'prismarine', 'concrete']
const axeBlocks = ['log', 'wood', 'planks', 'fence', 'door', 'bookshelf',
'crafting_table', 'chest', 'barrel', 'sign', 'bamboo', 'mushroom_block']
const shovelBlocks = ['dirt', 'grass_block', 'sand', 'gravel', 'clay',
'soul_sand', 'soul_soil', 'snow', 'mud', 'mycelium', 'podzol', 'farmland']
let toolType = null
for (const kw of pickaxeBlocks) {
if (blockName.includes(kw)) { toolType = 'pickaxe'; break }
}
if (!toolType) {
for (const kw of axeBlocks) {
if (blockName.includes(kw)) { toolType = 'axe'; break }
}
}
if (!toolType) {
for (const kw of shovelBlocks) {
if (blockName.includes(kw)) { toolType = 'shovel'; break }
}
}
if (!toolType) toolType = 'pickaxe'
// Search inventory for best tool of this type
const tiers = ['netherite', 'diamond', 'iron', 'stone', 'wooden', 'golden']
const available = bot.inventory.items().map(i => i.name)
console.log(`[auto-equip] Block: "${blockName}" → need: ${toolType} | inventory: ${available.filter(n => n.includes(toolType) || n.includes('sword') || n.includes('axe') || n.includes('pickaxe') || n.includes('shovel')).join(', ') || 'no tools'}`)
for (const tier of tiers) {
const toolName = `${tier}_${toolType}`
const item = bot.inventory.items().find(i => i.name === toolName)
if (item) {
await bot.equip(item, 'hand')
console.log(`[auto-equip] Equipped ${toolName}`)
return toolName
}
}
console.log(`[auto-equip] No ${toolType} found! Using fist.`)
return null
}
// GET /state - Full world state
app.get('/state', (req, res) => {
if (!botReady) return res.status(503).json({ error: 'Bot not ready' })
const pos = bot.entity.position
const nearbyBlocks = bot.findBlocks({
matching: (block) => block.name !== 'air',
maxDistance: 16,
count: 50
})
const blockNames = [...new Set(nearbyBlocks.map(p => bot.blockAt(p)?.name).filter(Boolean))]
const nearbyEntities = Object.values(bot.entities)
.filter(e => e !== bot.entity && e.position.distanceTo(pos) < 30)
.map(e => ({
type: e.name || e.username || 'unknown',
distance: parseFloat(e.position.distanceTo(pos).toFixed(1)),
position: { x: e.position.x.toFixed(1), y: e.position.y.toFixed(1), z: e.position.z.toFixed(1) }
}))
.sort((a, b) => a.distance - b.distance)
const inventory = bot.inventory.items().map(item => ({
name: item.name,
count: item.count,
durability: item.maxDurability ? {
current: item.maxDurability - (item.nbt?.value?.Damage?.value || 0),
max: item.maxDurability,
percent: Math.round(((item.maxDurability - (item.nbt?.value?.Damage?.value || 0)) / item.maxDurability) * 100)
} : null
}))
const emptySlots = 36 - inventory.length
// Time phases: 0-1000 sunrise, 1000-6000 morning, 6000-12000 afternoon,
// 12000-13000 dusk, 13000-18000 night, 18000-23000 midnight, 23000-24000 dawn
const t = bot.time.timeOfDay
let timePhase = 'day'
if (t >= 23000 || t < 1000) timePhase = 'dawn'
else if (t < 6000) timePhase = 'morning'
else if (t < 11000) timePhase = 'afternoon'
else if (t < 13000) timePhase = 'dusk'
else if (t < 18000) timePhase = 'night'
else timePhase = 'midnight'
// ── Environment detection ──
const headPos = pos.offset(0, 1, 0)
const blockLight = bot.blockAt(headPos)?.light ?? 0
const skyLightVal = bot.blockAt(headPos)?.skyLight ?? 0
// Check sky visibility: scan upward for solid blocks
let canSeeSky = true
let roofHeight = 0
for (let dy = 2; dy <= 64 && pos.y + dy <= 320; dy++) {
const above = bot.blockAt(pos.offset(0, dy, 0))
if (above && above.name !== 'air' && above.name !== 'cave_air'
&& above.name !== 'void_air' && !above.name.includes('leaves')
&& !above.name.includes('glass')) {
canSeeSky = false
roofHeight = dy
break
}
}
// Determine environment type
const y = Math.floor(pos.y)
let environment = 'surface'
if (!canSeeSky && y < 0) {
environment = 'deep_underground' // deepslate layer
} else if (!canSeeSky && y < 50) {
environment = 'underground' // cave or mine
} else if (!canSeeSky && y >= 50) {
environment = 'indoors' // under a roof but near surface level
}
const isDark = blockLight < 8
// ── Water detection ──
const isInWater = bot.entity.isInWater || false
const oxygenLevel = bot.oxygenLevel ?? 20 // 0-20, 20 = full air
const eyePos = pos.offset(0, 1.62, 0)
const eyeBlock = bot.blockAt(eyePos.floored())
const isUnderwater = isInWater && eyeBlock &&
(eyeBlock.name === 'water' || eyeBlock.name === 'flowing_water')
res.json({
position: { x: pos.x.toFixed(1), y: pos.y.toFixed(1), z: pos.z.toFixed(1) },
health: bot.health,
food: bot.food,
time: timePhase,
timeOfDay: t,
isSafeOutside: t < 12000 || t >= 23000,
environment,
canSeeSky,
lightLevel: blockLight,
isDark,
roofHeight: canSeeSky ? null : roofHeight,
isRaining: bot.isRaining,
isInWater,
oxygenLevel,
isUnderwater,
combat: {
isUnderAttack: combatState.isUnderAttack && (Date.now() - combatState.lastHitTime < 5000),
lastAttacker: combatState.lastAttacker,
healthDelta: combatState.healthDelta,
lastHitTime: combatState.lastHitTime,
timeSinceHit: combatState.lastHitTime ? Math.floor((Date.now() - combatState.lastHitTime) / 1000) : null,
},
inventory,
emptySlots,
nearbyBlocks: blockNames,
nearbyEntities,
recentChat: lastChatMessages.slice(-10)
})
})
// GET /combat_status - Detailed combat state for agent decision-making
app.get('/combat_status', (req, res) => {
if (!botReady) return res.status(503).json({ error: 'Bot not ready' })
// Refresh isUnderAttack based on time
const now = Date.now()
if (combatState.isUnderAttack && now - combatState.lastHitTime > 5000) {
combatState.isUnderAttack = false
combatState.combatStartTime = 0
combatState.lastAttacker = null
}
res.json({
isUnderAttack: combatState.isUnderAttack,
lastAttacker: combatState.lastAttacker,
healthDelta: combatState.healthDelta,
lastHitTime: combatState.lastHitTime,
timeSinceHit: combatState.lastHitTime ? Math.floor((now - combatState.lastHitTime) / 1000) : null,
combatDuration: combatState.combatStartTime ? Math.floor((now - combatState.combatStartTime) / 1000) : 0,
recentAttacks: combatState.recentAttacks,
health: bot.health,
food: bot.food,
})
})
// GET /inventory
app.get('/inventory', (req, res) => {
if (!botReady) return res.status(503).json({ error: 'Bot not ready' })
const items = bot.inventory.items().map(item => ({
name: item.name,
count: item.count,
slot: item.slot
}))
res.json({ items })
})
// GET /surrounding_blocks - Check blocks immediately around bot (for stuck detection)
app.get('/surrounding_blocks', (req, res) => {
if (!botReady) return res.status(503).json({ error: 'Bot not ready' })
const pos = bot.entity.position.floored()
// Check 4 horizontal directions at feet and head level
const directions = [
{ name: 'north', dx: 0, dz: -1 },
{ name: 'south', dx: 0, dz: 1 },
{ name: 'east', dx: 1, dz: 0 },
{ name: 'west', dx: -1, dz: 0 }
]
const passable = (block) => !block || block.name === 'air' || block.boundingBox !== 'block'
const result = {}
for (const dir of directions) {
const feet = bot.blockAt(pos.offset(dir.dx, 0, dir.dz))
const head = bot.blockAt(pos.offset(dir.dx, 1, dir.dz))
const feetPassable = passable(feet)
const headPassable = passable(head)
result[dir.name] = {
feet: { name: feet?.name || 'air', passable: feetPassable },
head: { name: head?.name || 'air', passable: headPassable },
open: feetPassable && headPassable,
x: pos.x + dir.dx,
z: pos.z + dir.dz
}
}
// Also check above and below
const above = bot.blockAt(pos.offset(0, 2, 0))
const below = bot.blockAt(pos.offset(0, -1, 0))
result.above = { name: above?.name || 'air', passable: passable(above) }
result.below = { name: below?.name || 'air', passable: passable(below) }
result.position = { x: pos.x, y: pos.y, z: pos.z }
res.json(result)
})
// GET /nearby
app.get('/nearby', (req, res) => {
if (!botReady) return res.status(503).json({ error: 'Bot not ready' })
const range = parseInt(req.query.range) || 16
const pos = bot.entity.position
const blocks = bot.findBlocks({
matching: (block) => block.name !== 'air',
maxDistance: range,
count: 100
})
const blockCounts = {}
blocks.forEach(p => {
const name = bot.blockAt(p)?.name
if (name) blockCounts[name] = (blockCounts[name] || 0) + 1
})
const entities = Object.values(bot.entities)
.filter(e => e !== bot.entity && e.position.distanceTo(pos) < range)
.map(e => ({
type: e.name || e.username || 'unknown',
distance: parseFloat(e.position.distanceTo(pos).toFixed(1)),
position: { x: e.position.x.toFixed(1), y: e.position.y.toFixed(1), z: e.position.z.toFixed(1) }
}))
.sort((a, b) => a.distance - b.distance)
res.json({ blocks: blockCounts, entities })
})
// GET /chat
app.get('/chat', (req, res) => {
res.json({ messages: lastChatMessages.slice(-20) })
})
// GET /chat/unread - Get new chat messages since last check (for agent priority)
app.get('/chat/unread', (req, res) => {
const unread = lastChatMessages.slice(lastReadChatIndex)
lastReadChatIndex = lastChatMessages.length
// Filter out bot's own messages
const playerMessages = unread.filter(m => m.username !== bot.username)
res.json({ messages: playerMessages, count: playerMessages.length })
})
// GET /threat_assessment - Evaluate combat readiness vs nearby threats
app.get('/threat_assessment', (req, res) => {
if (!botReady) return res.status(503).json({ error: 'Bot not ready' })
const pos = bot.entity.position
const health = bot.health
const food = bot.food
// ── Inventory analysis ──
const items = bot.inventory.items()
const weaponTiers = {
'diamond_sword': 7, 'iron_sword': 6, 'stone_sword': 5, 'wooden_sword': 4,
'diamond_axe': 6, 'iron_axe': 5, 'stone_axe': 4, 'wooden_axe': 3,
}
const armorValues = {
'diamond_helmet': 3, 'diamond_chestplate': 8, 'diamond_leggings': 6, 'diamond_boots': 3,
'iron_helmet': 2, 'iron_chestplate': 6, 'iron_leggings': 5, 'iron_boots': 2,
'chainmail_helmet': 2, 'chainmail_chestplate': 5, 'chainmail_leggings': 4, 'chainmail_boots': 1,
'leather_helmet': 1, 'leather_chestplate': 3, 'leather_leggings': 2, 'leather_boots': 1,
}
// Best weapon
let bestWeapon = null
let weaponPower = 0
for (const item of items) {
if (weaponTiers[item.name] && weaponTiers[item.name] > weaponPower) {
bestWeapon = item.name
weaponPower = weaponTiers[item.name]
}
}
// Total armor
let totalArmor = 0
const armorSlots = [bot.inventory.slots[5], bot.inventory.slots[6], bot.inventory.slots[7], bot.inventory.slots[8]]
for (const slot of armorSlots) {
if (slot && armorValues[slot.name]) {
totalArmor += armorValues[slot.name]
}
}
// Shield
const hasShield = items.some(i => i.name === 'shield')
// Food count
const foods = ['cooked_beef', 'cooked_porkchop', 'cooked_chicken', 'cooked_mutton',
'bread', 'golden_apple', 'apple', 'melon_slice', 'baked_potato',
'beef', 'porkchop', 'chicken', 'mutton', 'potato', 'carrot',
'sweet_berries', 'dried_kelp']
let foodCount = 0
for (const item of items) {
if (foods.includes(item.name)) foodCount += item.count
}
// ── Threat analysis ──
const hostileMobs = {
'zombie': { danger: 2, drops: true },
'husk': { danger: 2, drops: true },
'skeleton': { danger: 3, drops: true },
'stray': { danger: 3, drops: true },
'spider': { danger: 2, drops: true },
'creeper': { danger: 5, drops: false },
'enderman': { danger: 4, drops: true },
'witch': { danger: 4, drops: true },
'drowned': { danger: 2, drops: true },
'phantom': { danger: 3, drops: false },
'pillager': { danger: 3, drops: true },
'vindicator': { danger: 5, drops: true },
'ravager': { danger: 6, drops: false },
'warden': { danger: 10, drops: false },
}
const nearby = Object.values(bot.entities)
.filter(e => e !== bot.entity && e.position.distanceTo(pos) < 20)
.map(e => ({
type: e.name || 'unknown',
distance: parseFloat(e.position.distanceTo(pos).toFixed(1)),
}))
.sort((a, b) => a.distance - b.distance)
const threats = nearby.filter(e => hostileMobs[e.type])
let totalDanger = 0
const threatDetails = threats.map(t => {
const mob = hostileMobs[t.type]
const dangerScaled = mob.danger * (1 + Math.max(0, (10 - t.distance)) / 10) // closer = more dangerous
totalDanger += dangerScaled
return { type: t.type, distance: t.distance, danger: mob.danger }
})
// ── Combat score ──
// Player power = weapon + armor + health + food buffer
const playerPower = weaponPower + (totalArmor * 0.5) + (health * 0.3) + (foodCount > 0 ? 2 : 0)
// ── Decision ──
let recommendation = 'safe'
let reason = ''
if (threats.length === 0) {
recommendation = 'safe'
reason = 'No threats nearby.'
} else if (totalDanger >= 8 && playerPower < 5) {
recommendation = 'flee'
reason = `High danger (${totalDanger.toFixed(1)}) vs low power (${playerPower.toFixed(1)}). Multiple/strong threats without gear.`
} else if (threats.some(t => t.type === 'creeper' && t.distance < 8)) {
recommendation = 'flee'
reason = 'Creeper nearby! Risk of explosion. Back away and use ranged or wait for it to pass.'
} else if (threats.some(t => t.type === 'warden')) {
recommendation = 'flee'
reason = 'WARDEN detected! Extremely dangerous. Sneak away immediately.'
} else if (health <= 6 && foodCount === 0) {
recommendation = 'flee'
reason = `Low health (${health}/20) and no food. Cannot sustain combat.`
} else if (weaponPower === 0 && totalDanger > 3) {
recommendation = 'avoid'
reason = `No weapon against ${threats.length} hostile(s). Craft a sword first.`
} else if (playerPower > totalDanger * 1.5) {
recommendation = 'fight'
reason = `Strong advantage (power: ${playerPower.toFixed(1)} vs danger: ${totalDanger.toFixed(1)}). Should be safe to engage.`
} else if (playerPower > totalDanger) {
recommendation = 'fight_careful'
reason = `Slight advantage (power: ${playerPower.toFixed(1)} vs danger: ${totalDanger.toFixed(1)}). Watch health and eat if needed.`
} else {
recommendation = 'avoid'
reason = `Outmatched (power: ${playerPower.toFixed(1)} vs danger: ${totalDanger.toFixed(1)}). Gear up first or reduce threat count.`
}
const isNight = bot.time.timeOfDay > 13000
res.json({
recommendation, // 'safe', 'fight', 'fight_careful', 'avoid', 'flee'
reason,
combat_readiness: {
weapon: bestWeapon || 'none (fist)',
weapon_power: weaponPower,
armor_points: totalArmor,
shield: hasShield,
health,
food: bot.food,
food_items: foodCount,
player_power: parseFloat(playerPower.toFixed(1)),
},
threats: {
count: threats.length,
total_danger: parseFloat(totalDanger.toFixed(1)),
details: threatDetails,
is_night: isNight,
},
})
})
app.get('/find_block', (req, res) => {
if (!botReady) return res.status(503).json({ error: 'Bot not ready' })
const blockType = req.query.type
const maxDist = parseInt(req.query.range) || 64
// Exact match + deepslate variant for ores (e.g., iron_ore → also matches deepslate_iron_ore)
const block = bot.findBlock({
matching: b => b.name === blockType || b.name === 'deepslate_' + blockType,
maxDistance: maxDist
})
if (block) {
res.json({
success: true,
message: `Found ${block.name} at (${block.position.x}, ${block.position.y}, ${block.position.z})`,
block: { name: block.name, position: { x: block.position.x, y: block.position.y, z: block.position.z } }
})
} else {
res.json({ success: false, message: `No ${blockType} found within ${maxDist} blocks` })
}
})
// GET /search_item - Search for item/block names by keyword
app.get('/search_item', (req, res) => {
if (!botReady) return res.status(503).json({ error: 'Bot not ready' })
const query = (req.query.q || '').toLowerCase()
if (!query) return res.json({ error: 'Provide ?q=keyword' })
const mcData = require('minecraft-data')(bot.version)
// Search items
const items = Object.values(mcData.itemsByName)
.filter(i => i.name.includes(query) || (i.displayName || '').toLowerCase().includes(query))
.map(i => ({ name: i.name, displayName: i.displayName, id: i.id, type: 'item' }))
.slice(0, 20)
// Search blocks
const blocks = Object.values(mcData.blocksByName)
.filter(b => b.name.includes(query) || (b.displayName || '').toLowerCase().includes(query))
.map(b => ({ name: b.name, displayName: b.displayName, id: b.id, type: 'block' }))
.slice(0, 20)
res.json({
query,
results: [...items, ...blocks],
total: items.length + blocks.length,
tip: 'Use the "name" field (e.g., "oak_log", "wooden_pickaxe") when calling tools.'
})
})
// GET /death_log - Recent deaths with pre-death snapshots
app.get('/death_log', (req, res) => {
const count = parseInt(req.query.count) || 10
res.json({
total_deaths: deathLog.length,
deaths: deathLog.slice(-count)
})
})
// POST /death_log/clear
app.post('/death_log/clear', (req, res) => {
const cleared = deathLog.length
deathLog = []
res.json({ success: true, message: `Cleared ${cleared} death records` })
})
// ── ACTION ENDPOINTS ──
// POST /action/move
app.post('/action/move', async (req, res) => {
if (!botReady) return res.status(503).json({ error: 'Bot not ready' })
try {
const { x, y, z, range } = req.body
const target = new Vec3(x, y, z)
const dist = bot.entity.position.distanceTo(target)
// Dynamic timeout: 2 seconds per block, min 15s, max 120s
const timeoutMs = Math.max(15000, Math.min(120000, dist * 2000))
// Helper: try mining the block in front of the bot (toward target) to clear path
async function tryMineObstacle() {
const pos = bot.entity.position
const dir = target.minus(pos)
const len = Math.sqrt(dir.x * dir.x + dir.z * dir.z) || 1
// Normalized direction (only X/Z, rounded to nearest block)
const dx = Math.round(dir.x / len)
const dz = Math.round(dir.z / len)
// Try mining at eye level and foot level in front of bot
for (const dy of [0, 1]) {
const blockPos = pos.floored().offset(dx, dy, dz)
const block = bot.blockAt(blockPos)
if (block && block.name !== 'air' && block.name !== 'cave_air' && block.name !== 'water'
&& block.boundingBox === 'block' && block.diggable) {
try {
await bot.dig(block)
return true
} catch (e) { /* can't dig */ }
}
}
return false
}
let timedOut = false
const timer = setTimeout(() => {
timedOut = true
bot.pathfinder.setGoal(null)
}, timeoutMs)
try {
await bot.pathfinder.goto(new goals.GoalNear(x, y, z, range || 2))
clearTimeout(timer)
if (timedOut) {
// First attempt failed — try mining obstacle and retry once
const mined = await tryMineObstacle()
if (mined) {
let retry2TimedOut = false
const retryTimer = setTimeout(() => {
retry2TimedOut = true
bot.pathfinder.setGoal(null)
}, Math.min(timeoutMs, 30000))
try {
await bot.pathfinder.goto(new goals.GoalNear(x, y, z, range || 2))
clearTimeout(retryTimer)
if (!retry2TimedOut) {
return res.json({ success: true, message: `Moved to ${x}, ${y}, ${z} (mined obstacle)` })
}
} catch (e) { clearTimeout(retryTimer) }
}
const finalDist = bot.entity.position.distanceTo(target).toFixed(1)
res.json({ success: false, message: `Movement blocked. ${finalDist} blocks away from target (${x}, ${y}, ${z}). Mined obstacle: ${mined ? 'yes' : 'no'}.` })
} else {
res.json({ success: true, message: `Moved to ${x}, ${y}, ${z}` })
}
} catch (pathErr) {
clearTimeout(timer)
// Try mining obstacle before giving up
const mined = await tryMineObstacle()
if (mined) {
try {
const retryTimer = setTimeout(() => { bot.pathfinder.setGoal(null) }, Math.min(timeoutMs, 30000))
await bot.pathfinder.goto(new goals.GoalNear(x, y, z, range || 2))
clearTimeout(retryTimer)
return res.json({ success: true, message: `Moved to ${x}, ${y}, ${z} (mined obstacle)` })
} catch (e) { /* still failed */ }
}
const finalDist = bot.entity.position.distanceTo(target).toFixed(1)
res.json({ success: false, message: `Movement blocked. ${finalDist} blocks away from target (${x}, ${y}, ${z}). Mined obstacle: ${mined ? 'yes' : 'no'}.` })
}
} catch (err) {
res.json({ success: false, message: err.message })
}
})
// POST /action/move_to_player
app.post('/action/move_to_player', async (req, res) => {
if (!botReady) return res.status(503).json({ error: 'Bot not ready' })
try {
const { player_name } = req.body
const target = player_name
? bot.players[player_name]?.entity
: Object.values(bot.players).find(p => p.entity && p.username !== bot.username)?.entity
if (!target) return res.json({ success: false, message: `Player ${player_name || 'any'} not found nearby` })
const timeout = setTimeout(() => { bot.pathfinder.setGoal(null) }, 30000)
await bot.pathfinder.goto(new goals.GoalNear(target.position.x, target.position.y, target.position.z, 2))
clearTimeout(timeout)
res.json({ success: true, message: `Moved to player ${player_name || target.username}` })
} catch (err) {
res.json({ success: false, message: err.message })
}
})
// POST /action/follow
app.post('/action/follow', (req, res) => {
if (!botReady) return res.status(503).json({ error: 'Bot not ready' })
const { player_name } = req.body
const target = player_name
? bot.players[player_name]?.entity
: Object.values(bot.players).find(p => p.entity && p.username !== bot.username)?.entity
if (!target) return res.json({ success: false, message: 'Player not found' })
bot.pathfinder.setGoal(new goals.GoalFollow(target, 3), true)
res.json({ success: true, message: `Following ${player_name || 'player'}` })
})
// POST /action/stop
app.post('/action/stop', (req, res) => {
if (!botReady) return res.status(503).json({ error: 'Bot not ready' })
bot.pathfinder.setGoal(null)
res.json({ success: true, message: 'Stopped moving' })
})
// POST /action/explore
app.post('/action/explore', async (req, res) => {
if (!botReady) return res.status(503).json({ error: 'Bot not ready' })
try {
const { distance } = req.body
const dist = distance || 20
const x = bot.entity.position.x + (Math.random() - 0.5) * dist * 2
const z = bot.entity.position.z + (Math.random() - 0.5) * dist * 2
const y = bot.entity.position.y
const timeout = setTimeout(() => { bot.pathfinder.setGoal(null) }, 30000)
bot.pathfinder.setGoal(new goals.GoalNear(x, y, z, 3))
clearTimeout(timeout)
res.json({ success: true, message: `Exploring towards x=${x.toFixed(0)}, z=${z.toFixed(0)}` })
} catch (err) {
res.json({ success: false, message: err.message })
}
})
// POST /action/mine
app.post('/action/mine', async (req, res) => {
if (!botReady) return res.status(503).json({ error: 'Bot not ready' })
try {
const { block_type, count } = req.body
const mineCount = count || 1
let mined = 0
// Auto-equip best tool for the job
let equippedTool = await autoEquipBestTool(block_type)
// Fallback: if autoEquipBestTool found nothing, check if bot is already holding a valid tool
// (Python-side _auto_equip_for_mining may have equipped it via /action/equip before this call)
if (!equippedTool && bot.heldItem) {
const held = bot.heldItem.name
if (held.includes('pickaxe') || held.includes('axe') || held.includes('shovel')) {
console.log(`[auto-equip] Fallback: bot already holding ${held}`)
equippedTool = held
}
}
// ── Tool requirement checks ──
const requiresPickaxe = ['iron_ore', 'coal_ore', 'gold_ore', 'diamond_ore', 'copper_ore',
'redstone_ore', 'lapis_ore', 'emerald_ore', 'nether_quartz_ore', 'nether_gold_ore',
'obsidian', 'deepslate_iron_ore', 'deepslate_coal_ore', 'deepslate_gold_ore',
'deepslate_diamond_ore', 'deepslate_copper_ore', 'deepslate_redstone_ore',
'deepslate_lapis_ore', 'deepslate_emerald_ore']
const requiresTool = ['stone', 'cobblestone', 'deepslate', ...requiresPickaxe]
const needsTool = requiresTool.some(kw => block_type.includes(kw))
if (needsTool && !equippedTool) {
return res.json({
success: false,
message: `Cannot mine ${block_type} without a tool! Craft a pickaxe first.`
})
}
const needsStonePlus = requiresPickaxe.some(kw => block_type.includes(kw))
if (needsStonePlus && equippedTool && equippedTool.startsWith('wooden_')) {
return res.json({ success: false, message: `${block_type} needs stone_pickaxe or better!` })
}
const needsIronPlus = ['diamond_ore', 'deepslate_diamond_ore', 'gold_ore', 'deepslate_gold_ore',
'emerald_ore', 'deepslate_emerald_ore', 'redstone_ore', 'deepslate_redstone_ore']
if (needsIronPlus.some(kw => block_type.includes(kw)) && equippedTool &&
(equippedTool.startsWith('wooden_') || equippedTool.startsWith('stone_'))) {
return res.json({ success: false, message: `${block_type} needs iron_pickaxe or better!` })
}
const isWood = ['log', 'wood'].some(kw => block_type.includes(kw))
// ── Helper: force-equip the mining tool and verify it's held ──
const ensureToolHeld = async () => {
if (!equippedTool) return
const held = bot.heldItem?.name
if (held === equippedTool) return // already correct
// Try to equip
const toolItem = bot.inventory.items().find(i => i.name === equippedTool)
if (!toolItem) {
// Tool broke or lost — find next best
equippedTool = await autoEquipBestTool(block_type)
await new Promise(r => setTimeout(r, 150))
return
}
try {
await bot.equip(toolItem, 'hand')
await new Promise(r => setTimeout(r, 150)) // wait for server to process
console.log(`[mine] Re-equipped ${equippedTool} (was holding: ${held || 'nothing'})`)
} catch (e) {
console.log(`[mine] Re-equip failed: ${e.message}, retrying...`)
// Second attempt
try {
const freshItem = bot.inventory.items().find(i => i.name === equippedTool)
if (freshItem) {
await bot.equip(freshItem, 'hand')
await new Promise(r => setTimeout(r, 150))
}
} catch (e2) { /* give up */ }
}
}
// ── Use non-scaffolding movements for mine pathfinding ──
// Prevents pathfinder from equipping blocks (which changes held tool)
const mcData = require('minecraft-data')(bot.version)
const mineMovements = new Movements(bot, mcData)
mineMovements.allowSprinting = true
mineMovements.scafoldingBlocks = [] // CRITICAL: don't scaffold during mining
bot.pathfinder.setMovements(mineMovements)
// ── Helper: clear obstructing blocks between bot and target ──
const clearPathTo = async (targetPos) => {
const botPos = bot.entity.position.floored()
const dx = Math.sign(targetPos.x - botPos.x)
const dz = Math.sign(targetPos.z - botPos.z)
// Clear blocks in the direction of the target (feet + head level, 3 blocks ahead)
for (let step = 1; step <= 3; step++) {
if (abortFlag) break
for (let dy = 0; dy <= 1; dy++) {
const checkPos = botPos.offset(dx * step, dy, dz * step)
const b = bot.blockAt(checkPos)
if (b && b.boundingBox === 'block' && b.name !== 'air' && b.name !== 'cave_air'
&& !b.name.includes(block_type)) {
try { await bot.dig(b) } catch (e) { /* ignore */ }
}
}
}
}
// ── Helper: collect dropped items near a position ──
const collectItemsNear = async (pos, radius = 8) => {
const nearbyItems = Object.values(bot.entities).filter(
e => e.name === 'item' && e.position.distanceTo(pos) < radius
)
for (const item of nearbyItems) {
if (abortFlag) break
// Clear any lingering pathfinder goal before each item attempt
try { bot.pathfinder.setGoal(null) } catch (e) {}
const t = setTimeout(() => { try { bot.pathfinder.setGoal(null) } catch(e) {} }, 3000)
try {
await bot.pathfinder.goto(new goals.GoalNear(item.position.x, item.position.y, item.position.z, 1))
await new Promise(r => setTimeout(r, 250))
} catch (e) {
/* item may have been collected already or path blocked */
} finally {
clearTimeout(t)
}
}
}
// ── Main mining loop ──
const failedPositions = new Set() // Track unreachable block positions
const MAX_FAILS = 10 // Safety limit for unreachable blocks
for (let i = 0; i < mineCount; i++) {
if (failedPositions.size >= MAX_FAILS) break
if (abortFlag) {
abortFlag = false
return res.json({ success: false, message: `Aborted after ${mined} ${block_type}` })
}
// 1. Find the target block using block IDs (more reliable than callback matching)
const blockType1 = mcData.blocksByName[block_type]
const blockType2 = mcData.blocksByName['deepslate_' + block_type]
const matchIds = []
if (blockType1) matchIds.push(blockType1.id)
if (blockType2) matchIds.push(blockType2.id)
let block = null
if (matchIds.length > 0) {
// findBlocks returns Vec3 positions — filter by failedPositions, then get Block
const foundPositions = bot.findBlocks({
matching: matchIds,
maxDistance: 64,
count: 20
})
for (const pos of foundPositions) {
const key = `${pos.x},${pos.y},${pos.z}`
if (!failedPositions.has(key)) {
block = bot.blockAt(pos)
if (block && block.name !== 'air') break
block = null
}
}
}
if (!block) {
if (mined === 0) {
if (failedPositions.size > 0) {
return res.json({ success: false, message: `Found ${failedPositions.size} ${block_type} but all unreachable (enclosed in stone). Try mining toward them.` })
}
return res.json({ success: false, message: `No ${block_type} found nearby` })
}
break
}
const targetPos = block.position
const dist = bot.entity.position.distanceTo(targetPos)
console.log(`[mine] Found ${block.name} at ${targetPos} (dist=${dist.toFixed(1)})`)
// 2. For trees: clear leaves around target so bot can approach and items can drop
if (isWood) {
for (let dx = -2; dx <= 2; dx++) {
for (let dy = -1; dy <= 2; dy++) {
for (let dz = -2; dz <= 2; dz++) {
if (abortFlag) break
const b = bot.blockAt(targetPos.offset(dx, dy, dz))
if (b && b.name.includes('leaves')) {
try { await bot.dig(b) } catch (e) { /* ignore */ }
}
}
}
}
}
// 3. Move to within reach of the block
let reachedTarget = false
const REACH = 4.5
// Attempt 1: normal pathfinding
try {
const t = setTimeout(() => { bot.pathfinder.setGoal(null) }, 15000)
await bot.pathfinder.goto(new goals.GoalNear(targetPos.x, targetPos.y, targetPos.z, 2))
clearTimeout(t)
} catch (e) { /* pathfinding may fail partially */ }
if (bot.entity.position.distanceTo(targetPos) <= REACH) {
reachedTarget = true
}
// Attempt 2: if still too far, clear obstacles and walk closer
if (!reachedTarget) {
console.log(`[mine] Pathfind incomplete (dist=${bot.entity.position.distanceTo(targetPos).toFixed(1)}), clearing path...`)
await clearPathTo(targetPos)
try {
const t = setTimeout(() => { bot.pathfinder.setGoal(null) }, 10000)
await bot.pathfinder.goto(new goals.GoalNear(targetPos.x, targetPos.y, targetPos.z, 2))
clearTimeout(t)
} catch (e) { /* best effort */ }
reachedTarget = bot.entity.position.distanceTo(targetPos) <= REACH
}
if (!reachedTarget) {
console.log(`[mine] Cannot reach ${block.name} at ${targetPos} (dist=${bot.entity.position.distanceTo(targetPos).toFixed(1)}), blacklisting`)
failedPositions.add(`${targetPos.x},${targetPos.y},${targetPos.z}`)
i-- // Don't count failed attempts against mineCount
continue
}
// 4. Force re-equip tool right before dig (handles pathfinder scaffold, tool break, etc.)
await ensureToolHeld()
// 4b. If tool broke mid-loop and block requires one, stop mining
if (!equippedTool && needsTool) {
console.log(`[mine] Tool broke and no replacement available — stopping after ${mined} mined`)
break
}
// 5. Dig the block
const targetBlock = bot.blockAt(targetPos)
if (targetBlock && targetBlock.name !== 'air' && targetBlock.name !== 'cave_air'
&& targetBlock.boundingBox === 'block') {