link-assistant-router 0.95.0

Link.Assistant.Router — Claude MAX OAuth proxy and token gateway for Anthropic APIs
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
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
//! Temporary-by-default launcher shared by `router with` and `with-router`.

use std::ffi::OsString;
use std::fs::{self, OpenOptions};
use std::io::Write as _;
use std::path::Path;
#[cfg(unix)]
use std::process::Stdio;
use std::process::{Command, ExitCode};
use std::time::Duration;

use serde_json::json;

use crate::cli::WithArgs;
use crate::clients::{ClientIsolation, ClientKind, ClientManager, RouterModel};
use crate::managed_server::{
    cleanup_run_credential, ensure_model_available, prepare_run_credential, resolve,
};

type AnyError = Box<dyn std::error::Error + Send + Sync>;

/// Execute one wrapper invocation and preserve the client's exit status.
pub async fn run(args: &WithArgs) -> ExitCode {
    match run_inner(args).await {
        Ok(code) => code,
        Err(error) => {
            eprintln!("error: {error}");
            ExitCode::from(1)
        }
    }
}

async fn run_inner(args: &WithArgs) -> Result<ExitCode, AnyError> {
    if args.undo {
        crate::client_global::undo(args.client)?;
        return Ok(ExitCode::SUCCESS);
    }
    if args.client.integration().isolation == ClientIsolation::Unsupported {
        return Err(args
            .client
            .setup_limitation()
            .unwrap_or("client integration is unsupported")
            .into());
    }
    let explicit_token = if args.token_stdin {
        Some(crate::server_command::read_token()?)
    } else {
        args.token.clone()
    };
    let server = resolve(
        args.server.as_deref(),
        explicit_token,
        args.run_max_requests,
    )
    .await?;
    if args.global {
        if server.source == "managed local container" {
            crate::managed_server::start_managed()?;
        }
        if !matches!(
            args.client,
            ClientKind::Opencode | ClientKind::QwenCode | ClientKind::Agent
        ) {
            crate::client_global::configure(args.client, &server.base_url, &[])?;
            return Ok(ExitCode::SUCCESS);
        }
    }
    let working_directory = std::env::current_dir()
        .ok()
        .and_then(|path| {
            path.file_name()
                .map(|name| name.to_string_lossy().into_owned())
        })
        .unwrap_or_else(|| "unknown-workdir".to_string());
    let label = format!("with-{}-{working_directory}", args.client);
    let credential = prepare_run_credential(&server, &label, args.run_ttl_hours).await?;
    if args.global {
        let configured =
            crate::client_global::configure(args.client, &server.base_url, credential.models());
        let cleanup = cleanup_run_credential(credential).await;
        configured?;
        if let Err(error) = cleanup {
            eprintln!("warning: {error}; the short token TTL remains the cleanup backstop");
        }
        return Ok(ExitCode::SUCCESS);
    }
    // Resolve the concrete model from the live catalog rather than a name
    // compiled into the router (issue #192).
    let owner = args.client.integration().model_owner;
    let selected = if let Some(model) = args.model.clone() {
        model
    } else if let Some(model) = credential.select_model(owner) {
        model.to_string()
    } else {
        // Name what the catalog *does* hold: "only openai models" is a much
        // shorter path to the real cause — a lapsed subscription — than the
        // unrecognised-model error the client would otherwise report about
        // itself (issue #225).
        let advertised = credential.advertised_owners();
        let holdings = if advertised.is_empty() {
            "the catalog is empty".to_string()
        } else {
            format!("it advertises only {} models", advertised.join(", "))
        };
        cleanup_after_setup_failure(credential).await;
        return Err(format!(
            "the router advertises no model for {} ({owner} models): {holdings}. Authorize a \
             matching subscription on the router host, or pass --model explicitly",
            args.client.integration().name
        )
        .into());
    };
    let model = selected.as_str();
    if let Err(error) = ensure_model_available(&credential, model) {
        cleanup_after_setup_failure(credential).await;
        return Err(error);
    }
    let temporary = match TemporaryClient::prepare(
        args.client,
        &server.base_url,
        &credential.token,
        Some(model),
        credential.models(),
    ) {
        Ok(temporary) => temporary,
        Err(error) => {
            cleanup_after_setup_failure(credential).await;
            return Err(error);
        }
    };
    let arguments = client_arguments(args, model);
    let launch = temporary.launch(&arguments).await;
    if launch.as_ref().is_ok_and(|status| !status.success())
        && server.source == "managed local container"
        && let Some(hint) = crate::managed_server::managed_failure_hint()
    {
        eprintln!("warning: {hint}");
    }
    let cleanup = cleanup_run_credential(credential).await;
    let status = launch?;
    if let Err(error) = cleanup {
        eprintln!("warning: {error}; the short token TTL remains the cleanup backstop");
    }
    Ok(exit_code(status))
}

async fn cleanup_after_setup_failure(credential: crate::managed_server::RunCredential) {
    if let Err(error) = cleanup_run_credential(credential).await {
        eprintln!("warning: {error}; the short token TTL remains the cleanup backstop");
    }
}

struct TemporaryClient {
    directory: tempfile::TempDir,
    command: Command,
}

impl TemporaryClient {
    fn prepare(
        client: ClientKind,
        base_url: &str,
        token: &str,
        model_override: Option<&str>,
        models: &[RouterModel],
    ) -> Result<Self, AnyError> {
        sweep_stale_directories();
        let prefix = format!("link-assistant-router-with-{}-", std::process::id());
        let directory = tempfile::Builder::new().prefix(&prefix).tempdir()?;
        set_directory_owner_only(directory.path())?;
        let manager = ClientManager::isolated(directory.path());
        match client {
            ClientKind::GeminiCli => write_gemini_settings(&manager.config_path(client))?,
            ClientKind::Cursor => {
                return Err(client
                    .setup_limitation()
                    .unwrap_or("Cursor is unsupported")
                    .into());
            }
            _ => {
                manager.setup(client, base_url, models)?;
            }
        }
        let integration = client.integration();
        let mut command = Command::new(integration.command);
        configure_isolation(&mut command, &manager, directory.path(), client)?;
        if let Some(token_env) = integration.token_env {
            command.env(token_env, token);
        }
        if let Some(base_env) = integration.base_url_env {
            command.env(base_env, endpoint(base_url, integration.endpoint_suffix));
        }
        let model = model_override.unwrap_or("");
        match client {
            ClientKind::ClaudeCode => {
                command
                    .env("ANTHROPIC_API_KEY", "")
                    .env("MAX_THINKING_TOKENS", "16384");
            }
            ClientKind::GeminiCli => {
                command
                    .env("GEMINI_DEFAULT_AUTH_TYPE", "gemini-api-key")
                    .env("GEMINI_CLI_TRUST_WORKSPACE", "true");
            }
            ClientKind::QwenCode => {
                command
                    .env("OPENAI_API_KEY", token)
                    .env("OPENAI_BASE_URL", endpoint(base_url, "/v1"))
                    .env("OPENAI_MODEL", model)
                    .env(
                        "OPENAI_REASONING_EFFORT",
                        integration.default_reasoning_effort,
                    );
            }
            ClientKind::Codex | ClientKind::GrokCli | ClientKind::Opencode | ClientKind::Agent => {
                command.env(
                    "OPENAI_REASONING_EFFORT",
                    integration.default_reasoning_effort,
                );
            }
            ClientKind::Cursor => {}
        }
        Ok(Self { directory, command })
    }

    async fn launch(
        mut self,
        arguments: &[OsString],
    ) -> Result<std::process::ExitStatus, AnyError> {
        debug_assert!(self.directory.path().is_dir());
        self.command.args(arguments);
        let program = self.command.get_program().to_string_lossy().into_owned();
        let mut child = tokio::process::Command::from(self.command)
            .kill_on_drop(true)
            .spawn()
            .map_err(|error| -> AnyError {
            if error.kind() == std::io::ErrorKind::NotFound {
                format!(
                    "client executable `{program}` is not installed or not on PATH; install {program} and retry"
                )
                .into()
            } else {
                format!("could not launch {program}: {error}").into()
            }
        })?;
        tokio::select! {
            result = child.wait() => result.map_err(Into::into),
            signal = tokio::signal::ctrl_c() => {
                signal.map_err(|error| format!("could not listen for Ctrl-C: {error}"))?;
                interrupt_child(&mut child).await
            }
        }
    }
}

async fn interrupt_child(
    child: &mut tokio::process::Child,
) -> Result<std::process::ExitStatus, AnyError> {
    #[cfg(unix)]
    if let Some(pid) = child.id() {
        let _ = std::process::Command::new("kill")
            .args(["-INT", &pid.to_string()])
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .status();
    }
    #[cfg(windows)]
    child.start_kill()?;
    if let Ok(result) = tokio::time::timeout(Duration::from_secs(5), child.wait()).await {
        result.map_err(Into::into)
    } else {
        child.start_kill()?;
        child.wait().await.map_err(Into::into)
    }
}

fn configure_isolation(
    command: &mut Command,
    manager: &ClientManager,
    root: &Path,
    client: ClientKind,
) -> Result<(), AnyError> {
    match client.integration().isolation {
        ClientIsolation::Home => {
            command
                .env("HOME", root)
                .env_remove("CODEX_HOME")
                .env_remove("QWEN_HOME");
        }
        ClientIsolation::ClaudeConfig => {
            let config_path = manager.config_path(client);
            let directory = config_path.parent().expect("Claude config has a parent");
            command.env("CLAUDE_CONFIG_DIR", directory);
        }
        ClientIsolation::GeminiHome => {
            // Gemini CLI resolves its settings as `<home>/.gemini/settings.json`,
            // where `<home>` is `GEMINI_CLI_HOME` if set and `$HOME` otherwise.
            // The router pointed `GEMINI_CLI_HOME` at the `.gemini` directory
            // itself, so the CLI looked in `<root>/.gemini/.gemini/` — found no
            // settings, fell back to the user's personal ones, and refused the
            // run with `Invalid auth method selected.` (issue #227).
            //
            // Both variables therefore name the *root*, and `HOME` is overridden
            // as well so nothing else the CLI stores escapes into the real home.
            command
                .env("HOME", root)
                .env("GEMINI_CLI_HOME", root)
                // With auth fixed the next wall is the trusted-directory
                // prompt, which a `--non-interactive` run cannot answer.
                .env("GEMINI_CLI_TRUST_WORKSPACE", "true");
        }
        ClientIsolation::ConfigFile => {
            let path = manager.config_path(client);
            if client == ClientKind::Opencode {
                command
                    .env("OPENCODE_CONFIG", &path)
                    .env("OPENCODE_CONFIG_DIR", path.parent().expect("config parent"));
            } else {
                command.env("HOME", root).env(
                    "LINK_ASSISTANT_AGENT_CONFIG_CONTENT",
                    fs::read_to_string(path)?,
                );
            }
        }
        ClientIsolation::Environment => {}
        ClientIsolation::Unsupported => return Err("unsupported client isolation".into()),
    }
    Ok(())
}

/// Build the wrapped client's argv.
///
/// `resolved_model` is the id chosen from the live catalog by the caller; it is
/// passed in rather than read from `args` because auto-selection leaves
/// `args.model` empty (issue #192).
fn client_arguments(args: &WithArgs, resolved_model: &str) -> Vec<OsString> {
    let integration = args.client.integration();
    let mut forwarded = args.client_args.clone();
    if forwarded.first().is_some_and(|value| value == "--") {
        forwarded.remove(0);
    }
    let non_interactive = args.non_interactive || (!args.interactive && !forwarded.is_empty());
    let mode = integration.non_interactive_arg;
    let has_mode = contains_native_mode(args.client, &forwarded);
    let model = (!contains_model_argument(&forwarded))
        .then_some(integration.model_arg)
        .flatten()
        .map(|flag| {
            let model = resolved_model;
            [
                OsString::from(flag),
                model_selector(args.client, model).into(),
            ]
        });
    let command_mode = matches!(args.client, ClientKind::Codex | ClientKind::Opencode);
    let mut result = Vec::new();
    if command_mode && has_mode {
        result.push(forwarded.remove(0));
    } else if command_mode
        && non_interactive
        && let Some(mode) = mode
    {
        result.push(mode.into());
        if args.client == ClientKind::Codex {
            result.push("--skip-git-repo-check".into());
        }
    }
    if let Some(model) = model {
        result.extend(model);
    }
    if args.client == ClientKind::Codex
        && !forwarded.iter().any(|argument| {
            argument
                .to_string_lossy()
                .contains("model_reasoning_effort")
        })
    {
        result.extend([
            OsString::from("-c"),
            OsString::from(format!(
                "model_reasoning_effort=\"{}\"",
                integration.default_reasoning_effort
            )),
        ]);
    }
    if !command_mode
        && non_interactive
        && !has_mode
        && let Some(mode) = mode
    {
        result.push(mode.into());
    }
    result.extend(forwarded);
    result
}

fn contains_native_mode(client: ClientKind, arguments: &[OsString]) -> bool {
    let Some(mode) = client.integration().non_interactive_arg else {
        return false;
    };
    if matches!(client, ClientKind::Codex | ClientKind::Opencode) {
        arguments.first().is_some_and(|argument| argument == mode)
    } else {
        arguments.iter().any(|argument| argument == mode)
    }
}

fn contains_model_argument(arguments: &[OsString]) -> bool {
    arguments.iter().any(|argument| {
        let argument = argument.to_string_lossy();
        matches!(argument.as_ref(), "-m" | "--model") || argument.starts_with("--model=")
    })
}

fn model_selector(client: ClientKind, model: &str) -> String {
    if matches!(client, ClientKind::Opencode | ClientKind::Agent) && !model.contains('/') {
        format!("link-assistant/{model}")
    } else {
        model.to_string()
    }
}

fn endpoint(base_url: &str, suffix: &str) -> String {
    format!("{}{}", base_url.trim_end_matches('/'), suffix)
}

fn write_gemini_settings(path: &Path) -> Result<(), AnyError> {
    let contents = format!(
        "{}\n",
        serde_json::to_string_pretty(&json!({
            "security": {"auth": {"selectedType": "gemini-api-key"}}
        }))?
    );
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent)?;
    }
    // Truncating, not `create_new`: an isolated run must be governed by the
    // settings the router wrote. Deferring to a pre-existing file would let an
    // inherited `oauth-personal` survive and fail the run (issue #227).
    let mut options = OpenOptions::new();
    options.create(true).truncate(true).write(true);
    #[cfg(unix)]
    {
        use std::os::unix::fs::OpenOptionsExt as _;
        options.mode(0o600);
    }
    let mut file = options.open(path)?;
    file.write_all(contents.as_bytes())?;
    Ok(())
}

fn sweep_stale_directories() {
    const PREFIX: &str = "link-assistant-router-with-";
    let Ok(entries) = fs::read_dir(std::env::temp_dir()) else {
        return;
    };
    for entry in entries.flatten() {
        let name = entry.file_name();
        let name = name.to_string_lossy();
        let Some(rest) = name.strip_prefix(PREFIX) else {
            continue;
        };
        let Some(pid) = rest.split('-').next().and_then(|value| value.parse().ok()) else {
            continue;
        };
        if !process_alive(pid) {
            let _ = fs::remove_dir_all(entry.path());
        }
    }
}

fn process_alive(pid: u32) -> bool {
    if pid == std::process::id() {
        return true;
    }
    #[cfg(unix)]
    {
        std::process::Command::new("kill")
            .args(["-0", &pid.to_string()])
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .status()
            .is_ok_and(|status| status.success())
    }
    #[cfg(windows)]
    {
        std::process::Command::new("tasklist")
            .args(["/FI", &format!("PID eq {pid}"), "/NH"])
            .output()
            .is_ok_and(|output| {
                output.status.success()
                    && String::from_utf8_lossy(&output.stdout).contains(&pid.to_string())
            })
    }
}

fn set_directory_owner_only(path: &Path) -> Result<(), std::io::Error> {
    #[cfg(not(unix))]
    let _ = path;
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt as _;
        fs::set_permissions(path, fs::Permissions::from_mode(0o700))?;
    }
    Ok(())
}

fn exit_code(status: std::process::ExitStatus) -> ExitCode {
    if let Some(code) = status.code() {
        return ExitCode::from(u8::try_from(code).unwrap_or(1));
    }
    #[cfg(unix)]
    {
        use std::os::unix::process::ExitStatusExt as _;
        ExitCode::from(
            status
                .signal()
                .and_then(|signal| u8::try_from(128 + signal).ok())
                .unwrap_or(1),
        )
    }
    #[cfg(not(unix))]
    ExitCode::from(1)
}

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

    fn arguments(client: ClientKind, client_args: &[&str]) -> Vec<String> {
        let args = WithArgs {
            global: false,
            undo: false,
            non_interactive: false,
            interactive: false,
            server: None,
            token: None,
            token_stdin: false,
            model: None,
            run_ttl_hours: 1,
            run_max_requests: None,
            client,
            client_args: client_args.iter().map(OsString::from).collect(),
        };
        client_arguments(&args, "")
            .iter()
            .map(|value| value.to_string_lossy().into_owned())
            .collect()
    }

    /// Gemini CLI resolves settings as `<home>/.gemini/settings.json`, where
    /// `<home>` is `GEMINI_CLI_HOME` if set and `$HOME` otherwise. Pointing
    /// `GEMINI_CLI_HOME` at the `.gemini` directory made it look one level too
    /// deep, fall back to the user's personal settings, and refuse the run
    /// (issue #227). Both variables must therefore name the root.
    #[test]
    fn the_gemini_client_is_pointed_at_the_isolated_home() {
        let root = tempfile::tempdir().expect("isolated root");
        let manager = ClientManager::isolated(root.path());
        let mut command = Command::new("gemini");
        configure_isolation(&mut command, &manager, root.path(), ClientKind::GeminiCli)
            .expect("configure gemini isolation");

        let environment: std::collections::HashMap<_, _> = command
            .get_envs()
            .filter_map(|(key, value)| Some((key.to_string_lossy().into_owned(), value?)))
            .collect();

        for name in ["HOME", "GEMINI_CLI_HOME"] {
            assert_eq!(
                environment.get(name).map(|value| value.to_string_lossy()),
                Some(root.path().to_string_lossy()),
                "{name} must name the isolated root, not the .gemini directory \
                 inside it — the CLI appends `.gemini` itself"
            );
        }
        // The file the CLI actually reads lives under that home.
        assert_eq!(
            manager.config_path(ClientKind::GeminiCli),
            root.path().join(".gemini/settings.json")
        );
        // The trusted-directory prompt cannot be answered non-interactively.
        assert_eq!(
            environment
                .get("GEMINI_CLI_TRUST_WORKSPACE")
                .map(|value| value.to_string_lossy()),
            Some(std::borrow::Cow::Borrowed("true"))
        );
    }

    /// End to end: after preparing the client, the file Gemini CLI actually
    /// reads must exist and select the API-key flow. The router previously
    /// wrote a correct file the CLI never opened (issue #227).
    #[test]
    fn a_prepared_gemini_run_leaves_settings_where_the_cli_reads_them() {
        let models = [RouterModel {
            id: "test-model".to_string(),
            owned_by: "test".to_string(),
        }];
        let temporary = TemporaryClient::prepare(
            ClientKind::GeminiCli,
            "http://router.test",
            "task-token",
            None,
            &models,
        )
        .expect("prepare gemini");
        let root = temporary.directory.path();
        let home = temporary
            .command
            .get_envs()
            .find_map(|(name, value)| (name == "HOME").then_some(value?))
            .expect("gemini run sets HOME");
        // The CLI resolves its settings from HOME; the file must be there.
        let settings = Path::new(home).join(".gemini/settings.json");
        assert!(
            settings.is_file(),
            "no settings at {}, which is where the CLI looks",
            settings.display()
        );
        let written = fs::read_to_string(&settings).expect("read settings");
        assert!(written.contains("gemini-api-key"), "{written}");
        assert!(Path::new(home).starts_with(root), "HOME escaped the root");
    }

    /// An isolated run must be governed by the settings the router wrote. The
    /// previous `create_new` silently deferred to whatever was already there,
    /// which with the `HOME` fix would let an inherited `oauth-personal`
    /// survive and fail the run.
    #[test]
    fn written_gemini_settings_replace_an_existing_file() {
        let root = tempfile::tempdir().expect("isolated root");
        let path = root.path().join(".gemini/settings.json");
        fs::create_dir_all(path.parent().expect("parent")).expect("create directory");
        fs::write(
            &path,
            r#"{"security":{"auth":{"selectedType":"oauth-personal"}}}"#,
        )
        .expect("seed a conflicting file");

        write_gemini_settings(&path).expect("write settings");

        let written = fs::read_to_string(&path).expect("read settings");
        assert!(written.contains("gemini-api-key"), "{written}");
        assert!(
            !written.contains("oauth-personal"),
            "the inherited value survived: {written}"
        );
    }

    /// The value itself is the one the CLI accepts; a wrong spelling is what
    /// produced the original error, so it is pinned rather than assumed.
    #[test]
    fn gemini_settings_select_the_api_key_flow() {
        let root = tempfile::tempdir().expect("isolated root");
        let path = root.path().join(".gemini/settings.json");
        write_gemini_settings(&path).expect("write settings");
        let written: serde_json::Value =
            serde_json::from_str(&fs::read_to_string(&path).expect("read")).expect("valid JSON");
        assert_eq!(
            written["security"]["auth"]["selectedType"],
            "gemini-api-key"
        );
    }

    #[test]
    fn colliding_wrapper_flags_after_client_are_forwarded() {
        let args = arguments(ClientKind::Codex, &["--global", "hi"]);
        assert!(args.ends_with(&["--global".to_string(), "hi".to_string()]));
        assert_eq!(args.first().map(String::as_str), Some("exec"));
    }

    #[test]
    fn explicit_separator_is_not_forwarded() {
        let args = arguments(ClientKind::Opencode, &["--", "run", "hi"]);
        assert_eq!(args.first().map(String::as_str), Some("run"));
        assert_eq!(args.iter().filter(|arg| arg.as_str() == "run").count(), 1);
    }

    #[test]
    fn command_mode_word_inside_prompt_is_not_treated_as_the_subcommand() {
        let args = arguments(ClientKind::Opencode, &["explain", "run"]);
        assert_eq!(args.first().map(String::as_str), Some("run"));
        assert!(args.ends_with(&["explain".to_string(), "run".to_string()]));
    }

    #[test]
    fn every_supported_client_prepares_below_a_disposable_root() {
        let models = [RouterModel {
            id: "test-model".to_string(),
            owned_by: "test".to_string(),
        }];
        for client in ClientKind::ALL {
            if client == ClientKind::Cursor {
                assert!(
                    TemporaryClient::prepare(
                        client,
                        "http://router.test",
                        "task-token",
                        None,
                        &models,
                    )
                    .is_err()
                );
                continue;
            }
            let temporary =
                TemporaryClient::prepare(client, "http://router.test", "task-token", None, &models)
                    .unwrap_or_else(|error| panic!("{client} failed temporary setup: {error}"));
            let root = temporary.directory.path().to_path_buf();
            assert_eq!(temporary.command.get_program(), client.command());
            let environment = temporary
                .command
                .get_envs()
                .filter_map(|(name, value)| value.map(|value| (name, value)))
                .collect::<std::collections::HashMap<_, _>>();
            if let Some(token_env) = client.token_env() {
                assert_eq!(
                    environment.get(std::ffi::OsStr::new(token_env)).copied(),
                    Some(std::ffi::OsStr::new("task-token")),
                    "{client} did not receive its token environment"
                );
            }
            for name in [
                "HOME",
                "CLAUDE_CONFIG_DIR",
                "GEMINI_CLI_HOME",
                "OPENCODE_CONFIG",
                "OPENCODE_CONFIG_DIR",
            ] {
                if let Some(value) = environment.get(std::ffi::OsStr::new(name)) {
                    assert!(
                        Path::new(value).starts_with(&root),
                        "{client} {name} escaped the temporary root"
                    );
                }
            }
            drop(temporary);
            assert!(!root.exists(), "{client} temporary root survived drop");
        }
    }

    #[test]
    fn registry_order_matches_client_discriminants() {
        for client in ClientKind::ALL {
            assert_eq!(client.integration().kind, client);
        }
    }
}