ghast 0.5.6

Headless Minecraft Java Edition client / bot library (1.8.9, 1.12.2, 1.16.5, 26.1, 26.2 and 26.3) with vanilla-exact behaviour: facade crate re-exporting the ghast-* crates
Documentation
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
//! Combat and hands scenarios for the lab (`lab/combat.sh` drives them). The mode is the
//! `PROBE` environment variable:
//!
//! - `attack` (default): runs at the nearest target (`TARGET=mob|player`), attacks it once it
//!   is under the crosshair, backs off to `RETREAT` blocks (default 4.5), repeats. `SPRINT=1`
//!   sprints on the approach (a sprint attack), `SPRINT=0` walks (a plain attack).
//! - `victim`: walks forward, back, left and right in turn (20 ticks each) and logs the hurts
//!   and knockbacks it takes (an attacker bot runs at it).
//! - `miss`: walks and presses the left button at the sky with growing gaps (2 … 15 ticks),
//!   logs presses and swings (each released press swings again: the release ends the miss
//!   delay); then holds one press at the sky while turning down to the ground and logs when
//!   the dig starts (the 10-tick miss delay holds it back).
//! - `equip`: right-clicks every armor piece in the hotbar (slots 0 … 7, two sets: the second
//!   set finds the slots taken) and checks that the predicted armor and hotbar slots still
//!   hold 15 ticks later, when the server's slot updates have arrived (`correction` lines).
//! - `use`: holds the right button with hotbar slot 0 (40 ticks, `HOLD` to change), walking
//!   forward meanwhile, sprinting too with `SPRINT=1`.
//! - `inventory`: keeps the movement keys held (forward + sprint, then back), opens the own
//!   inventory, clicks a slot twice, closes it after 20 ticks, every 80 ticks. `REPRESS=1`
//!   lets go of the keys for a tick after the opening (1.16.5 then walks with it open).
//! - `clicks`: queued left clicks (`TickContext::press`) at `CPS` clicks per second (default
//!   12) on the nearest target (`TARGET=mob|player`) while strafing (left and right in turn,
//!   forward / back to stay 2 … 3 blocks away) and turning (the aim sweeps a few degrees around
//!   the target's middle, so some clicks miss and start the miss delay). Logs the presses, the
//!   attacks and the swings sent.
//!
//! Every mode logs Grim alerts seen in chat and server corrections (`ALERT`) and a summary at
//! the end.
//!
//! ```text
//! PROBE=attack TARGET=mob SPRINT=1 cargo run -p ghast --release --example combat_probe -- \
//!     --host 127.0.0.1 --port 25618 --username GhastBot2 --version 1.8.9 --minutes 1
//! ```

mod support;

use std::time::{Duration, Instant};

use ghast::{Behavior, Buttons, Controls, Interests, TickContext, Vec3};

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Mode {
    Attack,
    Victim,
    Miss,
    Equip,
    Use,
    Inventory,
    Clicks,
}

fn env(name: &str) -> Option<String> {
    std::env::var(name).ok().filter(|v| !v.is_empty())
}

struct Probe {
    mode: Mode,
    players: bool,
    sprint: bool,
    retreat: f64,
    hold: u64,
    n: u64,
    // attack
    approaching: bool,
    state_ticks: u64,
    attacks: u32,
    sprint_attacks: u32,
    after_attack: Option<(u64, bool, Vec3)>,
    // victim
    hurts: u32,
    last_hurt: Option<u64>,
    // miss
    presses: u32,
    gap_index: usize,
    held_press: Option<u64>,
    next_press: u64,
    // equip
    equip_slot: u8,
    pending_equip: Option<(u64, u8, [Option<i32>; 5])>,
    corrections: u32,
    equips: u32,
    // use
    was_using: bool,
    /// `RELEASE_ON_FINISH=1`: the right button stays up for one tick after a finish.
    release_ticks: u8,
    uses: u32,
    // inventory
    opened_at: Option<u64>,
    opens: u32,
    clicks: u32,
    refusals: u32,
    // clicks
    cps: f64,
    click_budget: f64,
    sent_attacks: u32,
    sent_swings: u32,
    // all
    alerts: u32,
    setbacks: u32,
    started: Instant,
    limit: Option<Duration>,
}

const GAPS: [u64; 7] = [2, 4, 6, 8, 10, 12, 15];

impl Probe {
    fn new(limit: Option<Duration>) -> Probe {
        let mode = match env("PROBE").as_deref() {
            None | Some("attack") => Mode::Attack,
            Some("victim") => Mode::Victim,
            Some("miss") => Mode::Miss,
            Some("equip") => Mode::Equip,
            Some("use") => Mode::Use,
            Some("inventory") => Mode::Inventory,
            Some("clicks") => Mode::Clicks,
            Some(m) => {
                log::error!("unknown PROBE {m}");
                std::process::exit(2);
            }
        };
        Probe {
            mode,
            players: env("TARGET").as_deref() == Some("player"),
            sprint: env("SPRINT").as_deref() == Some("1"),
            retreat: env("RETREAT").and_then(|v| v.parse().ok()).unwrap_or(4.5),
            hold: env("HOLD").and_then(|v| v.parse().ok()).unwrap_or(40),
            n: 0,
            approaching: true,
            state_ticks: 0,
            attacks: 0,
            sprint_attacks: 0,
            after_attack: None,
            hurts: 0,
            last_hurt: None,
            presses: 0,
            gap_index: 0,
            held_press: None,
            next_press: 0,
            equip_slot: 0,
            pending_equip: None,
            corrections: 0,
            equips: 0,
            was_using: false,
            release_ticks: 0,
            uses: 0,
            opened_at: None,
            opens: 0,
            clicks: 0,
            refusals: 0,
            cps: env("CPS").and_then(|v| v.parse().ok()).unwrap_or(12.0),
            click_budget: 0.0,
            sent_attacks: 0,
            sent_swings: 0,
            alerts: 0,
            setbacks: 0,
            started: Instant::now(),
            limit,
        }
    }

    fn summary(&self) -> String {
        format!(
            "summary mode {:?}: attacks {} (sprinting {}), hurts {}, presses {}, equips {}, \
             corrections {}, uses {}, opens {}, clicks {}, refusals {}, sent attacks {}, \
             sent swings {}, alerts {}, setbacks {}",
            self.mode,
            self.attacks,
            self.sprint_attacks,
            self.hurts,
            self.presses,
            self.equips,
            self.corrections,
            self.uses,
            self.opens,
            self.clicks,
            self.refusals,
            self.sent_attacks,
            self.sent_swings,
            self.alerts,
            self.setbacks
        )
    }

    /// Yaw / pitch from the eyes to the middle of a box.
    fn look_at(ctx: &TickContext<'_>, b: [f64; 6]) -> (f32, f32, f64) {
        let eyes = ctx.eyes(ctx.pose());
        let (dx, dy, dz) = (
            (b[0] + b[3]) / 2.0 - eyes.x,
            (b[1] + b[4]) / 2.0 - eyes.y,
            (b[2] + b[5]) / 2.0 - eyes.z,
        );
        let yaw = (-dx).atan2(dz).to_degrees() as f32;
        let pitch = -(dy.atan2((dx * dx + dz * dz).sqrt())).to_degrees() as f32;
        let cur = ctx.pose().yaw;
        (
            cur + ghast::rotation::wrap_degrees(yaw - cur),
            pitch,
            (dx * dx + dz * dz).sqrt(),
        )
    }

    fn attack(&mut self, ctx: &mut TickContext<'_>) {
        if let Some((tick, sprinted, before)) = self.after_attack.take() {
            let m = ctx.pose().motion;
            log::info!(
                "after attack at {tick} (sprinting {sprinted}): motion x/z {:.4} {:.4} -> {:.4} {:.4}, \
                 sprinting {}, server sprint flag {}, next look {:.4} {:.4}",
                before.x,
                before.z,
                m.x,
                m.z,
                ctx.pose().sprinting,
                ctx.server_sprinting(),
                ctx.sent().yaw,
                ctx.sent().pitch
            );
        }
        let me = ctx.entity_id();
        let eyes = ctx.eyes(ctx.pose());
        let players = self.players;
        let Some(ents) = ctx.entities() else {
            return;
        };
        let target = ents
            .within([eyes.x, eyes.y, eyes.z], 16.0)
            .filter(|e| {
                e.id() != me
                    && e.is_player() == players
                    && e.is_alive()
                    && !matches!(
                        e.class(),
                        ghast::entity::EntityClass::Item
                            | ghast::entity::EntityClass::ExperienceOrb
                    )
            })
            .filter_map(|e| Some((e.id(), e.drawn_bounding_box().or(e.bounding_box())?)))
            .min_by(|a, b| {
                let d = |x: &[f64; 6]| {
                    let (cx, cz) = ((x[0] + x[3]) / 2.0 - eyes.x, (x[2] + x[5]) / 2.0 - eyes.z);
                    cx * cx + cz * cz
                };
                d(&a.1).total_cmp(&d(&b.1))
            });
        let Some((id, b)) = target else {
            if self.n.is_multiple_of(40) {
                log::debug!(
                    "tick {}: no target among {} entities",
                    ctx.tick(),
                    ents.len()
                );
                for e in ents.iter() {
                    log::debug!(
                        "  {} {:?} {:?} at {:?} alive {} player {} box {:?}",
                        e.id(),
                        e.entity_type(),
                        e.class(),
                        e.position(),
                        e.is_alive(),
                        e.is_player(),
                        e.bounding_box()
                    );
                }
            }
            ctx.set_controls(Controls::NONE);
            return;
        };
        let (yaw, pitch, dist) = Self::look_at(ctx, b);
        ctx.set_aim(yaw, pitch);
        self.state_ticks += 1;
        if self.n.is_multiple_of(20) {
            log::debug!(
                "tick {}: target {id} at {dist:.2}, approaching {}, crosshair {:?}, pos {:?}",
                ctx.tick(),
                self.approaching,
                ctx.target_entity().map(|e| e.id),
                ctx.pose().pos
            );
        }
        if self.approaching {
            ctx.set_controls(Controls {
                forward: true,
                sprint: self.sprint,
                ..Controls::NONE
            });
            if let Some(hit) = ctx.target_entity().filter(|e| e.id == id) {
                let before = ctx.pose().motion;
                let (server, drawn) = ctx
                    .entities()
                    .and_then(|t| t.get(id))
                    .map_or(([0.0; 3], [0.0; 3]), |e| (e.position(), e.drawn_position()));
                let eyes = ctx.eyes(ctx.sent());
                log::info!(
                    "hit test: distance {:.5}, eyes {:.5} {:.5} {:.5}, look {:.4} {:.4}, \
                     target server {:.5?} drawn {:.5?}",
                    hit.distance,
                    eyes.x,
                    eyes.y,
                    eyes.z,
                    ctx.sent().yaw,
                    ctx.sent().pitch,
                    server,
                    drawn
                );
                let sprinting = ctx.pose().sprinting;
                if ctx.attack(id) {
                    self.attacks += 1;
                    if sprinting {
                        self.sprint_attacks += 1;
                    }
                    log::info!(
                        "tick {}: attack {} on {id} at {dist:.2}, sprinting {sprinting}",
                        ctx.tick(),
                        self.attacks
                    );
                    self.after_attack = Some((ctx.tick(), sprinting, before));
                    self.approaching = false;
                    self.state_ticks = 0;
                }
            } else if self.state_ticks > 100 {
                // Stuck (pushed aside): back off and try again.
                self.approaching = false;
                self.state_ticks = 0;
            }
        } else {
            // Back off without sprinting: the target stays in view, the attack cooldown runs out.
            ctx.set_controls(Controls {
                back: true,
                ..Controls::NONE
            });
            if (dist > self.retreat && self.state_ticks >= 12) || self.state_ticks > 60 {
                self.approaching = true;
                self.state_ticks = 0;
            }
        }
    }

    /// The nearest living target of the probe's kind within 16 blocks: id and box.
    fn nearest(&self, ctx: &TickContext<'_>) -> Option<(i32, [f64; 6])> {
        let me = ctx.entity_id();
        let eyes = ctx.eyes(ctx.pose());
        let players = self.players;
        ctx.entities()?
            .within([eyes.x, eyes.y, eyes.z], 16.0)
            .filter(|e| {
                e.id() != me
                    && e.is_player() == players
                    && e.is_alive()
                    && !matches!(
                        e.class(),
                        ghast::entity::EntityClass::Item
                            | ghast::entity::EntityClass::ExperienceOrb
                    )
            })
            .filter_map(|e| Some((e.id(), e.drawn_bounding_box().or(e.bounding_box())?)))
            .min_by(|a, b| {
                let d = |x: &[f64; 6]| {
                    let (cx, cz) = ((x[0] + x[3]) / 2.0 - eyes.x, (x[2] + x[5]) / 2.0 - eyes.z);
                    cx * cx + cz * cz
                };
                d(&a.1).total_cmp(&d(&b.1))
            })
    }

    fn clicks(&mut self, ctx: &mut TickContext<'_>) {
        let Some((id, b)) = self.nearest(ctx) else {
            ctx.set_controls(Controls::NONE);
            return;
        };
        let (yaw, pitch, dist) = Self::look_at(ctx, b);
        // Turning: the aim sweeps around the target's middle.
        let t = self.n as f64;
        ctx.set_aim(
            yaw + (5.0 * (t * 0.15).sin()) as f32,
            pitch + (3.0 * (t * 0.11).cos()) as f32,
        );
        let left = (self.n / 30).is_multiple_of(2);
        ctx.set_controls(Controls {
            left,
            right: !left,
            forward: dist > 3.0,
            back: dist < 2.0,
            ..Controls::NONE
        });
        self.click_budget += self.cps / 20.0;
        while self.click_budget >= 1.0 {
            self.click_budget -= 1.0;
            if ctx.press(ghast::hands::Button::Left) {
                self.presses += 1;
            }
        }
        if self.n.is_multiple_of(100) {
            log::info!(
                "tick {}: target {id} at {dist:.2}, presses {}, attacks sent {}, swings sent {}",
                ctx.tick(),
                self.presses,
                self.sent_attacks,
                self.sent_swings
            );
        }
    }

    fn victim(&mut self, ctx: &mut TickContext<'_>) {
        let phase = (self.n / 20) % 4;
        ctx.set_controls(Controls {
            forward: phase == 0,
            back: phase == 1,
            left: phase == 2,
            right: phase == 3,
            ..Controls::NONE
        });
        let hurt = ctx.last_hurt_tick();
        if hurt.is_some() && hurt != self.last_hurt {
            self.hurts += 1;
            let v = ctx.velocity();
            log::info!(
                "tick {}: hurt {} (health {:?}), velocity {:.4} {:.4} {:.4}",
                ctx.tick(),
                self.hurts,
                ctx.health().health,
                v.x,
                v.y,
                v.z
            );
        }
        self.last_hurt = hurt;
    }

    fn miss(&mut self, ctx: &mut TickContext<'_>) {
        // 160-tick cycle: taps at the sky with growing gaps while walking (ticks 0..100), then
        // one press at the sky held while turning down to the ground (100..140): the miss
        // delay holds the dig back for 10 ticks after the press.
        let phase = self.n % 160;
        ctx.set_controls(Controls {
            forward: phase < 100 && (self.n / 160).is_multiple_of(2),
            back: phase < 100 && (self.n / 160) % 2 == 1,
            ..Controls::NONE
        });
        if phase >= 100 {
            let down = (103..140).contains(&phase);
            ctx.set_aim(ctx.pose().yaw, if down { 89.0 } else { -89.0 });
            let held = (100..140).contains(&phase);
            ctx.set_buttons(Buttons {
                left: held,
                right: false,
            });
            if phase == 100 {
                self.presses += 1;
                self.held_press = Some(ctx.tick());
                log::info!("tick {}: held press at the sky", ctx.tick());
            }
            if let Some(at) = self.held_press
                && ctx.mining().is_some()
            {
                log::info!(
                    "tick {}: dig started {} ticks after the held miss press",
                    ctx.tick(),
                    ctx.tick() - at
                );
                self.held_press = None;
            }
            return;
        }
        ctx.set_aim(ctx.pose().yaw, -89.0);
        let press = self.n >= self.next_press;
        ctx.set_buttons(Buttons {
            left: press,
            right: false,
        });
        if press {
            self.presses += 1;
            let gap = GAPS[self.gap_index % GAPS.len()];
            log::info!(
                "tick {}: press {} (gap {gap}), swings so far {}",
                ctx.tick(),
                self.presses,
                ctx.swings()
            );
            self.gap_index += 1;
            self.next_press = self.n + GAPS[self.gap_index % GAPS.len()];
        }
    }

    fn snapshot(ctx: &TickContext<'_>, slot: u8) -> [Option<i32>; 5] {
        let inv = ctx.inventory();
        let id = |s: Option<&ghast::inventory::Stack>| s.map(|s| s.id());
        [
            id(inv.armor(0)),
            id(inv.armor(1)),
            id(inv.armor(2)),
            id(inv.armor(3)),
            id(inv.hotbar(usize::from(slot))),
        ]
    }

    fn equip(&mut self, ctx: &mut TickContext<'_>) {
        ctx.set_aim(ctx.pose().yaw, -89.0);
        let walk = env("WALK").as_deref() == Some("1");
        ctx.set_controls(Controls {
            forward: walk && (self.n / 60).is_multiple_of(2),
            back: walk && (self.n / 60) % 2 == 1,
            ..Controls::NONE
        });
        let phase = self.n % 30;
        if let Some((at, slot, predicted)) = self.pending_equip {
            if self.n == at + 1 {
                let now = Self::snapshot(ctx, slot);
                log::info!("slot {slot}: predicted after the press {now:?} (before {predicted:?})");
                self.pending_equip = Some((at, slot, now));
            } else if self.n == at + 15 {
                let now = Self::snapshot(ctx, slot);
                if now == predicted {
                    log::info!("slot {slot}: server agrees {now:?}");
                } else {
                    self.corrections += 1;
                    log::warn!("slot {slot}: correction, predicted {predicted:?}, now {now:?}");
                }
                self.pending_equip = None;
            }
        }
        let right = phase == 10 && self.equip_slot < 8;
        if phase == 5 && self.equip_slot < 8 {
            ctx.select_slot(self.equip_slot);
        } else if phase == 5 && self.pending_equip.is_none() {
            // Leave slot 0 selected: the server restores the held slot at the next join.
            ctx.select_slot(0);
        }
        if right {
            let slot = self.equip_slot;
            self.equips += 1;
            log::info!(
                "tick {}: right click with slot {slot} {:?}",
                ctx.tick(),
                Self::snapshot(ctx, slot)
            );
            self.pending_equip = Some((self.n, slot, Self::snapshot(ctx, slot)));
            self.equip_slot += 1;
        }
        ctx.set_buttons(Buttons { left: false, right });
    }

    fn use_item(&mut self, ctx: &mut TickContext<'_>) {
        ctx.set_aim(ctx.pose().yaw, -89.0);
        let cycle = self.hold + 25;
        let phase = self.n % cycle;
        let mut right = (5..5 + self.hold).contains(&phase);
        // A use the held button would restart in the finish tick is ended by the server's
        // stack update a tick later on 1.8 / 1.12: let go for one tick instead.
        if env("RELEASE_ON_FINISH").as_deref() == Some("1") {
            if ctx
                .events()
                .item_use()
                .iter()
                .any(|e| matches!(e, ghast::common::UseEvent::Finished { .. }))
            {
                self.release_ticks = 1;
            }
            if self.release_ticks > 0 {
                right = false;
                self.release_ticks -= 1;
            }
        }
        ctx.set_buttons(Buttons { left: false, right });
        // Walk all the time (the sprint must end while using and start again afterwards).
        ctx.set_controls(Controls {
            forward: env("WALK").as_deref() != Some("0"),
            sprint: self.sprint,
            ..Controls::NONE
        });
        for e in ctx.events().item_use() {
            log::info!("tick {}: {e:?}", ctx.tick());
        }
        if ctx.health().food <= 6 {
            ctx.set_controls(Controls::NONE);
        }
        let using = ctx.using_item();
        if using != self.was_using {
            if using {
                self.uses += 1;
            }
            log::info!(
                "tick {}: using_item {using} (held {:?}, sprinting {}, food {})",
                ctx.tick(),
                ctx.inventory().held().map(|s| (s.id(), s.count())),
                ctx.pose().sprinting,
                ctx.health().food
            );
            self.was_using = using;
        }
    }

    fn inventory(&mut self, ctx: &mut TickContext<'_>) {
        let forward = (self.n / 80).is_multiple_of(2);
        ctx.set_controls(Controls {
            forward,
            back: !forward,
            sprint: forward,
            left: (self.n / 160) % 2 == 1,
            ..Controls::NONE
        });
        // `REPRESS=1`: let go of the keys for one tick after the opening and press them again
        // (1.16.5's own inventory passes the new presses: the bot walks, and clicks, meanwhile).
        if env("REPRESS").as_deref() == Some("1")
            && self.opened_at.is_some_and(|at| self.n == at + 2)
        {
            ctx.set_controls(Controls::NONE);
        }
        if let Some(at) = self.opened_at
            && (self.n == at + 7 || self.n == at + 19)
        {
            log::info!(
                "tick {}: open {} ticks, sprinting {}, motion {:.3} {:.3}",
                ctx.tick(),
                self.n - at,
                ctx.pose().sprinting,
                ctx.pose().motion.x,
                ctx.pose().motion.z
            );
        }
        let phase = self.n % 80;
        match self.opened_at {
            None if (30..40).contains(&phase) => match ctx.open_inventory() {
                Ok(()) => {
                    self.opens += 1;
                    self.opened_at = Some(self.n);
                    log::info!(
                        "tick {}: opened the inventory (sprinting {}, motion {:.3} {:.3})",
                        ctx.tick(),
                        ctx.pose().sprinting,
                        ctx.pose().motion.x,
                        ctx.pose().motion.z
                    );
                }
                Err(e) => {
                    self.refusals += 1;
                    log::info!("open refused: {e}");
                }
            },
            Some(at) if self.n == at + 6 || self.n == at + 8 => {
                match ctx.click(ghast::inventory::Click::Pickup {
                    slot: 9,
                    right: false,
                }) {
                    Ok(_) => self.clicks += 1,
                    Err(e) => {
                        self.refusals += 1;
                        log::info!("click refused: {e}");
                    }
                }
            }
            Some(at) if self.n >= at + 20 => match ctx.close_window() {
                Ok(()) => {
                    self.opened_at = None;
                    log::info!(
                        "tick {}: closed (sprinting {}, motion {:.3} {:.3})",
                        ctx.tick(),
                        ctx.pose().sprinting,
                        ctx.pose().motion.x,
                        ctx.pose().motion.z
                    );
                }
                Err(e) => {
                    self.refusals += 1;
                    log::info!("close refused: {e}");
                }
            },
            _ => {}
        }
    }
}

impl Behavior for Probe {
    fn name(&self) -> &str {
        "combat-probe"
    }

    fn interests(&self) -> Interests {
        match self.mode {
            Mode::Attack | Mode::Clicks => Interests::CHAT | Interests::ENTITIES,
            _ => Interests::CHAT,
        }
    }

    fn after_tick(&mut self, view: &ghast::TickView<'_>) {
        if self.mode != Mode::Clicks {
            return;
        }
        for o in view.outbound() {
            match o {
                ghast::common::Outbound::UseEntity {
                    action: ghast::common::EntityUse::Attack,
                    ..
                } => self.sent_attacks += 1,
                ghast::common::Outbound::Swing | ghast::common::Outbound::Punch => {
                    self.sent_swings += 1;
                }
                _ => {}
            }
        }
    }

    fn start(&mut self, ctx: &mut TickContext<'_>) {
        // The server restores the held slot of the last session; select another slot first so
        // the server surely gets slot 0 (a select of 0 right after the server's slot change is
        // not sent yet, see the lab-legacy report).
        ctx.select_slot(1);
        ctx.select_slot(0);
    }

    fn tick(&mut self, ctx: &mut TickContext<'_>) {
        for m in &ctx.events().chat {
            let t = m.plain();
            if t.contains("Grim") || t.contains("failed") {
                self.alerts += 1;
                log::warn!("ALERT chat: {t}");
            }
        }
        if ctx.events().teleported && self.n > 120 {
            self.setbacks += 1;
            log::warn!("ALERT setback at tick {}", ctx.tick());
        }
        if self.limit.is_some_and(|l| self.started.elapsed() >= l) {
            log::info!("{}", self.summary());
            ctx.disconnect("time limit reached");
            return;
        }
        if ctx.is_dead() {
            ctx.respawn();
            return;
        }
        self.n += 1;
        // Settle after the join (and the script's teleport) first.
        if self.n < 120 {
            return;
        }
        match self.mode {
            Mode::Attack => self.attack(ctx),
            Mode::Victim => self.victim(ctx),
            Mode::Miss => self.miss(ctx),
            Mode::Equip => self.equip(ctx),
            Mode::Use => self.use_item(ctx),
            Mode::Inventory => self.inventory(ctx),
            Mode::Clicks => self.clicks(ctx),
        }
    }
}

fn main() {
    let opts = support::Options::parse();
    support::init_logger(opts.verbose);
    let rt = tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .expect("tokio runtime");
    rt.block_on(async {
        let client = match opts.client() {
            Ok(c) => c,
            Err(e) => {
                log::error!("{e}");
                std::process::exit(2);
            }
        };
        let mut b = Probe::new(opts.limit());
        let shutdown = async {
            let _ = tokio::signal::ctrl_c().await;
        };
        match client.run_until(&mut b, shutdown).await {
            Ok(e) => log::info!("session ended: {e:?}; {}", b.summary()),
            Err(e) => log::error!("session failed: {e}"),
        }
    });
}