Skip to main content

visdom_cli/components/
gateway.rs

1//! Which way this developer's sessions are traced, who decided it, and —
2//! through the AI Gateway — whether the gateway is ready for them.
3
4use tracevault_cli::agent::Agent;
5
6use crate::finding::{Finding, Severity};
7use crate::gateway::OpenProject;
8use crate::mode::{ModeReason, ResolvedMode, TracingMode, TrafficPolicy};
9use crate::suite::PolicyState;
10
11const COMPONENT: &str = "gateway";
12
13/// What a session through the gateway will use, worked out before anything
14/// is issued.
15#[derive(Clone, Debug, PartialEq, Eq)]
16pub struct GatewayPlan {
17    /// The gateway console, which issues the personal key.
18    pub console_url: String,
19    /// The LLM gateway the agent calls.
20    pub llm_url: String,
21    pub project: OpenProject,
22}
23
24/// The mode, and the policy behind it. Nothing here needs attention unless
25/// the policy overruled what the developer chose.
26fn mode_findings(mode: &ResolvedMode, policy: &PolicyState) -> Vec<Finding> {
27    const ID: &str = "gateway.mode";
28    let overruled = |chosen: TracingMode, policy: TrafficPolicy| {
29        format!(
30            "you chose {} tracing, but the workspace's AI traffic policy is `{}`: sessions {}",
31            chosen.name(),
32            policy.name(),
33            match mode.mode {
34                TracingMode::Gateway => "go through the AI Gateway",
35                TracingMode::Hooks => "are captured by hooks, not through the AI Gateway",
36            }
37        )
38    };
39    let finding = match (mode.mode, mode.reason, mode.overruled) {
40        (_, ModeReason::Policy(policy), Some(chosen)) => {
41            Finding::new(COMPONENT, ID, Severity::Warn, overruled(chosen, policy))
42        }
43        (TracingMode::Gateway, ModeReason::Policy(_), None) => Finding::new(
44            COMPONENT,
45            ID,
46            Severity::Ok,
47            "sessions go through the AI Gateway (required by the workspace's AI traffic policy)",
48        ),
49        (TracingMode::Hooks, ModeReason::Policy(_), None) => Finding::new(
50            COMPONENT,
51            ID,
52            Severity::Ok,
53            "sessions are captured by hooks (the workspace's AI traffic policy routes nothing \
54             through the AI Gateway)",
55        ),
56        (TracingMode::Gateway, _, _) => Finding::new(
57            COMPONENT,
58            ID,
59            Severity::Ok,
60            "sessions go through the AI Gateway (your choice)",
61        ),
62        (TracingMode::Hooks, ModeReason::Chosen, _) => Finding::new(
63            COMPONENT,
64            ID,
65            Severity::Ok,
66            "sessions are captured by hooks (your choice)",
67        ),
68        (TracingMode::Hooks, _, _) => Finding::new(
69            COMPONENT,
70            ID,
71            Severity::Ok,
72            "sessions are captured by hooks (set tracing_mode = \"gateway\" in your visdom \
73             config, or pass --mode gateway, to use the AI Gateway)",
74        ),
75    };
76    let mut findings = vec![finding];
77    // Not being able to read the policy is worth a line in `doctor`, not one
78    // above every launch: most installations simply have none to read.
79    match policy {
80        PolicyState::Fresh(_) => {}
81        PolicyState::Remembered(policy, why) => findings.push(Finding::new(
82            COMPONENT,
83            "gateway.policy",
84            Severity::Info,
85            format!(
86                "the workspace's AI traffic policy could not be read ({why}); using the last \
87                 one known, `{}`",
88                policy.name()
89            ),
90        )),
91        PolicyState::Unknown(why) => findings.push(Finding::new(
92            COMPONENT,
93            "gateway.policy",
94            Severity::Info,
95            format!("the workspace's AI traffic policy is not known ({why}): your choice applies"),
96        )),
97    }
98    findings
99}
100
101/// The findings about the mode and, in gateway mode, about the gateway.
102/// `plan` is `None` outside gateway mode.
103pub fn check(
104    mode: &ResolvedMode,
105    policy: &PolicyState,
106    plan: Option<&Result<GatewayPlan, String>>,
107    agent: Agent,
108) -> Vec<Finding> {
109    let mut findings = mode_findings(mode, policy);
110    let Some(plan) = plan else {
111        return findings;
112    };
113    match plan {
114        Ok(plan) => {
115            findings.push(Finding::new(
116                COMPONENT,
117                "gateway.project",
118                Severity::Ok,
119                format!(
120                    "AI Gateway project `{}` at {} (a personal key is issued when the agent starts)",
121                    plan.project.slug, plan.llm_url
122                ),
123            ));
124            if agent == Agent::Codex {
125                findings.push(Finding::new(
126                    COMPONENT,
127                    "gateway.codex_key",
128                    Severity::Info,
129                    "Codex is given its key once: a session running when the key expires (24 \
130                     hours at most) or is replaced has to be restarted with `visdom`",
131                ));
132            }
133        }
134        Err(why) => {
135            let required = matches!(mode.reason, ModeReason::Policy(TrafficPolicy::Enforced));
136            findings.push(Finding::new(
137                COMPONENT,
138                "gateway.project",
139                Severity::Error,
140                if required {
141                    format!("{why} — the workspace requires the AI Gateway, so the agent will not be started")
142                } else {
143                    format!("{why} — the agent will be started with hooks tracing instead")
144                },
145            ));
146        }
147    }
148    findings
149}
150
151#[cfg(test)]
152mod tests {
153    use super::*;
154    use crate::mode::effective_mode;
155
156    fn fresh(policy: TrafficPolicy) -> PolicyState {
157        PolicyState::Fresh(policy)
158    }
159
160    fn plan() -> GatewayPlan {
161        GatewayPlan {
162            console_url: "https://gw.example.com".to_string(),
163            llm_url: "https://llm.example.com".to_string(),
164            project: OpenProject {
165                id: "p-1".to_string(),
166                slug: "alpha".to_string(),
167                name: "Alpha".to_string(),
168            },
169        }
170    }
171
172    fn only(findings: Vec<Finding>) -> Finding {
173        assert_eq!(findings.len(), 1, "{findings:?}");
174        findings.into_iter().next().unwrap()
175    }
176
177    #[test]
178    fn the_default_is_hooks_and_says_how_to_choose_the_gateway() {
179        let mode = effective_mode(None, Some(TrafficPolicy::PerAgent));
180        let finding = only(check(
181            &mode,
182            &fresh(TrafficPolicy::PerAgent),
183            None,
184            Agent::ClaudeCode,
185        ));
186        assert_eq!(
187            (finding.id, finding.severity),
188            ("gateway.mode", Severity::Ok)
189        );
190        assert!(finding.message.contains("--mode gateway"), "{finding:?}");
191    }
192
193    #[test]
194    fn a_choice_the_policy_allows_is_reported_as_the_developers() {
195        let mode = effective_mode(Some(TracingMode::Gateway), Some(TrafficPolicy::PerAgent));
196        let findings = check(
197            &mode,
198            &fresh(TrafficPolicy::PerAgent),
199            Some(&Ok(plan())),
200            Agent::ClaudeCode,
201        );
202        assert_eq!(findings.len(), 2, "{findings:?}");
203        assert!(findings[0].message.contains("your choice"));
204        assert_eq!(findings[1].id, "gateway.project");
205        assert_eq!(findings[1].severity, Severity::Ok);
206        assert!(findings[1].message.contains("`alpha`"), "{findings:?}");
207    }
208
209    #[test]
210    fn an_overruled_choice_needs_attention() {
211        let mode = effective_mode(Some(TracingMode::Hooks), Some(TrafficPolicy::Enforced));
212        let findings = check(
213            &mode,
214            &fresh(TrafficPolicy::Enforced),
215            Some(&Ok(plan())),
216            Agent::ClaudeCode,
217        );
218        assert_eq!(findings[0].severity, Severity::Warn);
219        assert!(findings[0].message.contains("`enforced`"), "{findings:?}");
220        assert!(findings[0].message.contains("go through the AI Gateway"));
221
222        let mode = effective_mode(Some(TracingMode::Gateway), Some(TrafficPolicy::Direct));
223        let finding = only(check(
224            &mode,
225            &fresh(TrafficPolicy::Direct),
226            None,
227            Agent::Codex,
228        ));
229        assert_eq!(finding.severity, Severity::Warn);
230        assert!(finding.message.contains("captured by hooks"), "{finding:?}");
231    }
232
233    #[test]
234    fn a_policy_that_agrees_with_the_choice_is_fine() {
235        let mode = effective_mode(None, Some(TrafficPolicy::Enforced));
236        let findings = check(
237            &mode,
238            &fresh(TrafficPolicy::Enforced),
239            Some(&Ok(plan())),
240            Agent::ClaudeCode,
241        );
242        assert_eq!(findings[0].severity, Severity::Ok);
243        assert!(findings[0].message.contains("required by the workspace"));
244    }
245
246    #[test]
247    fn an_unreadable_policy_is_information_only() {
248        let mode = effective_mode(None, None);
249        let unknown = PolicyState::Unknown("this installation names no Control Plane".to_string());
250        let findings = check(&mode, &unknown, None, Agent::ClaudeCode);
251        assert_eq!(findings[1].id, "gateway.policy");
252        assert_eq!(findings[1].severity, Severity::Info);
253
254        let remembered = PolicyState::Remembered(TrafficPolicy::Enforced, "HTTP 503".to_string());
255        let mode = effective_mode(None, remembered.policy());
256        let findings = check(&mode, &remembered, Some(&Ok(plan())), Agent::ClaudeCode);
257        assert_eq!(findings[1].severity, Severity::Info);
258        assert!(findings[1].message.contains("HTTP 503"), "{findings:?}");
259        assert!(findings[1].message.contains("`enforced`"), "{findings:?}");
260    }
261
262    #[test]
263    fn a_gateway_that_is_not_ready_says_what_happens_next() {
264        let failed: Result<GatewayPlan, String> = Err("no AI Gateway project is open".to_string());
265        let chosen = effective_mode(Some(TracingMode::Gateway), Some(TrafficPolicy::PerAgent));
266        let findings = check(
267            &chosen,
268            &fresh(TrafficPolicy::PerAgent),
269            Some(&failed),
270            Agent::ClaudeCode,
271        );
272        assert_eq!(findings[1].severity, Severity::Error);
273        assert!(findings[1].message.contains("hooks tracing instead"));
274
275        let enforced = effective_mode(None, Some(TrafficPolicy::Enforced));
276        let findings = check(
277            &enforced,
278            &fresh(TrafficPolicy::Enforced),
279            Some(&failed),
280            Agent::ClaudeCode,
281        );
282        assert!(findings[1].message.contains("will not be started"));
283    }
284
285    #[test]
286    fn codex_is_told_its_key_does_not_renew() {
287        let mode = effective_mode(Some(TracingMode::Gateway), None);
288        let unknown = PolicyState::Fresh(TrafficPolicy::PerAgent);
289        let findings = check(&mode, &unknown, Some(&Ok(plan())), Agent::Codex);
290        let note = findings
291            .iter()
292            .find(|f| f.id == "gateway.codex_key")
293            .unwrap();
294        assert_eq!(note.severity, Severity::Info);
295        let findings = check(&mode, &unknown, Some(&Ok(plan())), Agent::ClaudeCode);
296        assert!(!findings.iter().any(|f| f.id == "gateway.codex_key"));
297    }
298}