Skip to main content

agentmux_srv_core/backend/vault/
uses.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! An agent's use of a Vault entry, waiting for the person to allow it
5//! (docs/specs/SPEC_VAULT_PANE_AGENTS_USE_SECRETS_UNSEEN_2026_10_19.md §6.4).
6//!
7//! The agent asks (`Browser` `fill` with `vault`); every window shows the person
8//! the entry, the site and the field; their answer reaches srv only through the
9//! host's Vault route. An agent can ask; it can never answer.
10//!
11//! srv keeps each request's deadline
12//! (SPEC_VAULT_REQUESTS_AS_CARDS_IN_THE_AGENT_PANE_2026_11_01.md §5): a use of an
13//! API key, login or note goes ahead once if nobody answers in [`VETO`]; any
14//! other entry, and a value the person must type, waits for a yes until the
15//! request's own wait runs out, and is then denied. The person's activity in the
16//! request holds its countdown ([`Uses::hold`]).
17
18use std::sync::{Mutex, OnceLock};
19use std::time::Duration;
20
21use serde::Serialize;
22use tokio::sync::oneshot;
23
24#[derive(Debug, Clone, Default, PartialEq, Serialize, ts_rs::TS)]
25#[ts(export, export_to = "../../../frontend/types/rpc/")]
26pub struct UseRequest {
27    pub id: String,
28    /// The agent, as its verified identity names it.
29    pub agent: String,
30    /// The asking agent's own pane, where the person answers it; empty when it
31    /// has none.
32    pub block_id: String,
33    pub entry_id: String,
34    pub entry_label: String,
35    /// What is being filled: "Card number", "Social Security number".
36    pub what: String,
37    /// The site the field is on (its frame's origin).
38    pub origin: String,
39    /// The page's own origin, when the field is in another site's frame (a payment provider's hosted field): the question
40    /// is then about that frame on that page, and "Always" is for the pair. Empty for a field of the page itself.
41    pub page: String,
42    /// The field, as a person reads it.
43    pub field: String,
44    /// Whether "Always on this site" is offered: only when the field looks like
45    /// what the entry is.
46    pub offer_always: bool,
47    /// Why the person is being asked: it is a new site, or the field doesn't look
48    /// like what the entry is.
49    pub reason: String,
50    /// The agent's own reason for asking, one line of at most 300 characters; shown as "<agent> says: ...",
51    /// never used to decide anything. Empty for a use no agent asked for.
52    pub agent_reason: String,
53    /// There is no entry yet: the person types the value in the prompt, and may
54    /// keep it in the Vault (spec section 6.5).
55    pub needs_value: bool,
56    /// The kind of entry that would be kept, when `needs_value`.
57    pub kind: String,
58    /// A command the agent runs with the value in its environment (spec section 7.3);
59    /// empty for a web form. `origin` and `field` are then empty too.
60    pub command: String,
61    /// The command's working directory, when `command` is set.
62    pub cwd: String,
63    /// What `command` prints replaces the entry's value (`capture`); nothing is
64    /// given to the command.
65    pub replaces: bool,
66    /// An agent's sign-in with a saved `login` (`Browser` `signin`): `field` is
67    /// then the masked user name, and "Always" is for this agent on this site.
68    pub signin: bool,
69    /// With `signin`: the login belongs to another profile and the person shared it with this agent, which uses it in
70    /// its own profile. Not sent to the pane: only srv reads it, to answer a card whose share was removed.
71    #[serde(skip)]
72    #[ts(skip)]
73    pub shared: bool,
74    /// An agent asks the person to share a login with it (`Vault` `share`): `origin` is the login's site and `field`
75    /// its user name as the card shows it. Never goes ahead on silence, and offers "Always" only with `prompt`.
76    pub share: bool,
77    /// With `share`: the login answers a site's HTTP prompt or a proxy's, which the browser answers itself in the
78    /// agent's own profile. "Always" then means the browser answers it there without asking again.
79    #[serde(skip_serializing_if = "Option::is_none")]
80    #[ts(optional)]
81    pub prompt: Option<UseHttpPrompt>,
82    /// An agent's new account on a sign-up form (`Browser` `generate_password`): the
83    /// Vault makes the password. There is no entry yet; `origin` is the site.
84    pub account: bool,
85    /// With `account`: the form changes the password of an account that already exists (a
86    /// `current-password` field, §7.3), so the Vault keeps the old one and the question has no "Always".
87    pub change: bool,
88    #[ts(type = "number")]
89    pub requested_ms: u64,
90    /// When silence decides: it goes ahead then if `goes_ahead`, else it is
91    /// denied. Set by [`Uses::ask`]; a hold moves it.
92    #[ts(type = "number")]
93    pub deadline_ms: u64,
94    /// The latest a hold can move `deadline_ms` to: the request's own wait.
95    #[ts(type = "number")]
96    pub expires_ms: u64,
97    /// Nobody answering lets it go ahead, once.
98    pub goes_ahead: bool,
99    /// The agent that set the entry's value, when an agent had the Vault read it (an import or a capture) and the person has
100    /// not seen it yet (`agent_set`); empty for any other use. Such a use never goes ahead on silence, offers no *Always*, and
101    /// the card says who set the value and when.
102    pub set_by: String,
103    /// When `set_by` set it, in ms.
104    #[ts(type = "number")]
105    pub set_ms: u64,
106    /// What `set_by` set: `value`, `site` or `value and site` (a site, realm or proxy an agent chose for a login).
107    pub set_what: String,
108    /// A secret an agent wants copied into the Vault from another service (`Vault` `import`); never goes ahead on silence.
109    #[serde(skip_serializing_if = "Option::is_none")]
110    #[ts(optional)]
111    pub import: Option<UseImport>,
112    /// The cards the person may pick from, when the agent named none or named one the person may swap
113    /// (`Browser` `fill` of a whole card): none for any other use. `entry_id` is the one preselected, if any.
114    #[serde(skip_serializing_if = "Option::is_none")]
115    #[ts(optional)]
116    pub choices: Option<Vec<UseChoice>>,
117}
118
119/// The HTTP prompt a shared sign-in answers, as the person reads it: the realm the site names (empty when it names
120/// none) and whether the prompt is a proxy's.
121#[derive(Debug, Clone, Default, PartialEq, Serialize, ts_rs::TS)]
122#[ts(export, export_to = "../../../frontend/types/rpc/")]
123pub struct UseHttpPrompt {
124    pub realm: String,
125    pub proxy: bool,
126}
127
128/// One card of a picker: what the person reads of it, never a number.
129#[derive(Debug, Clone, Default, PartialEq, Serialize, ts_rs::TS)]
130#[ts(export, export_to = "../../../frontend/types/rpc/")]
131pub struct UseChoice {
132    /// The entry's id.
133    pub id: String,
134    pub label: String,
135    /// "Visa •••• 4242, expires 03/27", or "…, expired 03/2026".
136    pub detail: String,
137    /// Past its month: "Always" is never offered for it.
138    pub expired: bool,
139    /// The person's default card.
140    pub default: bool,
141}
142
143/// What an import copies, as the person reads it: where from, and where to. Nothing of the value.
144#[derive(Debug, Clone, Default, PartialEq, Serialize, ts_rs::TS)]
145#[ts(export, export_to = "../../../frontend/types/rpc/")]
146pub struct UseImport {
147    /// The service the secret is read from, e.g. "AWS Secrets Manager".
148    pub service: String,
149    pub secret: String,
150    /// The field of a JSON secret, when one is picked; empty for the whole secret.
151    pub key: String,
152    pub region: String,
153    /// What the read runs under: an AWS grant (a container agent) or a profile on this computer (a native one); empty
154    /// for this computer's default login.
155    pub profile: String,
156    /// `profile` is a grant AgentMux mints a session for, not a profile on this computer.
157    pub grant: bool,
158    /// The Vault it goes into.
159    pub vault: String,
160    /// It replaces the value of the entry (`entry_id`), the old one kept as a version.
161    pub replaces: bool,
162    /// A new login's user name is read from this field of the same secret; empty when the import makes no login.
163    pub user_key: String,
164    /// The site the new login is saved for; empty for none.
165    pub site: String,
166    /// The agent asked for the new login to be shared with it: the card says so, with a tick the person can remove.
167    pub share: bool,
168}
169
170/// How long a use that may go ahead on silence waits for a Deny.
171pub const VETO: Duration = Duration::from_secs(30);
172/// How long the person's last activity in a request holds its countdown.
173pub const HOLD: Duration = Duration::from_secs(15);
174
175/// Whether a use of a `kind` entry goes ahead when nobody answers: an API
176/// key, a login or a note does; an ID, a card or a bank account never does,
177/// nor does a value only the person can type.
178pub fn goes_ahead_on_silence(kind: &str, needs_value: bool) -> bool {
179    !needs_value && matches!(kind, "api-key" | "login" | "note")
180}
181
182/// What a drone's actor starts with: `drone:<id>`. A drone is not an agent a person is watching.
183pub const DRONE_ACTOR: &str = "drone:";
184
185/// Whether `req` goes ahead when nobody answers: [`goes_ahead_on_silence`], and never a copy of a secret from elsewhere
186/// nor a new account (an agent makes one only on the person's yes), nor a
187/// value an agent had the Vault read that the person has not seen, nor a drone's use: the 30 s rule assumes the person is at the desk while an agent works, and a drone often runs
188/// unattended (at night, on a webhook), so for it silence is a no.
189pub fn goes_ahead(req: &UseRequest) -> bool {
190    req.import.is_none()
191        && !req.account
192        && !req.share
193        && req.set_by.is_empty()
194        && !req.agent.starts_with(DRONE_ACTOR)
195        && goes_ahead_on_silence(&req.kind, req.needs_value)
196}
197
198#[derive(Debug, Clone, Copy, PartialEq, Eq)]
199pub enum Decision {
200    Once,
201    Always,
202    Deny,
203}
204
205impl Decision {
206    pub fn parse(s: &str) -> Option<Self> {
207        match s {
208            "once" => Some(Self::Once),
209            "always" => Some(Self::Always),
210            "deny" => Some(Self::Deny),
211            _ => None,
212        }
213    }
214}
215
216/// Who decided a request.
217#[derive(Debug, Clone, Copy, PartialEq, Eq)]
218pub enum By {
219    Person,
220    /// Nobody answered by its deadline.
221    Silence,
222    /// Too many of this agent's requests waited, and this was the oldest.
223    Crowded,
224}
225
226/// What the person answered. `value` is what they typed when the entry didn't
227/// exist; it lives only as long as the fill does.
228pub struct UseAnswer {
229    pub decision: Decision,
230    pub value: Option<zeroize::Zeroizing<String>>,
231    /// Keep the typed value in the Vault.
232    pub save: bool,
233    pub by: By,
234    /// The card the person picked (an entry id from the request's `choices`), for a whole-card fill.
235    pub choice: Option<String>,
236    /// Whether the person left the share of an import's new login ticked; none for any other use.
237    pub share: Option<bool>,
238}
239
240impl UseAnswer {
241    pub fn of(decision: Decision) -> Self {
242        Self { decision, value: None, save: false, by: By::Person, choice: None, share: None }
243    }
244
245    fn by(decision: Decision, by: By) -> Self {
246        Self { by, ..Self::of(decision) }
247    }
248}
249
250/// How a use request ended, as its caller tells the agent and the Activity.
251#[derive(Debug, Clone, Copy, PartialEq, Eq)]
252pub enum Ended {
253    Once,
254    Always,
255    /// Nobody answered in [`VETO`], so it went ahead, once.
256    WentAhead,
257    Denied,
258    /// An entry that needs a yes, and nobody gave one.
259    Expired,
260    Crowded,
261    /// The caller stopped waiting before srv decided.
262    NoAnswer,
263}
264
265impl Ended {
266    /// `answer` as it came, or `None` if the caller's own wait ran out.
267    pub fn of(answer: Option<&UseAnswer>) -> Self {
268        match answer.map(|a| (a.decision, a.by)) {
269            None => Self::NoAnswer,
270            Some((Decision::Once, By::Silence)) => Self::WentAhead,
271            Some((Decision::Once, _)) => Self::Once,
272            Some((Decision::Always, _)) => Self::Always,
273            Some((Decision::Deny, By::Silence)) => Self::Expired,
274            Some((Decision::Deny, By::Crowded)) => Self::Crowded,
275            Some((Decision::Deny, By::Person)) => Self::Denied,
276        }
277    }
278
279    pub fn allowed(self) -> bool {
280        matches!(self, Self::Once | Self::Always | Self::WentAhead)
281    }
282
283    /// The Activity line's outcome, saying who decided (spec §5.2).
284    pub fn outcome(self) -> &'static str {
285        match self {
286            Self::Once | Self::Always | Self::WentAhead => "done",
287            Self::Denied => "denied",
288            Self::Expired => "expired",
289            Self::Crowded => "dropped",
290            Self::NoAnswer => "timed out",
291        }
292    }
293
294    /// What the agent is told when it didn't go ahead; `nothing` says what
295    /// didn't happen ("nothing was typed").
296    pub fn refusal(self, nothing: &str) -> String {
297        match self {
298            Self::Expired => format!("an ID or card entry is used only on a yes, and nobody gave one: {nothing}; ask the person"),
299            Self::Crowded => format!("too many of your Vault requests were waiting, and this was the oldest: {nothing}; ask again"),
300            Self::NoAnswer => format!("the person didn't answer in time: {nothing}; ask again when they are there"),
301            _ => format!("the person said no: {nothing}"),
302        }
303    }
304}
305
306/// The Activity outcome of a use nobody answered that went ahead, on a line of
307/// its own before the use's own line: the Vault pane filters these.
308pub const WENT_AHEAD_OUTCOME: &str = "approved: no answer in 30 s";
309/// What the agent is told when its use went ahead on silence.
310pub const WENT_AHEAD: &str = "no one answered in 30 s, so it went ahead";
311
312#[derive(Default)]
313pub struct Uses {
314    pending: Mutex<Vec<(UseRequest, oneshot::Sender<UseAnswer>)>>,
315}
316
317pub fn uses() -> &'static Uses {
318    static USES: OnceLock<Uses> = OnceLock::new();
319    USES.get_or_init(Uses::default)
320}
321
322/// At most this many of one agent's wait at once; its oldest is denied.
323const MAX_PER_AGENT: usize = 16;
324/// At most this many wait at once. A new one when they do pushes out its own
325/// agent's oldest, never another agent's: with none of its own, it is denied.
326const MAX_PENDING: usize = 64;
327
328fn ms(d: Duration) -> u64 {
329    u64::try_from(d.as_millis()).unwrap_or(u64::MAX)
330}
331
332impl Uses {
333    /// Asks the person; `wait` is how long the caller waits at most. Sets the
334    /// request's deadline, and decides it on silence when that passes.
335    pub fn ask(&'static self, req: UseRequest, wait: Duration) -> oneshot::Receiver<UseAnswer> {
336        let (rx, id) = self.enqueue(req, wait, agentmux_common::time::now_ms_u64());
337        if let (Some(id), Ok(rt)) = (id, tokio::runtime::Handle::try_current()) {
338            rt.spawn(async move {
339                while let Some(at) = self.deadline(&id) {
340                    let now = agentmux_common::time::now_ms_u64();
341                    if at > now {
342                        tokio::time::sleep(Duration::from_millis(at - now)).await;
343                    } else {
344                        self.decide_unanswered(&id, now);
345                    }
346                }
347            });
348        }
349        rx
350    }
351
352    /// Adds `req`, made at `now`, within the limits; the id to watch, if it waits.
353    fn enqueue(&self, mut req: UseRequest, wait: Duration, now: u64) -> (oneshot::Receiver<UseAnswer>, Option<String>) {
354        let (tx, rx) = oneshot::channel();
355        req.goes_ahead = goes_ahead(&req);
356        req.expires_ms = now.saturating_add(ms(wait));
357        req.deadline_ms = if req.goes_ahead { now.saturating_add(ms(VETO)).min(req.expires_ms) } else { req.expires_ms };
358        let mut pending = self.pending.lock().unwrap_or_else(|p| p.into_inner());
359        pending.retain(|(_, tx)| !tx.is_closed());
360        let own = pending.iter().filter(|(r, _)| r.agent == req.agent).count();
361        if own >= MAX_PER_AGENT || (pending.len() >= MAX_PENDING && own > 0) {
362            let i = pending.iter().position(|(r, _)| r.agent == req.agent).unwrap_or(0);
363            let (_, oldest) = pending.remove(i);
364            let _ = oldest.send(UseAnswer::by(Decision::Deny, By::Crowded));
365        } else if pending.len() >= MAX_PENDING {
366            let _ = tx.send(UseAnswer::by(Decision::Deny, By::Crowded));
367            return (rx, None);
368        }
369        let id = req.id.clone();
370        pending.push((req, tx));
371        (rx, Some(id))
372    }
373
374    fn deadline(&self, id: &str) -> Option<u64> {
375        self.get(id).map(|r| r.deadline_ms)
376    }
377
378    /// Decides `id` if its deadline has passed by `now`: once if it may go
379    /// ahead, else denied.
380    fn decide_unanswered(&self, id: &str, now: u64) {
381        let mut pending = self.pending.lock().unwrap_or_else(|p| p.into_inner());
382        let Some(i) = pending.iter().position(|(r, _)| r.id == id && r.deadline_ms <= now) else { return };
383        let (r, tx) = pending.remove(i);
384        let _ = tx.send(UseAnswer::by(if r.goes_ahead { Decision::Once } else { Decision::Deny }, By::Silence));
385    }
386
387    /// The person is reading or acting in request `id`: its countdown holds
388    /// until [`HOLD`] after now, never past its own wait. False if nothing
389    /// waits under `id`.
390    pub fn hold(&self, id: &str) -> bool {
391        self.hold_at(id, agentmux_common::time::now_ms_u64())
392    }
393
394    fn hold_at(&self, id: &str, now: u64) -> bool {
395        let mut pending = self.pending.lock().unwrap_or_else(|p| p.into_inner());
396        let Some((r, _)) = pending.iter_mut().find(|(r, _)| r.id == id) else { return false };
397        if r.goes_ahead {
398            r.deadline_ms = r.deadline_ms.max(now.saturating_add(ms(HOLD))).min(r.expires_ms);
399        }
400        true
401    }
402
403    /// The request, for the host's answer to check against.
404    pub fn get(&self, id: &str) -> Option<UseRequest> {
405        let pending = self.pending.lock().unwrap_or_else(|p| p.into_inner());
406        pending.iter().find(|(r, _)| r.id == id).map(|(r, _)| r.clone())
407    }
408
409    /// The person's answer; false if nothing waits under `id` (answered, or the
410    /// agent stopped waiting).
411    pub fn answer(&self, id: &str, answer: UseAnswer) -> bool {
412        let mut pending = self.pending.lock().unwrap_or_else(|p| p.into_inner());
413        let Some(i) = pending.iter().position(|(r, _)| r.id == id) else { return false };
414        let (_, tx) = pending.remove(i);
415        tx.send(answer).is_ok()
416    }
417
418    /// The requests still waiting; one whose agent stopped waiting goes.
419    pub fn list(&self) -> Vec<UseRequest> {
420        let mut pending = self.pending.lock().unwrap_or_else(|p| p.into_inner());
421        pending.retain(|(_, tx)| !tx.is_closed());
422        pending.iter().map(|(r, _)| r.clone()).collect()
423    }
424
425    /// Drops a request the agent gave up on.
426    pub fn forget(&self, id: &str) {
427        self.pending.lock().unwrap_or_else(|p| p.into_inner()).retain(|(r, _)| r.id != id);
428    }
429}
430
431#[cfg(test)]
432#[path = "uses_tests.rs"]
433mod tests;