Skip to main content

jouet_git/
agent.rs

1//! Which agent is running, as far as the environment says, and the commit
2//! trailers that follow from it.
3//!
4//! Nothing here is guessed. The tool and its version come from `AI_AGENT`
5//! (`claude-code_2-1-309_agent` is Claude Code 2.1.309), the tool alone from
6//! `mise-agent-env`'s detection when `AI_AGENT` is not set, and the model only
7//! from `JOUET_AI_MODEL`, since no harness exports the model it runs. A value
8//! the environment does not give is `unavailable`.
9
10use std::ffi::OsString;
11
12const UNAVAILABLE: &str = "unavailable";
13
14#[derive(Debug, Clone, Default, PartialEq, Eq)]
15pub struct Agent {
16    /// The agent's stable identifier, such as `claude-code` or `codex`.
17    pub id: Option<String>,
18    pub version: Option<String>,
19    /// `provider/model`, from `JOUET_AI_MODEL`.
20    pub model: Option<String>,
21}
22
23impl Agent {
24    pub fn from_env() -> Self {
25        Self::from_lookup(|name| std::env::var_os(name))
26    }
27
28    pub(crate) fn from_lookup(env: impl Fn(&str) -> Option<OsString>) -> Self {
29        let text = |name| {
30            env(name)
31                .map(|v| v.to_string_lossy().trim().to_string())
32                .filter(|v| !v.is_empty())
33        };
34        let raw = text("AI_AGENT");
35        let (named, version) = raw.as_deref().map_or((None, None), parse_ai_agent);
36        // mise-agent-env's names, so jouet and mise agree on who is running;
37        // an agent it does not know keeps the name `AI_AGENT` gives it.
38        let id = match mise_agent_env::detect_with_env(&env).map(|d| d.agent) {
39            Some(mise_agent_env::Agent::Other) | None => named,
40            Some(agent) => Some(agent.as_str().to_string()),
41        };
42        Self {
43            id,
44            version,
45            model: text("JOUET_AI_MODEL"),
46        }
47    }
48
49    /// The tool's name as people write it: `Claude Code`, `Codex`, or the
50    /// identifier itself for agents without a known spelling.
51    pub fn tool(&self) -> Option<String> {
52        let id = self.id.as_deref()?;
53        Some(
54            match id {
55                "claude-code" => "Claude Code",
56                "claude-cowork" => "Claude Cowork",
57                "codex" => "Codex",
58                "cursor" => "Cursor",
59                "gemini-cli" => "Gemini CLI",
60                "github-copilot" => "GitHub Copilot",
61                "opencode" => "OpenCode",
62                other => other,
63            }
64            .to_string(),
65        )
66    }
67
68    /// The trailers added when none are configured: none outside an agent;
69    /// inside one, the co-author line its vendor publishes (Claude Code
70    /// only, so far) and the AI disclosure.
71    pub fn default_trailers(&self) -> Vec<String> {
72        let Some(id) = self.id.as_deref() else {
73            return Vec::new();
74        };
75        let mut out = Vec::new();
76        if matches!(id, "claude-code" | "claude-cowork") {
77            out.push("Co-Authored-By: Claude <noreply@anthropic.com>".to_string());
78        }
79        out.push("AI-Assisted: Tool: {tool}; model: {model}; version: {version}".to_string());
80        out
81    }
82
83    /// Fills `{tool}`, `{model}` and `{version}` in a configured trailer.
84    pub fn expand(&self, template: &str) -> String {
85        let or = |v: Option<String>| v.unwrap_or_else(|| UNAVAILABLE.into());
86        template
87            .replace("{tool}", &or(self.tool()))
88            .replace("{model}", &or(self.model.clone()))
89            .replace("{version}", &or(self.version.clone()))
90    }
91}
92
93/// `claude-code_2-1-309_agent` is `claude-code`, version `2.1.309`, and
94/// `name@1.2.3` is `name`, version `1.2.3`. The value is free-form across
95/// vendors, so a word counts as the version only when it is digits separated
96/// by `-` or `.`.
97fn parse_ai_agent(raw: &str) -> (Option<String>, Option<String>) {
98    let (name, at_version) = match raw.split_once('@') {
99        Some((name, version)) => (name, Some(version)),
100        None => (raw, None),
101    };
102    let mut words = name.split('_');
103    let id = words
104        .next()
105        .map(|w| w.trim().to_ascii_lowercase())
106        .filter(|w| !w.is_empty() && !matches!(w.as_str(), "1" | "true" | "yes"));
107    let is_version = |w: &&str| {
108        w.starts_with(|c: char| c.is_ascii_digit())
109            && w.chars()
110                .all(|c| c.is_ascii_digit() || c == '-' || c == '.')
111    };
112    let version = at_version
113        .into_iter()
114        .chain(words)
115        .find(is_version)
116        .map(|w| w.replace('-', "."));
117    (id, version)
118}
119
120#[cfg(test)]
121mod tests {
122    use super::*;
123
124    fn agent(vars: &[(&str, &str)]) -> Agent {
125        let vars: Vec<(String, String)> = vars
126            .iter()
127            .map(|(k, v)| ((*k).to_string(), (*v).to_string()))
128            .collect();
129        Agent::from_lookup(|name| {
130            vars.iter()
131                .find(|(k, _)| k == name)
132                .map(|(_, v)| OsString::from(v))
133        })
134    }
135
136    #[test]
137    fn ai_agent_names_the_tool_and_version() {
138        let a = agent(&[("AI_AGENT", "claude-code_2-1-309_agent")]);
139        assert_eq!(a.id.as_deref(), Some("claude-code"));
140        assert_eq!(a.version.as_deref(), Some("2.1.309"));
141        assert_eq!(a.tool().as_deref(), Some("Claude Code"));
142        assert_eq!(a.model, None);
143        assert_eq!(
144            a.expand("Tool: {tool}; model: {model}; version: {version}"),
145            "Tool: Claude Code; model: unavailable; version: 2.1.309"
146        );
147    }
148
149    #[test]
150    fn a_vendor_marker_names_the_tool_without_a_version() {
151        let a = agent(&[("CODEX_SANDBOX", "seatbelt")]);
152        assert_eq!(a.id.as_deref(), Some("codex"));
153        assert_eq!(a.version, None);
154        let a = agent(&[("AI_AGENT", "codex"), ("JOUET_AI_MODEL", "openai/gpt-5")]);
155        assert_eq!(a.tool().as_deref(), Some("Codex"));
156        assert_eq!(a.model.as_deref(), Some("openai/gpt-5"));
157    }
158
159    #[test]
160    fn defaults_follow_the_agent() {
161        assert!(agent(&[]).default_trailers().is_empty());
162        let claude = agent(&[("AI_AGENT", "claude-code_2-1-309_agent")]);
163        assert_eq!(
164            claude.default_trailers(),
165            [
166                "Co-Authored-By: Claude <noreply@anthropic.com>",
167                "AI-Assisted: Tool: {tool}; model: {model}; version: {version}",
168            ]
169        );
170        let codex = agent(&[("AI_AGENT", "codex")]);
171        assert_eq!(codex.default_trailers().len(), 1);
172    }
173
174    #[test]
175    fn flag_like_values_name_no_tool() {
176        assert_eq!(parse_ai_agent("1"), (None, None));
177        assert_eq!(parse_ai_agent("opencode"), (Some("opencode".into()), None));
178        assert_eq!(
179            parse_ai_agent("some-agent_v2_x"),
180            (Some("some-agent".into()), None)
181        );
182        assert_eq!(
183            parse_ai_agent("pi@0.4.1"),
184            (Some("pi".into()), Some("0.4.1".into()))
185        );
186        let copilot = agent(&[("AI_AGENT", "github_copilot_vscode_agent")]);
187        assert_eq!(copilot.tool().as_deref(), Some("GitHub Copilot"));
188    }
189}