bevy-agent-feedback-plugin 0.2.4

Bevy plugin for Pi/Codex-driven input and screenshot feedback.
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
//! Rust client for the v2 agent feedback protocol.

use crate::session::{PROTOCOL_VERSION, unix_ms};
use serde::Deserialize;
use serde_json::{Value, json};
use std::{
    error::Error,
    fmt::{self, Display, Formatter},
    fs::{self, File, OpenOptions},
    io::{self, BufRead, BufReader, Write},
    net::{SocketAddr, TcpStream},
    path::{Path, PathBuf},
    time::{Duration, Instant},
};

/// Client configuration.
#[derive(Clone, Debug)]
pub struct AgentClientConfig {
    /// Protocol file written by the Bevy plugin.
    pub protocol_file: PathBuf,
    /// TCP connect/read/write timeout.
    pub timeout: Duration,
    /// Optional replayable transcript path.
    pub transcript_file: Option<PathBuf>,
    /// OCR settings used by `ocr_*` and text assertions.
    pub ocr: OcrOptions,
}

impl Default for AgentClientConfig {
    fn default() -> Self {
        Self {
            protocol_file: std::env::var_os("BEVY_FEEDBACK_PROTOCOL")
                .map(PathBuf::from)
                .unwrap_or_else(|| PathBuf::from("target/agent-feedback/agent-feedback.json")),
            timeout: Duration::from_secs(10),
            transcript_file: std::env::var_os("BEVY_FEEDBACK_TRANSCRIPT").map(PathBuf::from),
            ocr: OcrOptions::default(),
        }
    }
}

/// Tesseract OCR settings.
#[derive(Clone, Debug)]
pub struct OcrOptions {
    /// Path to the `tesseract` executable.
    pub tesseract: PathBuf,
    /// Tesseract language code, for example `eng`.
    pub language: String,
    /// OCR subprocess timeout.
    pub timeout: Duration,
}

impl Default for OcrOptions {
    fn default() -> Self {
        Self {
            tesseract: std::env::var_os("BEVY_FEEDBACK_TESSERACT")
                .map(PathBuf::from)
                .unwrap_or_else(|| PathBuf::from("tesseract")),
            language: "eng".to_string(),
            timeout: Duration::from_secs(5),
        }
    }
}

/// A captured PNG returned by the plugin.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Capture {
    /// Monotonic capture sequence number.
    pub sequence: u64,
    /// PNG path on disk.
    pub path: PathBuf,
}

/// Pixel-space rectangle used by image assertions.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Region {
    /// Left coordinate in pixels.
    pub x: u32,
    /// Top coordinate in pixels.
    pub y: u32,
    /// Width in pixels.
    pub width: u32,
    /// Height in pixels.
    pub height: u32,
}

/// Rust client for the local JSON-lines control socket.
pub struct AgentClient {
    stream: TcpStream,
    reader: BufReader<TcpStream>,
    next_id: u64,
    timeout: Duration,
    transcript: Option<File>,
    last_capture: Option<PathBuf>,
    ocr: OcrOptions,
}

/// Client failure.
#[derive(Debug)]
pub enum ClientError {
    /// Filesystem, socket, or subprocess I/O failed.
    Io(String),
    /// JSON parsing or formatting failed.
    Json(String),
    /// Protocol discovery failed before connecting.
    Protocol(String),
    /// The game returned an error response.
    Command {
        /// Protocol error code.
        code: String,
        /// Human-readable error message.
        message: String,
    },
    /// OCR is not available or the requested language is missing.
    OcrUnavailable(String),
    /// OCR ran but failed unexpectedly.
    Ocr(String),
    /// Visual/text assertion failed.
    Assertion(String),
}

impl Display for ClientError {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
        match self {
            Self::Io(message)
            | Self::Json(message)
            | Self::Protocol(message)
            | Self::OcrUnavailable(message)
            | Self::Ocr(message)
            | Self::Assertion(message) => formatter.write_str(message),
            Self::Command { code, message } => {
                write!(formatter, "command failed [{code}]: {message}")
            }
        }
    }
}

impl Error for ClientError {}

impl From<io::Error> for ClientError {
    fn from(error: io::Error) -> Self {
        Self::Io(error.to_string())
    }
}

impl From<serde_json::Error> for ClientError {
    fn from(error: serde_json::Error) -> Self {
        Self::Json(error.to_string())
    }
}

impl AgentClient {
    /// Connects using a protocol file path.
    pub fn connect(protocol_file: impl AsRef<Path>) -> Result<Self, ClientError> {
        Self::with_config(AgentClientConfig {
            protocol_file: protocol_file.as_ref().to_path_buf(),
            ..Default::default()
        })
    }

    /// Connects using explicit configuration.
    pub fn with_config(config: AgentClientConfig) -> Result<Self, ClientError> {
        let protocol = read_protocol(&config.protocol_file)?;
        let stream = TcpStream::connect_timeout(&protocol.socket_addr, config.timeout)
            .map_err(|error| socket_error(error, &protocol.socket_addr))?;
        stream.set_read_timeout(Some(config.timeout))?;
        stream.set_write_timeout(Some(config.timeout))?;
        let reader = BufReader::new(stream.try_clone()?);
        let transcript = match &config.transcript_file {
            Some(path) => {
                if let Some(parent) = path.parent()
                    && !parent.as_os_str().is_empty()
                {
                    fs::create_dir_all(parent)?;
                }
                Some(OpenOptions::new().create(true).append(true).open(path)?)
            }
            None => None,
        };
        Ok(Self {
            stream,
            reader,
            next_id: 1,
            timeout: config.timeout,
            transcript,
            last_capture: None,
            ocr: config.ocr,
        })
    }

    /// Sends a raw JSON request and returns the raw JSON response.
    pub fn request(&mut self, mut request: Value) -> Result<Value, ClientError> {
        let Some(object) = request.as_object_mut() else {
            return Err(ClientError::Protocol(
                "request must be a JSON object".to_string(),
            ));
        };
        object
            .entry("id".to_string())
            .or_insert_with(|| Value::from(self.next_id));
        self.next_id = self.next_id.saturating_add(1);

        let line = serde_json::to_string(&request)?;
        let ts_ms = u64::try_from(unix_ms()).unwrap_or(u64::MAX);
        let start = Instant::now();
        writeln!(self.stream, "{line}")?;
        self.stream.flush()?;

        let mut response = String::new();
        if let Err(error) = self.reader.read_line(&mut response) {
            return Err(self.read_error(error));
        }
        if response.is_empty() {
            return Err(ClientError::Io(
                "agent socket closed before response".to_string(),
            ));
        }
        let response: Value = serde_json::from_str(&response)?;
        if let Some(transcript) = &mut self.transcript {
            serde_json::to_writer(
                &mut *transcript,
                &json!({
                    "ts_ms": ts_ms,
                    "duration_ms": u64::try_from(start.elapsed().as_millis()).unwrap_or(u64::MAX),
                    "request": request,
                    "response": response,
                }),
            )?;
            writeln!(transcript)?;
            transcript.flush()?;
        }
        if response["ok"] == Value::Bool(true) {
            return Ok(response);
        }
        let code = response["error"]["code"]
            .as_str()
            .unwrap_or("command_failed")
            .to_string();
        let mut message = response["error"]["message"]
            .as_str()
            .unwrap_or("game returned an error")
            .to_string();
        if code == "timeout" {
            message = self.with_last_capture(message);
        }
        Err(ClientError::Command { code, message })
    }

    /// Replays request-only or transcript-envelope JSON-lines from disk.
    pub fn replay_jsonl(&mut self, path: impl AsRef<Path>) -> Result<Vec<Value>, ClientError> {
        let file = File::open(path)?;
        let lines = BufReader::new(file)
            .lines()
            .collect::<Result<Vec<_>, _>>()?;
        let mut responses = Vec::new();
        for line in lines {
            if line.trim().is_empty() {
                continue;
            }
            let value: Value = serde_json::from_str(&line)?;
            let request = value.get("request").cloned().unwrap_or(value);
            responses.push(self.request(request)?);
        }
        Ok(responses)
    }

    /// Queries primary-window metadata.
    pub fn window_info(&mut self) -> Result<Value, ClientError> {
        self.request(json!({"command": "window_info"}))
    }

    /// Captures the primary window as a PNG.
    pub fn capture(&mut self) -> Result<Capture, ClientError> {
        let response = self.request(json!({"command": "capture"}))?;
        let capture = capture_from_response(&response)?;
        self.last_capture = Some(capture.path.clone());
        Ok(capture)
    }

    /// Waits for `frames` Bevy frames.
    pub fn wait(&mut self, frames: u16) -> Result<Value, ClientError> {
        self.request(json!({"command": "wait", "frames": frames}))
    }

    /// Moves the cursor in logical window coordinates.
    pub fn cursor_move(&mut self, x: f32, y: f32) -> Result<Value, ClientError> {
        self.request(json!({"command": "cursor_move", "x": x, "y": y}))
    }

    /// Presses a physical key code.
    pub fn key_down(&mut self, key: &str) -> Result<Value, ClientError> {
        self.request(json!({"command": "key_down", "key": key}))
    }

    /// Releases a physical key code.
    pub fn key_up(&mut self, key: &str) -> Result<Value, ClientError> {
        self.request(json!({"command": "key_up", "key": key}))
    }

    /// Presses a mouse button.
    pub fn mouse_down(&mut self, button: &str) -> Result<Value, ClientError> {
        self.request(json!({"command": "mouse_down", "button": button}))
    }

    /// Releases a mouse button.
    pub fn mouse_up(&mut self, button: &str) -> Result<Value, ClientError> {
        self.request(json!({"command": "mouse_up", "button": button}))
    }

    /// Scrolls by line units.
    pub fn scroll(&mut self, lines: f32) -> Result<Value, ClientError> {
        self.request(json!({"command": "scroll", "lines": lines}))
    }

    /// Clicks at logical window coordinates.
    pub fn click(&mut self, x: f32, y: f32, button: &str) -> Result<Value, ClientError> {
        self.request(json!({"command": "click", "x": x, "y": y, "button": button}))
    }

    /// Drags between logical window coordinates.
    pub fn drag(
        &mut self,
        button: &str,
        from: [f32; 2],
        to: [f32; 2],
        steps: u16,
        frames: u16,
    ) -> Result<Value, ClientError> {
        self.request(json!({
            "command": "drag",
            "button": button,
            "from": from,
            "to": to,
            "steps": steps,
            "frames": frames,
        }))
    }

    /// Taps a key for one frame.
    pub fn key_tap(&mut self, key: &str) -> Result<Value, ClientError> {
        self.request(json!({"command": "key_tap", "key": key}))
    }

    /// Holds a key for `frames` frames, then releases it.
    pub fn key_hold(&mut self, key: &str, frames: u16) -> Result<Value, ClientError> {
        self.request(json!({"command": "key_hold", "key": key, "frames": frames}))
    }

    /// Releases every input held by this agent session.
    pub fn release_all_inputs(&mut self) -> Result<Value, ClientError> {
        self.request(json!({"command": "release_all_inputs"}))
    }

    /// Asks the Bevy app to exit cleanly.
    pub fn shutdown(&mut self) -> Result<Value, ClientError> {
        self.request(json!({"command": "shutdown"}))
    }

    fn read_error(&self, error: io::Error) -> ClientError {
        if error.kind() == io::ErrorKind::TimedOut || error.kind() == io::ErrorKind::WouldBlock {
            ClientError::Io(self.with_last_capture(format!(
                "agent request timed out after {} ms",
                self.timeout.as_millis()
            )))
        } else {
            ClientError::Io(error.to_string())
        }
    }

    fn with_last_capture(&self, message: String) -> String {
        match &self.last_capture {
            Some(path) => format!("{message}; last captured frame: {}", path.display()),
            None => message,
        }
    }

    /// Counts differing pixels across two equally-sized images.
    pub fn pixel_diff(a: impl AsRef<Path>, b: impl AsRef<Path>) -> Result<u64, ClientError> {
        let a = image::ImageReader::open(a)?.decode().map_err(image_error)?;
        let b = image::ImageReader::open(b)?.decode().map_err(image_error)?;
        diff_images(&a, &b, None)
    }

    /// Counts differing pixels inside a region across two equally-sized images.
    pub fn region_diff(
        a: impl AsRef<Path>,
        b: impl AsRef<Path>,
        region: Region,
    ) -> Result<u64, ClientError> {
        let a = image::ImageReader::open(a)?.decode().map_err(image_error)?;
        let b = image::ImageReader::open(b)?.decode().map_err(image_error)?;
        diff_images(&a, &b, Some(region))
    }

    /// Asserts that two screenshots differ by at least `min_pixels`.
    pub fn assert_changed(
        a: impl AsRef<Path>,
        b: impl AsRef<Path>,
        min_pixels: u64,
    ) -> Result<(), ClientError> {
        let changed = Self::pixel_diff(&a, &b)?;
        if changed >= min_pixels {
            return Ok(());
        }
        Err(ClientError::Assertion(format!(
            "screenshots changed {changed} pixels, expected at least {min_pixels}: {} and {}",
            a.as_ref().display(),
            b.as_ref().display()
        )))
    }

    /// Asserts that two screenshots differ by at least `min_pixels` inside `region`.
    pub fn assert_region_changed(
        a: impl AsRef<Path>,
        b: impl AsRef<Path>,
        region: Region,
        min_pixels: u64,
    ) -> Result<(), ClientError> {
        let changed = Self::region_diff(&a, &b, region)?;
        if changed >= min_pixels {
            return Ok(());
        }
        Err(ClientError::Assertion(format!(
            "region {:?} changed {changed} pixels, expected at least {min_pixels}: {} and {}",
            region,
            a.as_ref().display(),
            b.as_ref().display()
        )))
    }

    /// Asserts that a color appears at least `min_pixels` times.
    pub fn assert_color_present(
        path: impl AsRef<Path>,
        color: [u8; 3],
        region: Option<Region>,
        tolerance: u8,
        min_pixels: u64,
    ) -> Result<(), ClientError> {
        let found = color_pixel_count(path.as_ref(), color, region, tolerance)?;
        if found >= min_pixels {
            return Ok(());
        }
        Err(ClientError::Assertion(format!(
            "color {:?} found {found} pixels, expected at least {min_pixels}: {}",
            color,
            path.as_ref().display()
        )))
    }

    /// Captures until the screenshot differs from `before`.
    pub fn wait_until_changed(
        &mut self,
        before: impl AsRef<Path>,
        frames_per_poll: u16,
        attempts: u16,
    ) -> Result<Capture, ClientError> {
        for _ in 0..attempts {
            self.wait(frames_per_poll)?;
            let capture = self.capture()?;
            if Self::pixel_diff(before.as_ref(), &capture.path)? > 0 {
                return Ok(capture);
            }
        }
        Err(ClientError::Assertion(
            "screenshot did not change".to_string(),
        ))
    }

    /// Captures until a color appears in a pixel region.
    pub fn wait_until_color(
        &mut self,
        color: [u8; 3],
        region: Region,
        tolerance: u8,
        frames_per_poll: u16,
        attempts: u16,
    ) -> Result<Capture, ClientError> {
        for _ in 0..attempts {
            self.wait(frames_per_poll)?;
            let capture = self.capture()?;
            if image_has_color(&capture.path, color, region, tolerance)? {
                return Ok(capture);
            }
        }
        Err(ClientError::Assertion("color did not appear".to_string()))
    }

    /// Runs Tesseract OCR on an image.
    pub fn ocr_image(&self, path: impl AsRef<Path>) -> Result<String, ClientError> {
        run_tesseract(&self.ocr, path.as_ref())
    }

    /// Crops a region and runs Tesseract OCR on it.
    pub fn ocr_region(
        &self,
        path: impl AsRef<Path>,
        region: Region,
    ) -> Result<String, ClientError> {
        let image = image::ImageReader::open(path)?
            .decode()
            .map_err(image_error)?;
        validate_region(&image, region)?;
        let cropped = image.crop_imm(region.x, region.y, region.width, region.height);
        let temp = std::env::temp_dir().join(format!(
            "bevy-feedback-ocr-{}-{}.png",
            std::process::id(),
            unix_ms()
        ));
        cropped.save(&temp).map_err(image_error)?;
        let result = self.ocr_image(&temp);
        let _ = fs::remove_file(temp);
        result
    }

    /// Asserts that OCR output contains `expected`.
    pub fn assert_text(&self, path: impl AsRef<Path>, expected: &str) -> Result<(), ClientError> {
        let text = normalize_text(&self.ocr_image(path)?);
        let expected = normalize_text(expected);
        if text.contains(&expected) {
            Ok(())
        } else {
            Err(ClientError::Assertion(format!(
                "OCR text did not contain '{expected}': {text}"
            )))
        }
    }

    /// Captures until OCR output contains `expected`.
    pub fn wait_until_text(
        &mut self,
        expected: &str,
        frames_per_poll: u16,
        attempts: u16,
    ) -> Result<Capture, ClientError> {
        for _ in 0..attempts {
            self.wait(frames_per_poll)?;
            let capture = self.capture()?;
            match self.assert_text(&capture.path, expected) {
                Ok(()) => return Ok(capture),
                Err(ClientError::Assertion(_)) => {}
                Err(error) => return Err(error),
            }
        }
        Err(ClientError::Assertion(format!(
            "text '{expected}' did not appear"
        )))
    }
}

impl Drop for AgentClient {
    fn drop(&mut self) {
        let _ = writeln!(
            self.stream,
            "{}",
            json!({"id": self.next_id, "command": "release_all_inputs"})
        );
        let _ = self.stream.flush();
    }
}

#[derive(Debug, Deserialize)]
struct ProtocolFile {
    socket_addr: SocketAddr,
    pid: u32,
    heartbeat_file: PathBuf,
    stale_after_ms: u64,
}

fn read_protocol(path: &Path) -> Result<ProtocolFile, ClientError> {
    let bytes = fs::read(path).map_err(|error| {
        ClientError::Protocol(format!(
            "failed to read protocol file {}: {error}",
            path.display()
        ))
    })?;
    let value: Value = serde_json::from_slice(&bytes)?;
    let Some(version) = value["protocol"].as_str() else {
        return Err(ClientError::Protocol(format!(
            "unknown protocol file {}; missing protocol, expected {PROTOCOL_VERSION}",
            path.display()
        )));
    };
    if version != PROTOCOL_VERSION {
        return Err(ClientError::Protocol(format!(
            "unsupported protocol '{version}'; expected {PROTOCOL_VERSION}"
        )));
    }
    let protocol: ProtocolFile = serde_json::from_value(value)?;
    if !process_alive(protocol.pid) {
        return Err(ClientError::Protocol(format!(
            "protocol stale: process {} is not alive",
            protocol.pid
        )));
    }
    let heartbeat = fs::read_to_string(&protocol.heartbeat_file).map_err(|error| {
        ClientError::Protocol(format!(
            "protocol stale: failed to read heartbeat {}: {error}",
            protocol.heartbeat_file.display()
        ))
    })?;
    let heartbeat_ms = heartbeat.trim().parse::<u128>().map_err(|error| {
        ClientError::Protocol(format!("protocol stale: heartbeat is invalid: {error}"))
    })?;
    let age = unix_ms().saturating_sub(heartbeat_ms);
    if age > u128::from(protocol.stale_after_ms) {
        return Err(ClientError::Protocol(format!(
            "protocol stale: heartbeat is {age} ms old, stale after {} ms",
            protocol.stale_after_ms
        )));
    }
    Ok(protocol)
}

fn socket_error(error: io::Error, socket_addr: &SocketAddr) -> ClientError {
    if error.kind() == io::ErrorKind::ConnectionRefused {
        ClientError::Protocol(format!(
            "socket refused at {socket_addr}; game probably exited"
        ))
    } else {
        ClientError::Io(format!("connect {socket_addr}: {error}"))
    }
}

fn capture_from_response(response: &Value) -> Result<Capture, ClientError> {
    let capture = &response["result"]["capture"];
    let sequence = capture["sequence"].as_u64().ok_or_else(|| {
        ClientError::Protocol(format!("capture response missing sequence: {response}"))
    })?;
    let path = capture["path"].as_str().ok_or_else(|| {
        ClientError::Protocol(format!("capture response missing path: {response}"))
    })?;
    Ok(Capture {
        sequence,
        path: PathBuf::from(path),
    })
}

mod image_assertions;
use image_assertions::{
    color_pixel_count, diff_images, image_error, image_has_color, normalize_text, run_tesseract,
    validate_region,
};

fn process_alive(pid: u32) -> bool {
    if pid == 0 {
        return false;
    }
    #[cfg(target_os = "linux")]
    {
        Path::new("/proc").join(pid.to_string()).exists()
    }
    #[cfg(not(target_os = "linux"))]
    {
        true
    }
}

#[cfg(test)]
mod tests;