Skip to main content

visdom_cli/
billing.rs

1//! Who pays for the calls of an agent `visdom` starts through the AI
2//! Gateway: the project (its gateway key, today's behaviour) or the
3//! developer's own Claude subscription. A choice inside gateway mode, not a
4//! mode of its own.
5
6use clap::ValueEnum;
7use serde::{Deserialize, Serialize};
8use tracevault_cli::agent::Agent;
9
10use crate::mode::{ModeReason, ResolvedMode, TracingMode, TrafficPolicy};
11
12/// The environment variable that names who pays.
13pub const BILLING_ENV: &str = "VISDOM_GATEWAY_BILLING";
14
15/// Who pays for the agent's calls through the gateway.
16#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, ValueEnum)]
17#[serde(rename_all = "snake_case")]
18pub enum Billing {
19    /// The project, through the developer's personal gateway key.
20    #[default]
21    Project,
22    /// The developer's own Claude subscription (Claude Code only).
23    Subscription,
24}
25
26impl Billing {
27    pub fn name(self) -> &'static str {
28        match self {
29            Billing::Project => "project",
30            Billing::Subscription => "subscription",
31        }
32    }
33}
34
35impl std::fmt::Display for Billing {
36    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
37        f.write_str(self.name())
38    }
39}
40
41/// Parse a billing value as the command line and the config files spell it.
42pub fn parse_billing(name: &str) -> Result<Billing, String> {
43    match name.trim().to_ascii_lowercase().as_str() {
44        "project" => Ok(Billing::Project),
45        "subscription" => Ok(Billing::Subscription),
46        _ => Err(format!(
47            "unknown billing `{name}` (use project or subscription)"
48        )),
49    }
50}
51
52/// Where the billing of a session was set.
53#[derive(Clone, Debug, PartialEq, Eq)]
54pub enum BillingSource {
55    Flag,
56    Env,
57    /// `billing` under `[gateway]` in the repository's (or workspace
58    /// folder's) `.visdom/config.toml`.
59    Repo,
60    /// `billing` under `[gateway]` in the user config at this path.
61    User(String),
62    /// Nobody set it: the project pays.
63    Default,
64}
65
66impl BillingSource {
67    /// Said as a person would read it.
68    pub fn describe(&self) -> String {
69        match self {
70            BillingSource::Flag => "--billing".to_string(),
71            BillingSource::Env => format!("{BILLING_ENV} in the environment"),
72            BillingSource::Repo => "billing under [gateway] in .visdom/config.toml".to_string(),
73            BillingSource::User(path) => format!("billing under [gateway] in {path}"),
74            BillingSource::Default => "the default".to_string(),
75        }
76    }
77}
78
79/// Who pays, and who said so.
80#[derive(Clone, Debug, PartialEq, Eq)]
81pub struct ResolvedBilling {
82    pub billing: Billing,
83    pub source: BillingSource,
84}
85
86impl ResolvedBilling {
87    /// `subscription (--billing)`.
88    pub fn describe(&self) -> String {
89        format!("{} ({})", self.billing.name(), self.source.describe())
90    }
91}
92
93/// Who pays: `--billing`, then `VISDOM_GATEWAY_BILLING` (a blank one is not
94/// set, an unknown value is an error), then the repository config, then the
95/// user config (`user_file` names it), then the project.
96pub fn configured_billing(
97    flag: Option<Billing>,
98    env: Option<&str>,
99    repo: Option<Billing>,
100    user: Option<Billing>,
101    user_file: &str,
102) -> Result<ResolvedBilling, String> {
103    let resolved = |billing, source| Ok(ResolvedBilling { billing, source });
104    if let Some(billing) = flag {
105        return resolved(billing, BillingSource::Flag);
106    }
107    if let Some(name) = env.filter(|v| !v.trim().is_empty()) {
108        let billing = parse_billing(name).map_err(|e| format!("{BILLING_ENV}: {e}"))?;
109        return resolved(billing, BillingSource::Env);
110    }
111    match (repo, user) {
112        (Some(billing), _) => resolved(billing, BillingSource::Repo),
113        (None, Some(billing)) => resolved(billing, BillingSource::User(user_file.to_string())),
114        (None, None) => resolved(Billing::Project, BillingSource::Default),
115    }
116}
117
118/// What the billing means for a session in `mode` with `agent`.
119#[derive(Clone, Debug, PartialEq, Eq)]
120pub enum BillingUse {
121    /// The setting applies.
122    Applies,
123    /// The workspace's policy keeps sessions off the gateway: nothing to pay
124    /// through it, so the setting is not used.
125    Unused,
126    /// A combination that cannot work; the text says why and what to do.
127    Rejected(String),
128}
129
130/// Whether `billing` can be used in `mode` with `agent`. `subscription`
131/// needs the gateway (hooks have no gateway key to pay or not pay with) and
132/// Claude Code; under a `direct` policy the setting is simply unused.
133pub fn billing_use(billing: &ResolvedBilling, mode: &ResolvedMode, agent: Agent) -> BillingUse {
134    if billing.billing == Billing::Project {
135        return match mode.mode {
136            TracingMode::Gateway => BillingUse::Applies,
137            TracingMode::Hooks => BillingUse::Unused,
138        };
139    }
140    if mode.mode == TracingMode::Hooks {
141        if mode.reason == ModeReason::Policy(TrafficPolicy::Direct) {
142            return BillingUse::Unused;
143        }
144        let why = match mode.reason {
145            ModeReason::Default => "nobody chose gateway mode, so sessions are traced by hooks",
146            _ => "this session is traced by hooks",
147        };
148        return BillingUse::Rejected(format!(
149            "billing = subscription ({}) is for sessions through the AI Gateway, but {why}: \
150             hooks tracing has no gateway key that would pay or not pay. Use --mode gateway, or \
151             set billing to project",
152            billing.source.describe()
153        ));
154    }
155    if agent != Agent::ClaudeCode {
156        return BillingUse::Rejected(format!(
157            "billing = subscription ({}) is not supported yet for {}: only Claude Code can use a \
158             subscription through the AI Gateway. Use --billing project, or set billing to project",
159            billing.source.describe(),
160            agent.label()
161        ));
162    }
163    BillingUse::Applies
164}
165
166#[cfg(test)]
167mod tests {
168    use super::*;
169    use crate::mode::effective_mode;
170    use Billing::{Project, Subscription};
171
172    fn pick(
173        flag: Option<Billing>,
174        env: Option<&str>,
175        repo: Option<Billing>,
176        user: Option<Billing>,
177    ) -> Result<ResolvedBilling, String> {
178        configured_billing(flag, env, repo, user, "/home/u/.config/visdom/config.toml")
179    }
180
181    fn resolved(billing: Billing, source: BillingSource) -> ResolvedBilling {
182        ResolvedBilling { billing, source }
183    }
184
185    #[test]
186    fn billing_parses_as_it_is_written() {
187        assert_eq!(parse_billing("project"), Ok(Project));
188        assert_eq!(parse_billing(" Subscription "), Ok(Subscription));
189        assert!(parse_billing("free")
190            .unwrap_err()
191            .contains("project or subscription"));
192        assert_eq!(Subscription.name(), "subscription");
193        assert_eq!(Billing::default(), Project);
194    }
195
196    #[test]
197    fn who_pays_is_flag_then_env_then_repo_then_user_then_the_project() {
198        assert_eq!(
199            pick(None, None, None, None),
200            Ok(resolved(Project, BillingSource::Default))
201        );
202        assert_eq!(
203            pick(None, None, None, Some(Subscription)),
204            Ok(resolved(
205                Subscription,
206                BillingSource::User("/home/u/.config/visdom/config.toml".to_string())
207            ))
208        );
209        assert_eq!(
210            pick(None, None, Some(Project), Some(Subscription)),
211            Ok(resolved(Project, BillingSource::Repo))
212        );
213        assert_eq!(
214            pick(None, Some("subscription"), Some(Project), Some(Project)),
215            Ok(resolved(Subscription, BillingSource::Env))
216        );
217        assert_eq!(
218            pick(
219                Some(Project),
220                Some("subscription"),
221                Some(Subscription),
222                Some(Subscription)
223            ),
224            Ok(resolved(Project, BillingSource::Flag))
225        );
226    }
227
228    #[test]
229    fn a_blank_variable_is_not_set_and_an_unknown_one_is_an_error() {
230        assert_eq!(
231            pick(None, Some("  "), None, Some(Subscription))
232                .unwrap()
233                .billing,
234            Subscription
235        );
236        let err = pick(None, Some("free"), None, None).unwrap_err();
237        assert!(err.starts_with("VISDOM_GATEWAY_BILLING:"), "{err}");
238        assert!(err.contains("project or subscription"), "{err}");
239    }
240
241    #[test]
242    fn sources_are_said_as_a_person_reads_them() {
243        let user = pick(None, None, None, Some(Project)).unwrap();
244        assert_eq!(
245            user.describe(),
246            "project (billing under [gateway] in /home/u/.config/visdom/config.toml)"
247        );
248        assert_eq!(
249            pick(None, Some("project"), None, None)
250                .unwrap()
251                .source
252                .describe(),
253            "VISDOM_GATEWAY_BILLING in the environment"
254        );
255        assert_eq!(BillingSource::Default.describe(), "the default");
256    }
257
258    fn sub(source: BillingSource) -> ResolvedBilling {
259        resolved(Subscription, source)
260    }
261
262    #[test]
263    fn a_subscription_through_the_gateway_applies_to_claude_code() {
264        for policy in [None, Some(TrafficPolicy::PerAgent)] {
265            let mode = effective_mode(Some(TracingMode::Gateway), policy);
266            assert_eq!(
267                billing_use(&sub(BillingSource::Flag), &mode, Agent::ClaudeCode),
268                BillingUse::Applies
269            );
270        }
271        // `enforced` means through the gateway, not paid by the project.
272        let enforced = effective_mode(None, Some(TrafficPolicy::Enforced));
273        assert_eq!(
274            billing_use(&sub(BillingSource::Repo), &enforced, Agent::ClaudeCode),
275            BillingUse::Applies
276        );
277        assert_eq!(
278            billing_use(
279                &resolved(Project, BillingSource::Default),
280                &enforced,
281                Agent::ClaudeCode
282            ),
283            BillingUse::Applies
284        );
285    }
286
287    #[test]
288    fn a_subscription_outside_the_gateway_is_rejected_and_says_why() {
289        for mode in [
290            effective_mode(Some(TracingMode::Hooks), None),
291            effective_mode(None, Some(TrafficPolicy::PerAgent)),
292        ] {
293            match billing_use(&sub(BillingSource::Flag), &mode, Agent::ClaudeCode) {
294                BillingUse::Rejected(why) => {
295                    assert!(why.contains("--billing"), "{why}");
296                    assert!(why.contains("hooks"), "{why}");
297                    assert!(why.contains("--mode gateway"), "{why}");
298                }
299                other => panic!("{other:?}"),
300            }
301        }
302    }
303
304    #[test]
305    fn a_direct_policy_leaves_the_setting_unused() {
306        let direct = effective_mode(Some(TracingMode::Gateway), Some(TrafficPolicy::Direct));
307        assert_eq!(
308            billing_use(&sub(BillingSource::Env), &direct, Agent::ClaudeCode),
309            BillingUse::Unused
310        );
311        assert_eq!(
312            billing_use(
313                &resolved(Project, BillingSource::Default),
314                &direct,
315                Agent::Codex
316            ),
317            BillingUse::Unused
318        );
319    }
320
321    #[test]
322    fn codex_cannot_use_a_subscription_yet() {
323        let mode = effective_mode(Some(TracingMode::Gateway), None);
324        match billing_use(&sub(BillingSource::Env), &mode, Agent::Codex) {
325            BillingUse::Rejected(why) => {
326                assert!(why.contains("not supported yet for Codex"), "{why}");
327                assert!(why.contains("VISDOM_GATEWAY_BILLING"), "{why}");
328            }
329            other => panic!("{other:?}"),
330        }
331        assert_eq!(
332            billing_use(
333                &resolved(Project, BillingSource::Default),
334                &mode,
335                Agent::Codex
336            ),
337            BillingUse::Applies
338        );
339    }
340}