1use std::ffi::OsString;
11
12const UNAVAILABLE: &str = "unavailable";
13
14#[derive(Debug, Clone, Default, PartialEq, Eq)]
15pub struct Agent {
16 pub id: Option<String>,
18 pub version: Option<String>,
19 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 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 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 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 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
93fn 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}