Skip to main content

agentmux_srv/server/
browser_capture_shape.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! How many shaped captures an agent may make (#47629).
5//!
6//! `Browser` `capture` can be told what the value should look like (`agentmux_common::capture_shape`: a
7//! short prefix, one of a closed list of named shapes, a length range), and nothing is saved if it is not.
8//! The answer to that, saved or not, is a yes or no about a value the agent cannot read, so it is budgeted
9//! like any other question about one:
10//!
11//! - an agent may make [`SHAPED`] captures with a shape in an hour, whether they match or not (a match is
12//!   as much an answer as a miss), all its panes together: opening another pane starts nothing new;
13//! - at most [`MISSES`] of them may fail; the next one that does ends shapes for the agent for an hour, and
14//!   the answer says so. A capture that fails because the host found no value to test counts as a miss too:
15//!   that is the same answer.
16//!
17//! A capture with no shape is not budgeted: it never answers about the value.
18
19use std::collections::HashMap;
20use std::sync::{Mutex, OnceLock};
21use std::time::{Duration, Instant};
22
23/// Shaped captures an agent may make, and how many may miss, in [`WINDOW`].
24const SHAPED: usize = 10;
25const MISSES: usize = 3;
26const WINDOW: Duration = Duration::from_secs(60 * 60);
27
28#[derive(Default)]
29struct Agent {
30    shaped: Vec<Instant>,
31    misses: Vec<Instant>,
32    /// Shapes are refused until then.
33    locked_until: Option<Instant>,
34}
35
36/// What each agent has used, by agent.
37#[derive(Default)]
38pub(super) struct Ledger(HashMap<String, Agent>);
39
40impl Ledger {
41    /// Take one shaped capture from `agent`'s budget at `now`, or say why it may not make one.
42    fn start(&mut self, agent: &str, now: Instant) -> Result<(), String> {
43        let a = self.0.entry(agent.to_string()).or_default();
44        a.shaped.retain(|t| now.duration_since(*t) < WINDOW);
45        a.misses.retain(|t| now.duration_since(*t) < WINDOW);
46        if let Some(until) = a.locked_until.filter(|u| *u > now) {
47            return Err(format!("{}: shapes are refused for you for another {} minutes. Capture without a shape, or ask the person", LOCKED, (until - now).as_secs() / 60 + 1));
48        }
49        a.locked_until = None;
50        if a.shaped.len() >= SHAPED {
51            return Err(format!("{SHAPED} captures with a shape in the last hour: a shape is for choosing between values, not for testing what one says. Capture without a shape, or ask the person"));
52        }
53        a.shaped.push(now);
54        Ok(())
55    }
56
57    /// Note a shaped capture that did not match; true when it was one too many, and shapes are refused for an hour.
58    fn miss(&mut self, agent: &str, now: Instant) -> bool {
59        let a = self.0.entry(agent.to_string()).or_default();
60        a.misses.retain(|t| now.duration_since(*t) < WINDOW);
61        a.misses.push(now);
62        if a.misses.len() > MISSES {
63            a.locked_until = Some(now + WINDOW);
64            return true;
65        }
66        false
67    }
68}
69
70const LOCKED: &str = "too many captures with a shape did not match";
71
72fn ledger() -> &'static Mutex<Ledger> {
73    static LEDGER: OnceLock<Mutex<Ledger>> = OnceLock::new();
74    LEDGER.get_or_init(Mutex::default)
75}
76
77/// Take one shaped capture from the agent's budget.
78pub(super) fn start(agent: &str) -> Result<(), String> {
79    ledger().lock().unwrap_or_else(|p| p.into_inner()).start(&agent.to_lowercase(), Instant::now())
80}
81
82/// Note that a shaped capture did not match (or found nothing to test); the words to add to the answer when
83/// shapes are now refused for an hour.
84pub(super) fn miss(agent: &str) -> &'static str {
85    if ledger().lock().unwrap_or_else(|p| p.into_inner()).miss(&agent.to_lowercase(), Instant::now()) {
86        " That was one miss too many: shapes are refused for you for an hour."
87    } else {
88        ""
89    }
90}
91
92#[cfg(test)]
93#[path = "browser_capture_shape_tests.rs"]
94mod tests;