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::billing::{Billing, BillingUse, ResolvedBilling};
7use crate::finding::{Finding, Severity};
8use crate::gateway::{OpenProject, SubscriptionTraffic};
9use crate::mode::{ModeReason, ResolvedMode, TracingMode, TrafficPolicy};
10use crate::suite::PolicyState;
11
12const COMPONENT: &str = "gateway";
13
14/// What a session through the gateway will use, worked out before anything
15/// is issued.
16#[derive(Clone, Debug, PartialEq, Eq)]
17pub struct GatewayPlan {
18    /// The gateway console, which issues the personal key.
19    pub console_url: String,
20    /// The LLM gateway the agent calls.
21    pub llm_url: String,
22    pub project: OpenProject,
23    /// Whether the gateway takes calls paid by a Claude subscription.
24    pub subscription_traffic: SubscriptionTraffic,
25}
26
27/// The mode, and the policy behind it. Nothing here needs attention unless
28/// the policy overruled what the developer chose.
29fn mode_findings(mode: &ResolvedMode, policy: &PolicyState) -> Vec<Finding> {
30    const ID: &str = "gateway.mode";
31    let overruled = |chosen: TracingMode, policy: TrafficPolicy| {
32        format!(
33            "you chose {} tracing, but the workspace's AI traffic policy is `{}`: sessions {}",
34            chosen.name(),
35            policy.name(),
36            match mode.mode {
37                TracingMode::Gateway => "go through the AI Gateway",
38                TracingMode::Hooks => "are captured by hooks, not through the AI Gateway",
39            }
40        )
41    };
42    let finding = match (mode.mode, mode.reason, mode.overruled) {
43        (_, ModeReason::Policy(policy), Some(chosen)) => {
44            Finding::new(COMPONENT, ID, Severity::Warn, overruled(chosen, policy))
45        }
46        (TracingMode::Gateway, ModeReason::Policy(_), None) => Finding::new(
47            COMPONENT,
48            ID,
49            Severity::Ok,
50            "sessions go through the AI Gateway (required by the workspace's AI traffic policy)",
51        ),
52        (TracingMode::Hooks, ModeReason::Policy(_), None) => Finding::new(
53            COMPONENT,
54            ID,
55            Severity::Ok,
56            "sessions are captured by hooks (the workspace's AI traffic policy routes nothing \
57             through the AI Gateway)",
58        ),
59        (TracingMode::Gateway, _, _) => Finding::new(
60            COMPONENT,
61            ID,
62            Severity::Ok,
63            "sessions go through the AI Gateway (your choice)",
64        ),
65        (TracingMode::Hooks, ModeReason::Chosen, _) => Finding::new(
66            COMPONENT,
67            ID,
68            Severity::Ok,
69            "sessions are captured by hooks (your choice)",
70        ),
71        (TracingMode::Hooks, _, _) => Finding::new(
72            COMPONENT,
73            ID,
74            Severity::Ok,
75            "sessions are captured by hooks (set tracing_mode = \"gateway\" in your visdom \
76             config, or pass --mode gateway, to use the AI Gateway)",
77        ),
78    };
79    let mut findings = vec![finding];
80    // Not being able to read the policy is worth a line in `doctor`, not one
81    // above every launch: most installations simply have none to read.
82    match policy {
83        PolicyState::Fresh(_) => {}
84        PolicyState::Remembered(policy, why) => findings.push(Finding::new(
85            COMPONENT,
86            "gateway.policy",
87            Severity::Info,
88            format!(
89                "the workspace's AI traffic policy could not be read ({why}); using the last \
90                 one known, `{}`",
91                policy.name()
92            ),
93        )),
94        PolicyState::Unknown(why) => findings.push(Finding::new(
95            COMPONENT,
96            "gateway.policy",
97            Severity::Info,
98            format!("the workspace's AI traffic policy is not known ({why}): your choice applies"),
99        )),
100    }
101    findings
102}
103
104/// The findings about the mode and, in gateway mode, about the gateway.
105/// `plan` is `None` outside gateway mode.
106pub fn check(
107    mode: &ResolvedMode,
108    policy: &PolicyState,
109    plan: Option<&Result<GatewayPlan, String>>,
110    agent: Agent,
111) -> Vec<Finding> {
112    let mut findings = mode_findings(mode, policy);
113    let Some(plan) = plan else {
114        return findings;
115    };
116    match plan {
117        Ok(plan) => {
118            findings.push(Finding::new(
119                COMPONENT,
120                "gateway.project",
121                Severity::Ok,
122                format!(
123                    "AI Gateway project `{}` at {} (a personal key is issued when the agent starts)",
124                    plan.project.slug, plan.llm_url
125                ),
126            ));
127            if agent == Agent::Codex {
128                findings.push(Finding::new(
129                    COMPONENT,
130                    "gateway.codex_key",
131                    Severity::Info,
132                    "Codex is given its key once: a session running when the key expires (24 \
133                     hours at most) or is replaced has to be restarted with `visdom`",
134                ));
135            }
136        }
137        Err(why) => {
138            let required = matches!(mode.reason, ModeReason::Policy(TrafficPolicy::Enforced));
139            findings.push(Finding::new(
140                COMPONENT,
141                "gateway.project",
142                Severity::Error,
143                if required {
144                    format!("{why} — the workspace requires the AI Gateway, so the agent will not be started")
145                } else {
146                    format!("{why} — the agent will be started with hooks tracing instead")
147                },
148            ));
149        }
150    }
151    findings
152}
153
154/// Who pays for the agent's calls through the gateway, and who said so
155/// (`gateway.billing`). Nothing outside the gateway unless a subscription is
156/// set where it cannot be used.
157pub fn billing_finding(billing: &ResolvedBilling, usage: &BillingUse) -> Option<Finding> {
158    const ID: &str = "gateway.billing";
159    let finding = match (usage, billing.billing) {
160        (BillingUse::Rejected(why), _) => Finding::new(COMPONENT, ID, Severity::Error, why.clone()),
161        (BillingUse::Unused, Billing::Project) => return None,
162        (BillingUse::Unused, Billing::Subscription) => Finding::new(
163            COMPONENT,
164            ID,
165            Severity::Info,
166            format!(
167                "billing = {}: not used, the workspace's AI traffic policy keeps sessions off the \
168                 AI Gateway",
169                billing.describe()
170            ),
171        ),
172        (BillingUse::Applies, Billing::Project) => Finding::new(
173            COMPONENT,
174            ID,
175            Severity::Ok,
176            format!(
177                "billing = {}: the project pays for the agent's calls, through your personal key",
178                billing.describe()
179            ),
180        ),
181        (BillingUse::Applies, Billing::Subscription) => Finding::new(
182            COMPONENT,
183            ID,
184            Severity::Ok,
185            format!(
186                "billing = {}: your Claude subscription pays for the agent's calls — Claude Code \
187                 keeps its claude.ai login and the gateway gets your subscription key",
188                billing.describe()
189            ),
190        ),
191    };
192    Some(finding)
193}
194
195#[cfg(test)]
196mod tests {
197    use super::*;
198    use crate::mode::effective_mode;
199
200    fn fresh(policy: TrafficPolicy) -> PolicyState {
201        PolicyState::Fresh(policy)
202    }
203
204    fn plan() -> GatewayPlan {
205        GatewayPlan {
206            console_url: "https://gw.example.com".to_string(),
207            llm_url: "https://llm.example.com".to_string(),
208            project: OpenProject {
209                id: "p-1".to_string(),
210                slug: "alpha".to_string(),
211                name: "Alpha".to_string(),
212                models: None,
213            },
214            subscription_traffic: SubscriptionTraffic::Allowed,
215        }
216    }
217
218    fn only(findings: Vec<Finding>) -> Finding {
219        assert_eq!(findings.len(), 1, "{findings:?}");
220        findings.into_iter().next().unwrap()
221    }
222
223    #[test]
224    fn the_default_is_hooks_and_says_how_to_choose_the_gateway() {
225        let mode = effective_mode(None, Some(TrafficPolicy::PerAgent));
226        let finding = only(check(
227            &mode,
228            &fresh(TrafficPolicy::PerAgent),
229            None,
230            Agent::ClaudeCode,
231        ));
232        assert_eq!(
233            (finding.id, finding.severity),
234            ("gateway.mode", Severity::Ok)
235        );
236        assert!(finding.message.contains("--mode gateway"), "{finding:?}");
237    }
238
239    #[test]
240    fn a_choice_the_policy_allows_is_reported_as_the_developers() {
241        let mode = effective_mode(Some(TracingMode::Gateway), Some(TrafficPolicy::PerAgent));
242        let findings = check(
243            &mode,
244            &fresh(TrafficPolicy::PerAgent),
245            Some(&Ok(plan())),
246            Agent::ClaudeCode,
247        );
248        assert_eq!(findings.len(), 2, "{findings:?}");
249        assert!(findings[0].message.contains("your choice"));
250        assert_eq!(findings[1].id, "gateway.project");
251        assert_eq!(findings[1].severity, Severity::Ok);
252        assert!(findings[1].message.contains("`alpha`"), "{findings:?}");
253    }
254
255    #[test]
256    fn an_overruled_choice_needs_attention() {
257        let mode = effective_mode(Some(TracingMode::Hooks), Some(TrafficPolicy::Enforced));
258        let findings = check(
259            &mode,
260            &fresh(TrafficPolicy::Enforced),
261            Some(&Ok(plan())),
262            Agent::ClaudeCode,
263        );
264        assert_eq!(findings[0].severity, Severity::Warn);
265        assert!(findings[0].message.contains("`enforced`"), "{findings:?}");
266        assert!(findings[0].message.contains("go through the AI Gateway"));
267
268        let mode = effective_mode(Some(TracingMode::Gateway), Some(TrafficPolicy::Direct));
269        let finding = only(check(
270            &mode,
271            &fresh(TrafficPolicy::Direct),
272            None,
273            Agent::Codex,
274        ));
275        assert_eq!(finding.severity, Severity::Warn);
276        assert!(finding.message.contains("captured by hooks"), "{finding:?}");
277    }
278
279    #[test]
280    fn a_policy_that_agrees_with_the_choice_is_fine() {
281        let mode = effective_mode(None, Some(TrafficPolicy::Enforced));
282        let findings = check(
283            &mode,
284            &fresh(TrafficPolicy::Enforced),
285            Some(&Ok(plan())),
286            Agent::ClaudeCode,
287        );
288        assert_eq!(findings[0].severity, Severity::Ok);
289        assert!(findings[0].message.contains("required by the workspace"));
290    }
291
292    #[test]
293    fn an_unreadable_policy_is_information_only() {
294        let mode = effective_mode(None, None);
295        let unknown = PolicyState::Unknown("this installation names no Control Plane".to_string());
296        let findings = check(&mode, &unknown, None, Agent::ClaudeCode);
297        assert_eq!(findings[1].id, "gateway.policy");
298        assert_eq!(findings[1].severity, Severity::Info);
299
300        let remembered = PolicyState::Remembered(TrafficPolicy::Enforced, "HTTP 503".to_string());
301        let mode = effective_mode(None, remembered.policy());
302        let findings = check(&mode, &remembered, Some(&Ok(plan())), Agent::ClaudeCode);
303        assert_eq!(findings[1].severity, Severity::Info);
304        assert!(findings[1].message.contains("HTTP 503"), "{findings:?}");
305        assert!(findings[1].message.contains("`enforced`"), "{findings:?}");
306    }
307
308    #[test]
309    fn a_gateway_that_is_not_ready_says_what_happens_next() {
310        let failed: Result<GatewayPlan, String> = Err("no AI Gateway project is open".to_string());
311        let chosen = effective_mode(Some(TracingMode::Gateway), Some(TrafficPolicy::PerAgent));
312        let findings = check(
313            &chosen,
314            &fresh(TrafficPolicy::PerAgent),
315            Some(&failed),
316            Agent::ClaudeCode,
317        );
318        assert_eq!(findings[1].severity, Severity::Error);
319        assert!(findings[1].message.contains("hooks tracing instead"));
320
321        let enforced = effective_mode(None, Some(TrafficPolicy::Enforced));
322        let findings = check(
323            &enforced,
324            &fresh(TrafficPolicy::Enforced),
325            Some(&failed),
326            Agent::ClaudeCode,
327        );
328        assert!(findings[1].message.contains("will not be started"));
329    }
330
331    #[test]
332    fn who_pays_is_reported_with_its_source() {
333        use crate::billing::BillingSource;
334        let project = ResolvedBilling {
335            billing: Billing::Project,
336            source: BillingSource::Default,
337        };
338        let finding = billing_finding(&project, &BillingUse::Applies).unwrap();
339        assert_eq!(
340            (finding.id, finding.severity),
341            ("gateway.billing", Severity::Ok)
342        );
343        assert!(
344            finding.message.contains("project (the default)"),
345            "{finding:?}"
346        );
347        assert!(billing_finding(&project, &BillingUse::Unused).is_none());
348
349        let sub = ResolvedBilling {
350            billing: Billing::Subscription,
351            source: BillingSource::Flag,
352        };
353        let finding = billing_finding(&sub, &BillingUse::Applies).unwrap();
354        assert_eq!(finding.severity, Severity::Ok);
355        assert!(
356            finding.message.contains("your Claude subscription pays")
357                && finding.message.contains("claude.ai login"),
358            "{finding:?}"
359        );
360        let finding = billing_finding(&sub, &BillingUse::Unused).unwrap();
361        assert_eq!(finding.severity, Severity::Info);
362        let finding = billing_finding(&sub, &BillingUse::Rejected("why".to_string())).unwrap();
363        assert_eq!(
364            (finding.severity, finding.message.as_str()),
365            (Severity::Error, "why")
366        );
367    }
368
369    #[test]
370    fn codex_is_told_its_key_does_not_renew() {
371        let mode = effective_mode(Some(TracingMode::Gateway), None);
372        let unknown = PolicyState::Fresh(TrafficPolicy::PerAgent);
373        let findings = check(&mode, &unknown, Some(&Ok(plan())), Agent::Codex);
374        let note = findings
375            .iter()
376            .find(|f| f.id == "gateway.codex_key")
377            .unwrap();
378        assert_eq!(note.severity, Severity::Info);
379        let findings = check(&mode, &unknown, Some(&Ok(plan())), Agent::ClaudeCode);
380        assert!(!findings.iter().any(|f| f.id == "gateway.codex_key"));
381    }
382}