Skip to main content

visdom_cli/
mode.rs

1//! How a developer's agent sessions reach AI Tracing: the developer's choice,
2//! bounded by the workspace's AI traffic policy.
3
4use clap::ValueEnum;
5use serde::{Deserialize, Serialize};
6
7/// The environment variable that names the mode. `visdom` reads it as a
8/// choice and sets it on the agent it launches, where the capture hooks read
9/// it: under `gateway` they record nothing, the gateway does.
10pub const MODE_ENV: &str = tracevault_cli::commands::stream::TRACING_MODE_ENV;
11/// Set to `1` on an agent started through the AI Gateway, and on nothing
12/// else: what tells the capture hooks to record nothing.
13pub const GATEWAY_SESSION_ENV: &str = tracevault_cli::commands::stream::GATEWAY_SESSION_ENV;
14
15/// The capture path of a session. Exactly one is meant to be active.
16#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, ValueEnum)]
17#[serde(rename_all = "snake_case")]
18pub enum TracingMode {
19    /// Agent hooks and git hooks capture the session.
20    Hooks,
21    /// The agent's LLM traffic goes through the AI Gateway, which records it.
22    Gateway,
23}
24
25impl TracingMode {
26    pub fn name(self) -> &'static str {
27        match self {
28            TracingMode::Hooks => "hooks",
29            TracingMode::Gateway => "gateway",
30        }
31    }
32}
33
34/// Parse a mode as the command line and the config files spell it.
35pub fn parse_mode(name: &str) -> Result<TracingMode, String> {
36    match name.trim().to_ascii_lowercase().as_str() {
37        "hooks" => Ok(TracingMode::Hooks),
38        "gateway" => Ok(TracingMode::Gateway),
39        _ => Err(format!(
40            "unknown tracing mode `{name}` (use hooks or gateway)"
41        )),
42    }
43}
44
45/// The workspace's AI traffic policy, set by an admin in Control Plane
46/// (`ai_traffic_policy` of `GET /api/v1/workspace/settings`).
47#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
48#[serde(rename_all = "snake_case")]
49pub enum TrafficPolicy {
50    /// Nothing goes through the AI Gateway.
51    Direct,
52    /// Each developer (and agent) chooses.
53    PerAgent,
54    /// All LLM traffic goes through the AI Gateway.
55    Enforced,
56}
57
58impl TrafficPolicy {
59    pub fn name(self) -> &'static str {
60        match self {
61            TrafficPolicy::Direct => "direct",
62            TrafficPolicy::PerAgent => "per_agent",
63            TrafficPolicy::Enforced => "enforced",
64        }
65    }
66}
67
68/// Why a session runs in the mode it does.
69#[derive(Clone, Copy, Debug, PartialEq, Eq)]
70pub enum ModeReason {
71    /// The developer chose it and the policy leaves the choice to them (or
72    /// could not be read).
73    Chosen,
74    /// Nobody chose: hooks, the mode that needs nothing else.
75    Default,
76    /// The workspace policy decides, whatever was chosen.
77    Policy(TrafficPolicy),
78}
79
80/// The mode of a session and how it came about.
81#[derive(Clone, Copy, Debug, PartialEq, Eq)]
82pub struct ResolvedMode {
83    pub mode: TracingMode,
84    pub reason: ModeReason,
85    /// What the developer chose, when the policy overrules it.
86    pub overruled: Option<TracingMode>,
87}
88
89/// The mode somebody chose: `--mode`, then `VISDOM_TRACING_MODE`, then the
90/// repository config, then the user config. `None` when nobody did.
91pub fn configured_mode(
92    flag: Option<TracingMode>,
93    env: Option<&str>,
94    repo: Option<TracingMode>,
95    user: Option<TracingMode>,
96) -> Result<Option<TracingMode>, String> {
97    if flag.is_some() {
98        return Ok(flag);
99    }
100    match env.filter(|v| !v.trim().is_empty()) {
101        Some(name) => parse_mode(name)
102            .map(Some)
103            .map_err(|e| format!("{MODE_ENV}: {e}")),
104        None => Ok(repo.or(user)),
105    }
106}
107
108/// The mode a session runs in. An admin may enforce one (`enforced`: gateway,
109/// `direct`: hooks); under `per_agent`, or when the policy is not known, the
110/// developer's choice stands, and hooks when they made none.
111pub fn effective_mode(chosen: Option<TracingMode>, policy: Option<TrafficPolicy>) -> ResolvedMode {
112    let forced = match policy {
113        Some(TrafficPolicy::Enforced) => Some(TracingMode::Gateway),
114        Some(TrafficPolicy::Direct) => Some(TracingMode::Hooks),
115        Some(TrafficPolicy::PerAgent) | None => None,
116    };
117    match (forced, chosen, policy) {
118        (Some(mode), chosen, Some(policy)) => ResolvedMode {
119            mode,
120            reason: ModeReason::Policy(policy),
121            overruled: chosen.filter(|c| *c != mode),
122        },
123        (_, Some(mode), _) => ResolvedMode {
124            mode,
125            reason: ModeReason::Chosen,
126            overruled: None,
127        },
128        _ => ResolvedMode {
129            mode: TracingMode::Hooks,
130            reason: ModeReason::Default,
131            overruled: None,
132        },
133    }
134}
135
136#[cfg(test)]
137mod tests {
138    use super::*;
139    use TracingMode::{Gateway, Hooks};
140
141    #[test]
142    fn modes_parse_as_they_are_written() {
143        assert_eq!(parse_mode("hooks"), Ok(Hooks));
144        assert_eq!(parse_mode(" Gateway "), Ok(Gateway));
145        assert!(parse_mode("proxy")
146            .unwrap_err()
147            .contains("hooks or gateway"));
148        assert_eq!(Gateway.name(), "gateway");
149    }
150
151    #[test]
152    fn the_choice_is_flag_then_env_then_repo_then_user() {
153        let pick = |flag, env, repo, user| configured_mode(flag, env, repo, user);
154        assert_eq!(pick(None, None, None, None), Ok(None));
155        assert_eq!(pick(None, None, None, Some(Gateway)), Ok(Some(Gateway)));
156        assert_eq!(
157            pick(None, None, Some(Hooks), Some(Gateway)),
158            Ok(Some(Hooks))
159        );
160        assert_eq!(
161            pick(None, Some("gateway"), Some(Hooks), Some(Hooks)),
162            Ok(Some(Gateway))
163        );
164        assert_eq!(
165            pick(Some(Hooks), Some("gateway"), Some(Gateway), Some(Gateway)),
166            Ok(Some(Hooks))
167        );
168        assert_eq!(
169            pick(None, Some("  "), None, Some(Gateway)),
170            Ok(Some(Gateway))
171        );
172        let err = pick(None, Some("nope"), None, None).unwrap_err();
173        assert!(err.starts_with("VISDOM_TRACING_MODE:"), "{err}");
174    }
175
176    #[test]
177    fn without_an_enforcing_policy_the_choice_stands() {
178        for policy in [None, Some(TrafficPolicy::PerAgent)] {
179            assert_eq!(
180                effective_mode(Some(Gateway), policy),
181                ResolvedMode {
182                    mode: Gateway,
183                    reason: ModeReason::Chosen,
184                    overruled: None
185                }
186            );
187            assert_eq!(
188                effective_mode(None, policy),
189                ResolvedMode {
190                    mode: Hooks,
191                    reason: ModeReason::Default,
192                    overruled: None
193                }
194            );
195        }
196    }
197
198    #[test]
199    fn an_enforcing_policy_decides_and_says_what_it_overruled() {
200        let enforced = Some(TrafficPolicy::Enforced);
201        assert_eq!(
202            effective_mode(Some(Hooks), enforced),
203            ResolvedMode {
204                mode: Gateway,
205                reason: ModeReason::Policy(TrafficPolicy::Enforced),
206                overruled: Some(Hooks)
207            }
208        );
209        assert_eq!(effective_mode(None, enforced).mode, Gateway);
210        assert_eq!(effective_mode(Some(Gateway), enforced).overruled, None);
211
212        let direct = Some(TrafficPolicy::Direct);
213        assert_eq!(
214            effective_mode(Some(Gateway), direct),
215            ResolvedMode {
216                mode: Hooks,
217                reason: ModeReason::Policy(TrafficPolicy::Direct),
218                overruled: Some(Gateway)
219            }
220        );
221        assert_eq!(effective_mode(None, direct).overruled, None);
222    }
223
224    #[test]
225    fn policies_read_control_planes_spelling() {
226        let parse = |s: &str| serde_json::from_str::<TrafficPolicy>(s);
227        assert_eq!(parse("\"per_agent\"").unwrap(), TrafficPolicy::PerAgent);
228        assert_eq!(parse("\"enforced\"").unwrap(), TrafficPolicy::Enforced);
229        assert_eq!(parse("\"direct\"").unwrap(), TrafficPolicy::Direct);
230        assert!(parse("\"other\"").is_err());
231    }
232}