is-ai-agent 0.3.0

Detect whether a CLI is being invoked by an AI coding agent, and identify which one.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
//! Detect whether the current process is being invoked by an AI coding agent,
//! and identify which one.
//!
//! Detection order:
//! 1. The generic `AGENT` (agentsmd/agents.md#136) and `AI_AGENT`
//!    (@vercel/detect-agent) env vars, when their value names a known agent.
//! 2. Tool-specific env vars (`CLAUDECODE`, `CURSOR_AGENT`, ...).
//! 3. Filesystem signals (e.g. `/opt/.devin`).
//! 4. A bare truthy `AGENT`/`AI_AGENT` (e.g. `AGENT=1`) as a last resort,
//!    resolving to [`AgentId::Unknown`]. Tool-specific vars outrank it so
//!    agents that set both (e.g. OpenCode sets `AGENT=1` and `OPENCODE=1`)
//!    are still identified.
//!
//! ```no_run
//! if is_ai_agent::is_ai_agent() {
//!     // emit structured output
//! }
//!
//! if let Some(agent) = is_ai_agent::detect() {
//!     eprintln!("running under {}", agent.name);
//! }
//! ```

use std::env;
use std::path::Path;

/// A detected AI agent and the signal that revealed it.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Agent {
    pub id: AgentId,
    pub name: &'static str,
    pub signal: Signal,
}

/// Canonical identifier for a known agent, or `Unknown` when an agent is
/// present but its specific identity can't be determined (e.g. `AGENT=1`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum AgentId {
    ClaudeCode,
    Cursor,
    CursorCli,
    GeminiCli,
    Codex,
    Augment,
    Cline,
    OpenCode,
    Trae,
    Goose,
    Amp,
    Devin,
    Replit,
    Antigravity,
    GitHubCopilot,
    Crush,
    QwenCode,
    IflowCli,
    AmazonQCli,
    RooCode,
    Unknown,
}

impl AgentId {
    /// A stable, URL-safe lowercase slug for this agent.
    ///
    /// These slugs round-trip through the `AGENT` env var convention:
    /// setting `AGENT=<slug>` will be classified back to the same `AgentId`.
    pub fn as_str(&self) -> &'static str {
        match self {
            AgentId::ClaudeCode => "claude-code",
            AgentId::Cursor => "cursor",
            AgentId::CursorCli => "cursor-cli",
            AgentId::GeminiCli => "gemini-cli",
            AgentId::Codex => "codex",
            AgentId::Augment => "augment",
            AgentId::Cline => "cline",
            AgentId::OpenCode => "opencode",
            AgentId::Trae => "trae",
            AgentId::Goose => "goose",
            AgentId::Amp => "amp",
            AgentId::Devin => "devin",
            AgentId::Replit => "replit",
            AgentId::Antigravity => "antigravity",
            AgentId::GitHubCopilot => "github-copilot",
            AgentId::Crush => "crush",
            AgentId::QwenCode => "qwen-code",
            AgentId::IflowCli => "iflow-cli",
            AgentId::AmazonQCli => "amazon-q-cli",
            AgentId::RooCode => "roo-code",
            AgentId::Unknown => "unknown",
        }
    }
}

/// What signal triggered the detection.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Signal {
    EnvVar { name: &'static str, value: String },
    File { path: &'static str },
}

const TOOL_VARS: &[(&str, AgentId, &str)] = &[
    // Amp sets CLAUDECODE=1 for compatibility, so its own marker must be
    // checked before Claude Code's.
    ("AMP_CURRENT_THREAD_ID", AgentId::Amp, "Amp"),
    ("CLAUDECODE", AgentId::ClaudeCode, "Claude Code"),
    ("CLAUDE_CODE_ENTRYPOINT", AgentId::ClaudeCode, "Claude Code"),
    ("CLAUDE_CODE_SESSION_ID", AgentId::ClaudeCode, "Claude Code"),
    ("CLAUDE_CODE_EXECPATH", AgentId::ClaudeCode, "Claude Code"),
    // Set by both the Cursor CLI and the IDE's agent terminals, so it only
    // proves "some Cursor agent surface", not specifically the CLI.
    ("CURSOR_AGENT", AgentId::Cursor, "Cursor"),
    ("CURSOR_SANDBOX", AgentId::CursorCli, "Cursor CLI"),
    // Qwen Code is a Gemini CLI fork; its marker must precede Gemini's.
    ("QWEN_CODE", AgentId::QwenCode, "Qwen Code"),
    ("GEMINI_CLI", AgentId::GeminiCli, "Gemini CLI"),
    ("CODEX_THREAD_ID", AgentId::Codex, "OpenAI Codex"),
    ("CODEX_SANDBOX", AgentId::Codex, "OpenAI Codex"),
    (
        "CODEX_SANDBOX_NETWORK_DISABLED",
        AgentId::Codex,
        "OpenAI Codex",
    ),
    ("CODEX_CI", AgentId::Codex, "OpenAI Codex"),
    ("ANTIGRAVITY_AGENT", AgentId::Antigravity, "Antigravity"),
    ("AUGMENT_AGENT", AgentId::Augment, "Augment"),
    ("CLINE_ACTIVE", AgentId::Cline, "Cline"),
    ("ROO_ACTIVE", AgentId::RooCode, "Roo Code"),
    ("CRUSH", AgentId::Crush, "Crush"),
    ("IFLOW_CLI", AgentId::IflowCli, "iFlow CLI"),
    ("OPENCODE", AgentId::OpenCode, "OpenCode"),
    ("OPENCODE_PID", AgentId::OpenCode, "OpenCode"),
    // No longer set in plain CLI/TUI use (only acp/desktop embeddings).
    ("OPENCODE_CLIENT", AgentId::OpenCode, "OpenCode"),
    ("TRAE_AI_SHELL_ID", AgentId::Trae, "TRAE AI"),
    ("GOOSE_TERMINAL", AgentId::Goose, "Goose"),
    ("REPL_ID", AgentId::Replit, "Replit"),
    (
        "COPILOT_AGENT_SESSION_ID",
        AgentId::GitHubCopilot,
        "GitHub Copilot",
    ),
    // Inherited user config rather than injected markers — weaker signals.
    ("COPILOT_MODEL", AgentId::GitHubCopilot, "GitHub Copilot"),
    (
        "COPILOT_ALLOW_ALL",
        AgentId::GitHubCopilot,
        "GitHub Copilot",
    ),
    (
        "COPILOT_GITHUB_TOKEN",
        AgentId::GitHubCopilot,
        "GitHub Copilot",
    ),
];

const FILE_SIGNALS: &[(&str, AgentId, &str)] = &[("/opt/.devin", AgentId::Devin, "Devin")];

/// Returns `true` if any AI agent signal is present.
pub fn is_ai_agent() -> bool {
    detect().is_some()
}

/// Detect the AI agent, if any.
pub fn detect() -> Option<Agent> {
    detect_with(|name| env::var(name).ok(), |path| Path::new(path).exists())
}

/// Detection with injectable lookups, useful for tests and for callers that
/// want to consult a captured environment instead of the live process.
pub fn detect_with<E, F>(env: E, file_exists: F) -> Option<Agent>
where
    E: Fn(&str) -> Option<String>,
    F: Fn(&str) -> bool,
{
    // Generic vars win outright when they name a known agent. A bare truthy
    // value (`AGENT=1`) only proves *an* agent is present, so it is held as
    // a fallback while the more specific signals below get a chance to
    // identify the tool — e.g. OpenCode sets both AGENT=1 and OPENCODE=1.
    let mut generic_fallback = None;
    for var in ["AGENT", "AI_AGENT"] {
        if let Some(value) = nonempty(env(var)) {
            let (id, name) = classify_agent_value(agent_name_part(&value));
            let agent = Agent {
                id,
                name,
                signal: Signal::EnvVar { name: var, value },
            };
            if id != AgentId::Unknown {
                return Some(agent);
            }
            if generic_fallback.is_none() {
                generic_fallback = Some(agent);
            }
        }
    }

    // Special-cased value match: Cursor's extension host signals an agent
    // execution context only when the value equals "agent-exec".
    if let Some(value) = nonempty(env("CURSOR_EXTENSION_HOST_ROLE"))
        && value.trim() == "agent-exec"
    {
        return Some(Agent {
            id: AgentId::CursorCli,
            name: "Cursor CLI",
            signal: Signal::EnvVar {
                name: "CURSOR_EXTENSION_HOST_ROLE",
                value,
            },
        });
    }

    // Special-cased combination match: older Cursor builds (pre ~v3.7) set
    // CURSOR_TRACE_ID in every integrated terminal, including interactive
    // human sessions. Agent mode is distinguished by the PAGER override
    // Cursor applies when running commands itself.
    if let Some(value) = nonempty(env("CURSOR_TRACE_ID"))
        && env("PAGER").as_deref() == Some("head -n 10000 | cat")
    {
        return Some(Agent {
            id: AgentId::Cursor,
            name: "Cursor",
            signal: Signal::EnvVar {
                name: "CURSOR_TRACE_ID",
                value,
            },
        });
    }

    // Special-cased substring match: Amazon Q Developer CLI appends itself
    // to AWS_EXECUTION_ENV (e.g. "AmazonQ-For-CLI Version/1.16.0"), a var
    // that other AWS runtimes also set.
    if let Some(value) = nonempty(env("AWS_EXECUTION_ENV"))
        && value.contains("AmazonQ-For-CLI")
    {
        return Some(Agent {
            id: AgentId::AmazonQCli,
            name: "Amazon Q Developer CLI",
            signal: Signal::EnvVar {
                name: "AWS_EXECUTION_ENV",
                value,
            },
        });
    }

    for &(var, id, name) in TOOL_VARS {
        if let Some(value) = nonempty(env(var)) {
            return Some(Agent {
                id,
                name,
                signal: Signal::EnvVar { name: var, value },
            });
        }
    }

    for &(path, id, name) in FILE_SIGNALS {
        if file_exists(path) {
            return Some(Agent {
                id,
                name,
                signal: Signal::File { path },
            });
        }
    }

    generic_fallback
}

fn nonempty(v: Option<String>) -> Option<String> {
    v.filter(|s| !s.is_empty())
}

/// Extract the agent name from a generic var value. Strips the version
/// suffixes in the wild: `name@version` (Vercel's @vercel/detect-agent
/// convention, e.g. `v0@1.2.3`) and `name_version_surface` (Claude Code's
/// AI_AGENT shape, e.g. `claude-code_2.1.0_cli`).
fn agent_name_part(value: &str) -> &str {
    let name = value.trim();
    let name = name.split('@').next().unwrap_or(name);
    name.split('_').next().unwrap_or(name)
}

fn classify_agent_value(value: &str) -> (AgentId, &'static str) {
    match value.trim().to_ascii_lowercase().as_str() {
        "goose" => (AgentId::Goose, "Goose"),
        "amp" => (AgentId::Amp, "Amp"),
        "claude" | "claude-code" | "claudecode" => (AgentId::ClaudeCode, "Claude Code"),
        "cursor" => (AgentId::Cursor, "Cursor"),
        "cursor-cli" => (AgentId::CursorCli, "Cursor CLI"),
        "gemini" | "gemini-cli" => (AgentId::GeminiCli, "Gemini CLI"),
        "codex" => (AgentId::Codex, "OpenAI Codex"),
        "augment" | "augment-cli" => (AgentId::Augment, "Augment"),
        "cline" => (AgentId::Cline, "Cline"),
        "opencode" => (AgentId::OpenCode, "OpenCode"),
        "trae" => (AgentId::Trae, "TRAE AI"),
        "devin" => (AgentId::Devin, "Devin"),
        "replit" => (AgentId::Replit, "Replit"),
        "antigravity" => (AgentId::Antigravity, "Antigravity"),
        "github-copilot" | "github-copilot-cli" => (AgentId::GitHubCopilot, "GitHub Copilot"),
        "crush" => (AgentId::Crush, "Crush"),
        "qwen" | "qwen-code" | "qwencode" => (AgentId::QwenCode, "Qwen Code"),
        "iflow" | "iflow-cli" => (AgentId::IflowCli, "iFlow CLI"),
        "amazonq" | "amazon-q" | "amazon-q-cli" => (AgentId::AmazonQCli, "Amazon Q Developer CLI"),
        "roo" | "roo-code" | "roocode" => (AgentId::RooCode, "Roo Code"),
        _ => (AgentId::Unknown, "AI agent"),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashMap;

    fn env_from(pairs: &[(&str, &str)]) -> impl Fn(&str) -> Option<String> + use<> {
        let map: HashMap<String, String> = pairs
            .iter()
            .map(|(k, v)| ((*k).to_string(), (*v).to_string()))
            .collect();
        move |name| map.get(name).cloned()
    }

    #[test]
    fn returns_none_when_nothing_set() {
        let env = env_from(&[]);
        assert!(detect_with(env, |_| false).is_none());
    }

    #[test]
    fn agent_var_with_known_name_classifies() {
        let env = env_from(&[("AGENT", "goose")]);
        let agent = detect_with(env, |_| false).unwrap();
        assert_eq!(agent.id, AgentId::Goose);
        assert_eq!(
            agent.signal,
            Signal::EnvVar {
                name: "AGENT",
                value: "goose".to_string()
            }
        );
    }

    #[test]
    fn agent_var_normalizes_case_and_aliases() {
        let env = env_from(&[("AGENT", "Claude-Code")]);
        assert_eq!(detect_with(env, |_| false).unwrap().id, AgentId::ClaudeCode);
    }

    #[test]
    fn agent_var_with_truthy_value_is_unknown() {
        let env = env_from(&[("AGENT", "1")]);
        let agent = detect_with(env, |_| false).unwrap();
        assert_eq!(agent.id, AgentId::Unknown);
        assert_eq!(agent.name, "AI agent");
    }

    #[test]
    fn agent_var_takes_priority_over_tool_var() {
        let env = env_from(&[("AGENT", "amp"), ("CLAUDECODE", "1")]);
        assert_eq!(detect_with(env, |_| false).unwrap().id, AgentId::Amp);
    }

    #[test]
    fn tool_var_falls_back_when_agent_unset() {
        let env = env_from(&[("CURSOR_AGENT", "1")]);
        let agent = detect_with(env, |_| false).unwrap();
        assert_eq!(agent.id, AgentId::Cursor);
        assert_eq!(
            agent.signal,
            Signal::EnvVar {
                name: "CURSOR_AGENT",
                value: "1".to_string()
            }
        );
    }

    #[test]
    fn empty_var_value_is_ignored() {
        let env = env_from(&[("AGENT", ""), ("CLAUDECODE", "1")]);
        assert_eq!(detect_with(env, |_| false).unwrap().id, AgentId::ClaudeCode);
    }

    #[test]
    fn devin_marker_file_detected() {
        let env = env_from(&[]);
        let agent = detect_with(env, |p| p == "/opt/.devin").unwrap();
        assert_eq!(agent.id, AgentId::Devin);
        assert_eq!(
            agent.signal,
            Signal::File {
                path: "/opt/.devin"
            }
        );
    }

    #[test]
    fn env_vars_take_priority_over_files() {
        let env = env_from(&[("CLAUDECODE", "1")]);
        assert_eq!(detect_with(env, |_| true).unwrap().id, AgentId::ClaudeCode);
    }

    #[test]
    fn claude_code_sibling_vars_detected() {
        for var in [
            "CLAUDE_CODE_ENTRYPOINT",
            "CLAUDE_CODE_SESSION_ID",
            "CLAUDE_CODE_EXECPATH",
        ] {
            let env = env_from(&[(var, "x")]);
            let agent = detect_with(env, |_| false).unwrap();
            assert_eq!(agent.id, AgentId::ClaudeCode, "var={var}");
        }
    }

    #[test]
    fn ai_agent_var_with_known_name_classifies() {
        let env = env_from(&[("AI_AGENT", "crush")]);
        let agent = detect_with(env, |_| false).unwrap();
        assert_eq!(agent.id, AgentId::Crush);
        assert_eq!(
            agent.signal,
            Signal::EnvVar {
                name: "AI_AGENT",
                value: "crush".to_string()
            }
        );
    }

    #[test]
    fn ai_agent_var_strips_version_suffixes() {
        // Claude Code's shape: name_version_surface.
        let env = env_from(&[("AI_AGENT", "claude-code_2.1.0_cli")]);
        assert_eq!(detect_with(env, |_| false).unwrap().id, AgentId::ClaudeCode);

        // Vercel's @vercel/detect-agent shape: name@version.
        let env = env_from(&[("AI_AGENT", "goose@1.2.3")]);
        assert_eq!(detect_with(env, |_| false).unwrap().id, AgentId::Goose);
    }

    #[test]
    fn truthy_agent_var_defers_to_tool_vars() {
        // OpenCode sets AGENT=1 alongside its own markers; the specific
        // marker must win over the generic truthy value.
        let env = env_from(&[("AGENT", "1"), ("OPENCODE", "1")]);
        let agent = detect_with(env, |_| false).unwrap();
        assert_eq!(agent.id, AgentId::OpenCode);
        assert_eq!(
            agent.signal,
            Signal::EnvVar {
                name: "OPENCODE",
                value: "1".to_string()
            }
        );
    }

    #[test]
    fn truthy_agent_var_defers_to_file_signals() {
        let env = env_from(&[("AGENT", "true")]);
        let agent = detect_with(env, |p| p == "/opt/.devin").unwrap();
        assert_eq!(agent.id, AgentId::Devin);
    }

    #[test]
    fn truthy_ai_agent_var_is_unknown_fallback() {
        let env = env_from(&[("AI_AGENT", "1")]);
        let agent = detect_with(env, |_| false).unwrap();
        assert_eq!(agent.id, AgentId::Unknown);
        assert_eq!(
            agent.signal,
            Signal::EnvVar {
                name: "AI_AGENT",
                value: "1".to_string()
            }
        );
    }

    #[test]
    fn amp_marker_outranks_claudecode_compat_var() {
        // Amp sets CLAUDECODE=1 for compatibility.
        let env = env_from(&[("AMP_CURRENT_THREAD_ID", "t-1"), ("CLAUDECODE", "1")]);
        assert_eq!(detect_with(env, |_| false).unwrap().id, AgentId::Amp);
    }

    #[test]
    fn qwen_code_outranks_gemini_cli_var() {
        // Qwen Code is a Gemini CLI fork.
        let env = env_from(&[("QWEN_CODE", "1"), ("GEMINI_CLI", "1")]);
        assert_eq!(detect_with(env, |_| false).unwrap().id, AgentId::QwenCode);
    }

    #[test]
    fn new_tool_vars_detected() {
        for (var, expected) in [
            ("CRUSH", AgentId::Crush),
            ("QWEN_CODE", AgentId::QwenCode),
            ("IFLOW_CLI", AgentId::IflowCli),
            ("ROO_ACTIVE", AgentId::RooCode),
            ("OPENCODE", AgentId::OpenCode),
            ("OPENCODE_PID", AgentId::OpenCode),
            ("CURSOR_SANDBOX", AgentId::CursorCli),
            ("CODEX_SANDBOX_NETWORK_DISABLED", AgentId::Codex),
            ("AMP_CURRENT_THREAD_ID", AgentId::Amp),
            ("COPILOT_AGENT_SESSION_ID", AgentId::GitHubCopilot),
        ] {
            let env = env_from(&[(var, "1")]);
            let agent = detect_with(env, |_| false).unwrap();
            assert_eq!(agent.id, expected, "var={var}");
        }
    }

    #[test]
    fn amazon_q_detected_via_aws_execution_env_substring() {
        let env = env_from(&[("AWS_EXECUTION_ENV", "AmazonQ-For-CLI Version/1.16.0")]);
        let agent = detect_with(env, |_| false).unwrap();
        assert_eq!(agent.id, AgentId::AmazonQCli);
    }

    #[test]
    fn aws_execution_env_without_amazon_q_ignored() {
        let env = env_from(&[("AWS_EXECUTION_ENV", "AWS_Lambda_nodejs22.x")]);
        assert!(detect_with(env, |_| false).is_none());
    }

    #[test]
    fn cursor_trace_id_with_pager_override_detected() {
        let env = env_from(&[
            ("CURSOR_TRACE_ID", "abc123"),
            ("PAGER", "head -n 10000 | cat"),
        ]);
        let agent = detect_with(env, |_| false).unwrap();
        assert_eq!(agent.id, AgentId::Cursor);
        assert_eq!(
            agent.signal,
            Signal::EnvVar {
                name: "CURSOR_TRACE_ID",
                value: "abc123".to_string()
            }
        );
    }

    #[test]
    fn cursor_trace_id_alone_is_interactive_not_agent() {
        // Older Cursor builds set CURSOR_TRACE_ID for human terminal
        // sessions too; without the agent-mode PAGER override it must not
        // count as an agent.
        let env = env_from(&[("CURSOR_TRACE_ID", "abc123")]);
        assert!(detect_with(env, |_| false).is_none());
    }

    #[test]
    fn cursor_agent_var_maps_to_generic_cursor() {
        // CURSOR_AGENT is set by both the CLI and the IDE's agent terminals.
        let env = env_from(&[("CURSOR_AGENT", "1")]);
        let agent = detect_with(env, |_| false).unwrap();
        assert_eq!(agent.id, AgentId::Cursor);
        assert_eq!(agent.name, "Cursor");
    }

    #[test]
    fn cursor_cli_detected_via_extension_host_role() {
        let env = env_from(&[("CURSOR_EXTENSION_HOST_ROLE", "agent-exec")]);
        let agent = detect_with(env, |_| false).unwrap();
        assert_eq!(agent.id, AgentId::CursorCli);
    }

    #[test]
    fn cursor_extension_host_role_other_value_ignored() {
        let env = env_from(&[("CURSOR_EXTENSION_HOST_ROLE", "ui")]);
        assert!(detect_with(env, |_| false).is_none());
    }

    #[test]
    fn codex_alternate_signals_detected() {
        for var in ["CODEX_SANDBOX", "CODEX_CI", "CODEX_THREAD_ID"] {
            let env = env_from(&[(var, "1")]);
            let agent = detect_with(env, |_| false).unwrap();
            assert_eq!(agent.id, AgentId::Codex, "var={var}");
        }
    }

    #[test]
    fn antigravity_detected() {
        let env = env_from(&[("ANTIGRAVITY_AGENT", "1")]);
        assert_eq!(
            detect_with(env, |_| false).unwrap().id,
            AgentId::Antigravity
        );
    }

    #[test]
    fn replit_detected() {
        let env = env_from(&[("REPL_ID", "x")]);
        assert_eq!(detect_with(env, |_| false).unwrap().id, AgentId::Replit);
    }

    #[test]
    fn github_copilot_detected_via_each_var() {
        for var in ["COPILOT_MODEL", "COPILOT_ALLOW_ALL", "COPILOT_GITHUB_TOKEN"] {
            let env = env_from(&[(var, "1")]);
            let agent = detect_with(env, |_| false).unwrap();
            assert_eq!(agent.id, AgentId::GitHubCopilot, "var={var}");
        }
    }

    #[test]
    fn as_str_returns_url_safe_slug() {
        assert_eq!(AgentId::ClaudeCode.as_str(), "claude-code");
        assert_eq!(AgentId::CursorCli.as_str(), "cursor-cli");
        assert_eq!(AgentId::GitHubCopilot.as_str(), "github-copilot");
        assert_eq!(AgentId::Goose.as_str(), "goose");
        assert_eq!(AgentId::Unknown.as_str(), "unknown");
    }

    #[test]
    fn as_str_round_trips_through_agent_var() {
        for id in [
            AgentId::ClaudeCode,
            AgentId::Cursor,
            AgentId::CursorCli,
            AgentId::GeminiCli,
            AgentId::Codex,
            AgentId::Augment,
            AgentId::Cline,
            AgentId::OpenCode,
            AgentId::Trae,
            AgentId::Goose,
            AgentId::Amp,
            AgentId::Devin,
            AgentId::Replit,
            AgentId::Antigravity,
            AgentId::GitHubCopilot,
            AgentId::Crush,
            AgentId::QwenCode,
            AgentId::IflowCli,
            AgentId::AmazonQCli,
            AgentId::RooCode,
        ] {
            let slug = id.as_str();
            let env = env_from(&[("AGENT", slug)]);
            assert_eq!(
                detect_with(env, |_| false).unwrap().id,
                id,
                "slug {slug} did not round-trip"
            );
        }
    }

    #[test]
    fn agent_var_classifies_new_names() {
        for (val, expected) in [
            ("replit", AgentId::Replit),
            ("antigravity", AgentId::Antigravity),
            ("github-copilot", AgentId::GitHubCopilot),
            ("github-copilot-cli", AgentId::GitHubCopilot),
            ("cursor-cli", AgentId::CursorCli),
            ("augment-cli", AgentId::Augment),
            ("crush", AgentId::Crush),
            ("qwen", AgentId::QwenCode),
            ("iflow", AgentId::IflowCli),
            ("amazonq", AgentId::AmazonQCli),
            ("roo", AgentId::RooCode),
        ] {
            let env = env_from(&[("AGENT", val)]);
            assert_eq!(
                detect_with(env, |_| false).unwrap().id,
                expected,
                "val={val}"
            );
        }
    }
}