Skip to main content

agentmux_srv/server/
vault_ask.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Asking the person to allow an agent's use of a Vault entry, and waiting for
5//! how it ended (SPEC_VAULT_REQUESTS_AS_CARDS_IN_THE_AGENT_PANE_2026_11_01.md §5):
6//! the one way every use (a fill, a command, a capture, a sign-in, a rotation)
7//! asks, so each gets srv's deadline, the same attention and the same record of
8//! who decided.
9
10use std::time::Duration;
11
12use crate::backend::vault::agent_set;
13use crate::backend::vault::uses::{self, Ended, UseAnswer, UseRequest};
14
15use super::browser_vault_fill::Waiting;
16use super::AppState;
17
18/// How long past its own wait a caller waits, so srv's decision on silence
19/// always reaches it first.
20const GRACE: Duration = Duration::from_secs(5);
21
22/// The Activity action of a use that nobody answered and that went ahead.
23const ASKED: &str = "asked to use it";
24
25/// Asks the person to allow `request` and waits at most `wait`: srv decides on
26/// silence then. The tone and badges that say it waits are the asking agent's
27/// pane's, where its card is, else `attention_block`'s. A use that went ahead
28/// with no answer is recorded as such at once; every other outcome is recorded
29/// by the caller, with what it did.
30pub(super) async fn ask(state: &AppState, attention_block: &str, mut request: UseRequest, wait: Duration, headline: &str) -> (Ended, Option<UseAnswer>) {
31    request.block_id = shown_pane(state, &request.block_id);
32    // A value an agent had the Vault read, and the person has not seen, is never used on silence.
33    agent_set::apply(&state.identity_store, &mut request);
34    let was_unseen = !request.set_by.is_empty();
35    let (id, entry, label, agent) = (request.id.clone(), request.entry_id.clone(), request.entry_label.clone(), request.agent.clone());
36    let agent_reason = request.agent_reason.clone();
37    let target = target_of(&request);
38    let attention_block = if request.block_id.is_empty() { attention_block.to_string() } else { request.block_id.clone() };
39    let headline = notice(headline, uses::goes_ahead(&request));
40    let answer = uses::uses().ask(request, wait);
41    let _waiting = Waiting::new(id, state.clone());
42    super::vault_handlers::publish(state);
43    let _asking = crate::backend::user_attention::Asking::start(&state.broker, &state.mstore, &attention_block, "vault", &headline);
44    let answer = match tokio::time::timeout(wait + GRACE, answer).await {
45        Ok(Ok(a)) => Some(a),
46        // The request was taken down without an answer: as a no.
47        Ok(Err(_)) => Some(UseAnswer::of(uses::Decision::Deny)),
48        Err(_) => None,
49    };
50    let mut ended = Ended::of(answer.as_ref());
51    // The value was replaced by an agent while the person was being asked: the card did not say so, and silence does not
52    // approve a value nobody has seen. An answer they gave stands for this use, with no Always and no look at it counted.
53    let replaced_meanwhile = !was_unseen && agent_set::is_unseen(&state.identity_store, &entry);
54    if replaced_meanwhile {
55        ended = match ended {
56            Ended::WentAhead => Ended::NoAnswer,
57            Ended::Always => Ended::Once,
58            other => other,
59        };
60    }
61    // The person's yes to a use of a value an agent had the Vault read is their look at it: it is trusted from now on.
62    if matches!(ended, Ended::Once | Ended::Always) && !replaced_meanwhile {
63        agent_set::clear(&state.identity_store, &entry);
64    }
65    if ended == Ended::WentAhead {
66        let line = crate::backend::vault::Line { entry_id: &entry, label: &label, actor: &agent, action: ASKED, target: &target, outcome: uses::WENT_AHEAD_OUTCOME, reason: &agent_reason };
67        crate::backend::vault::record_line(&state.identity_store, line);
68    }
69    (ended, answer)
70}
71
72/// The notification's text: what the agent wants, and what silence does
73/// (spec §6): "Builder wants to rotate Stripe: goes ahead in 30 s unless you
74/// deny", or "...: needs your yes" for an ID or card entry.
75fn notice(headline: &str, goes_ahead: bool) -> String {
76    if goes_ahead {
77        format!("{headline}: goes ahead in {} s unless you deny", uses::VETO.as_secs())
78    } else {
79        format!("{headline}: needs your yes")
80    }
81}
82
83/// `out`, a successful answer to the agent, saying it went ahead because nobody
84/// answered, when it did (spec §5.1).
85pub(super) fn with_approval(mut out: serde_json::Value, went_ahead: bool) -> serde_json::Value {
86    if went_ahead {
87        out["approval"] = serde_json::json!(uses::WENT_AHEAD);
88    }
89    out
90}
91
92/// What a command's agent is told about the entries it was given because
93/// nobody answered, if any.
94pub(super) fn approval(labels: &[String]) -> Option<String> {
95    (!labels.is_empty()).then(|| format!("{} ({})", uses::WENT_AHEAD, labels.join(", ")))
96}
97
98/// Where the use was for, as the Activity line names it.
99fn target_of(r: &UseRequest) -> String {
100    if !r.command.is_empty() {
101        r.command.chars().take(160).collect()
102    } else if r.field.is_empty() {
103        r.origin.clone()
104    } else {
105        format!("{} ({})", r.origin, r.field)
106    }
107}
108
109/// `block_id` while a window shows that pane, else none: a request from an agent
110/// whose pane no window holds (a parked agent, a closed window) is asked in
111/// every window, where it can be answered, not as a card nobody sees.
112pub(super) fn shown_pane(state: &AppState, block_id: &str) -> String {
113    let shown = !block_id.is_empty() && crate::backend::notify::router::resolve_click_target(&state.mstore, block_id).is_some_and(|t| !t.window_ids.is_empty());
114    if shown {
115        block_id.to_string()
116    } else {
117        String::new()
118    }
119}
120
121/// The asking agent's own pane, for its request: the card is answered there.
122/// Empty when the agent's identity doesn't name one.
123pub(super) fn agent_pane(state: &AppState, caller: Option<&crate::server::caller::Caller>, auth: &agentmux_common::api_types::UiAutomationAuth) -> String {
124    super::ui_handlers::verified_block_id(state, caller, auth).unwrap_or_default()
125}
126
127#[cfg(test)]
128mod tests {
129    use super::notice;
130
131    #[test]
132    fn the_notice_says_what_silence_does() {
133        assert_eq!(notice("Builder wants to use Stripe", true), "Builder wants to use Stripe: goes ahead in 30 s unless you deny");
134        assert_eq!(notice("Builder wants to fill your passport", false), "Builder wants to fill your passport: needs your yes");
135    }
136}