link-assistant-router 0.68.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
//! Safe local configuration for agentic CLI clients.
//!
//! The writer deliberately owns only one Codex provider table and one Claude
//! Code environment key. Unknown settings are parsed and merged, never
//! replaced wholesale, and every changed existing file is backed up first.

use std::fmt;
use std::fs::{self, OpenOptions};
use std::io::Write;
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};

use clap::ValueEnum;
use serde::Serialize;
use serde_json::{Value, json};
use toml_edit::{DocumentMut, Item, Table, value};

mod json_config;

use json_config::{read_json_provider_base_url, read_qwen_base_url};

const CODEX_PROVIDER: &str = "link-assistant";
const CODEX_TOKEN_ENV: &str = "LINK_ASSISTANT_TOKEN";
const CLAUDE_TOKEN_ENV: &str = "ANTHROPIC_AUTH_TOKEN";
const CLAUDE_BASE_ENV: &str = "ANTHROPIC_BASE_URL";
const ROUTER_TOKEN_ENV: &str = "LINK_ASSISTANT_TOKEN";
const GROK_TOKEN_ENV: &str = "GROK_API_KEY";
const GROK_BASE_ENV: &str = "GROK_BASE_URL";
const ROUTER_PROVIDER: &str = "link-assistant";
const OWNERSHIP_MARKER: &str = ".link-assistant-router-client.json";

/// Documented local clients, including clients whose vendor gates prevent setup.
#[derive(Clone, Copy, Debug, Eq, PartialEq, ValueEnum)]
pub enum ClientKind {
    Codex,
    ClaudeCode,
    Cursor,
    GeminiCli,
    GrokCli,
    Opencode,
    QwenCode,
    Agent,
}

impl ClientKind {
    pub const ALL: [Self; 8] = [
        Self::Codex,
        Self::ClaudeCode,
        Self::Cursor,
        Self::GeminiCli,
        Self::GrokCli,
        Self::Opencode,
        Self::QwenCode,
        Self::Agent,
    ];

    #[must_use]
    pub const fn command(self) -> &'static str {
        match self {
            Self::Codex => "codex",
            Self::ClaudeCode => "claude",
            Self::Cursor => "cursor-agent",
            Self::GeminiCli => "gemini",
            Self::GrokCli => "grok",
            Self::Opencode => "opencode",
            Self::QwenCode => "qwen",
            Self::Agent => "agent",
        }
    }

    #[must_use]
    pub const fn display_name(self) -> &'static str {
        match self {
            Self::Codex => "Codex CLI",
            Self::ClaudeCode => "Claude Code",
            Self::Cursor => "Cursor CLI",
            Self::GeminiCli => "Gemini CLI",
            Self::GrokCli => "Grok CLI",
            Self::Opencode => "OpenCode",
            Self::QwenCode => "Qwen Code",
            Self::Agent => "Link.Assistant Agent",
        }
    }

    #[must_use]
    pub const fn dialect(self) -> &'static str {
        match self {
            Self::Codex => "OpenAI Responses",
            Self::ClaudeCode => "Anthropic Messages",
            Self::GeminiCli => "Gemini native",
            Self::Cursor => "Cursor private",
            Self::GrokCli | Self::Opencode | Self::QwenCode | Self::Agent => "OpenAI Chat",
        }
    }

    #[must_use]
    pub const fn token_env(self) -> Option<&'static str> {
        match self {
            Self::Codex => Some(CODEX_TOKEN_ENV),
            Self::ClaudeCode => Some(CLAUDE_TOKEN_ENV),
            Self::GeminiCli => Some("GEMINI_API_KEY"),
            Self::GrokCli => Some(GROK_TOKEN_ENV),
            Self::Opencode | Self::QwenCode | Self::Agent => Some(ROUTER_TOKEN_ENV),
            Self::Cursor => None,
        }
    }

    #[must_use]
    pub const fn setup_limitation(self) -> Option<&'static str> {
        match self {
            Self::Cursor => Some(
                "Cursor CLI does not expose a base-URL override and rejects non-Cursor keys before making an HTTP request",
            ),
            Self::GeminiCli => Some(
                "Gemini CLI aborts with IneligibleTierError before contacting the router on the tested individual Code Assist flow",
            ),
            _ => None,
        }
    }

    #[must_use]
    pub const fn base_url_env(self) -> Option<&'static str> {
        match self {
            Self::GrokCli => Some(GROK_BASE_ENV),
            _ => None,
        }
    }
}

impl fmt::Display for ClientKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Codex => write!(f, "codex"),
            Self::ClaudeCode => write!(f, "claude-code"),
            Self::Cursor => write!(f, "cursor"),
            Self::GeminiCli => write!(f, "gemini-cli"),
            Self::GrokCli => write!(f, "grok-cli"),
            Self::Opencode => write!(f, "opencode"),
            Self::QwenCode => write!(f, "qwen-code"),
            Self::Agent => write!(f, "agent"),
        }
    }
}

#[derive(Debug)]
pub struct ClientError(String);

impl ClientError {
    fn message(message: impl Into<String>) -> Self {
        Self(message.into())
    }
}

impl fmt::Display for ClientError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

impl std::error::Error for ClientError {}

impl From<std::io::Error> for ClientError {
    fn from(error: std::io::Error) -> Self {
        Self(error.to_string())
    }
}

impl From<serde_json::Error> for ClientError {
    fn from(error: serde_json::Error) -> Self {
        Self(error.to_string())
    }
}

/// Secret-free state returned by `clients list` and `clients show`.
#[derive(Debug, Serialize)]
pub struct ClientStatus {
    pub client: String,
    pub installed: bool,
    pub configured: bool,
    pub config_path: PathBuf,
    pub dialect: &'static str,
    pub base_url: Option<String>,
    pub token_env: Option<&'static str>,
    pub token_env_set: bool,
}

/// Result of a successful setup operation.
#[derive(Debug)]
pub struct SetupResult {
    pub path: PathBuf,
    pub backup: Option<PathBuf>,
    pub changed: bool,
}

/// Reads and updates supported clients below their normal user config roots.
#[derive(Debug)]
pub struct ClientManager {
    home: PathBuf,
    codex_home: PathBuf,
    claude_home: PathBuf,
    config_home: PathBuf,
    qwen_home: PathBuf,
}

impl ClientManager {
    /// Resolve client directories, respecting the clients' own override vars.
    pub fn from_env() -> Result<Self, ClientError> {
        let home = std::env::var_os("HOME")
            .map(PathBuf::from)
            .ok_or_else(|| ClientError::message("HOME is unset; cannot locate client configs"))?;
        let codex_home =
            std::env::var_os("CODEX_HOME").map_or_else(|| home.join(".codex"), PathBuf::from);
        let claude_home = std::env::var_os("CLAUDE_CONFIG_DIR")
            .map_or_else(|| home.join(".claude"), PathBuf::from);
        let config_home =
            std::env::var_os("XDG_CONFIG_HOME").map_or_else(|| home.join(".config"), PathBuf::from);
        let qwen_home =
            std::env::var_os("QWEN_HOME").map_or_else(|| home.join(".qwen"), PathBuf::from);
        Ok(Self {
            home,
            codex_home,
            claude_home,
            config_home,
            qwen_home,
        })
    }

    #[must_use]
    pub fn config_path(&self, client: ClientKind) -> PathBuf {
        match client {
            ClientKind::Codex => self.codex_home.join("config.toml"),
            ClientKind::ClaudeCode => self.claude_home.join("settings.json"),
            ClientKind::Cursor => std::env::var_os("CURSOR_CONFIG_DIR").map_or_else(
                || self.home.join(".cursor/cli-config.json"),
                |path| PathBuf::from(path).join("cli-config.json"),
            ),
            ClientKind::GeminiCli => self.home.join(".gemini/settings.json"),
            ClientKind::GrokCli => self.home.join(".grok/user-settings.json"),
            ClientKind::Opencode => self.config_home.join("opencode/opencode.json"),
            ClientKind::QwenCode => self.qwen_home.join("settings.json"),
            ClientKind::Agent => self.config_home.join("link-assistant-agent/opencode.json"),
        }
    }

    pub fn status(&self, client: ClientKind) -> Result<ClientStatus, ClientError> {
        let path = self.config_path(client);
        let base_url = match client {
            ClientKind::Codex => read_codex_base_url(&path)?,
            ClientKind::ClaudeCode => read_claude_base_url(&path)?,
            ClientKind::Opencode | ClientKind::Agent => read_json_provider_base_url(&path)?,
            ClientKind::QwenCode => read_qwen_base_url(&path)?,
            ClientKind::GrokCli => std::env::var(GROK_BASE_ENV).ok(),
            ClientKind::Cursor | ClientKind::GeminiCli => None,
        };
        let token_env = client.token_env();
        Ok(ClientStatus {
            client: client.to_string(),
            installed: command_exists(client.command()),
            configured: base_url.is_some(),
            config_path: path,
            dialect: client.dialect(),
            base_url,
            token_env,
            token_env_set: token_env.is_some_and(|name| std::env::var_os(name).is_some()),
        })
    }

    pub fn setup(&self, client: ClientKind, base_url: &str) -> Result<SetupResult, ClientError> {
        if let Some(limitation) = client.setup_limitation() {
            return Err(ClientError::message(limitation));
        }
        let base_url = normalize_base_url(base_url)?;
        match client {
            ClientKind::Codex => self.setup_codex(&base_url),
            ClientKind::ClaudeCode => self.setup_claude(&base_url),
            ClientKind::Opencode | ClientKind::Agent => self.setup_json_provider(client, &base_url),
            ClientKind::QwenCode => self.setup_qwen(&base_url),
            ClientKind::GrokCli => Ok(unchanged(self.config_path(client))),
            ClientKind::Cursor | ClientKind::GeminiCli => unreachable!(),
        }
    }

    pub fn remove(&self, client: ClientKind) -> Result<SetupResult, ClientError> {
        match client {
            ClientKind::Codex => self.remove_codex(),
            ClientKind::ClaudeCode => self.remove_claude(),
            ClientKind::Opencode | ClientKind::Agent => self.remove_json_provider(client),
            ClientKind::QwenCode => self.remove_qwen(),
            ClientKind::GrokCli | ClientKind::Cursor | ClientKind::GeminiCli => {
                Ok(unchanged(self.config_path(client)))
            }
        }
    }

    /// Exercise the same URL and token variable configured for the client.
    pub async fn doctor(&self, client: ClientKind) -> Result<String, ClientError> {
        if let Some(limitation) = client.setup_limitation() {
            return Err(ClientError::message(limitation));
        }
        let status = self.status(client)?;
        let base_url = status.base_url.ok_or_else(|| {
            ClientError::message(format!(
                "{} is not configured; run `clients setup {client}`",
                client.display_name()
            ))
        })?;
        let token_env = client
            .token_env()
            .ok_or_else(|| ClientError::message("client has no router token environment"))?;
        let token = std::env::var(token_env).map_err(|_| {
            ClientError::message(format!(
                "{token_env} is unset; export the token printed by `clients setup {client}`"
            ))
        })?;
        let (url, body) = match client {
            ClientKind::Codex => (
                format!("{}/responses", base_url.trim_end_matches('/')),
                json!({"model":"gpt-5", "input":"Reply OK", "max_output_tokens":1}),
            ),
            ClientKind::ClaudeCode => (
                format!("{}/v1/messages", base_url.trim_end_matches('/')),
                json!({
                    "model":"claude-sonnet-4-5-20250929",
                    "max_tokens":1,
                    "messages":[{"role":"user", "content":"Reply OK"}]
                }),
            ),
            ClientKind::GrokCli
            | ClientKind::Opencode
            | ClientKind::QwenCode
            | ClientKind::Agent => (
                format!("{}/chat/completions", base_url.trim_end_matches('/')),
                json!({
                    "model":"claude-sonnet-4-5-20250929",
                    "messages":[{"role":"user", "content":"Reply OK"}],
                    "max_tokens":1
                }),
            ),
            ClientKind::Cursor | ClientKind::GeminiCli => unreachable!(),
        };
        let response = reqwest::Client::new()
            .post(&url)
            .bearer_auth(token)
            .json(&body)
            .send()
            .await
            .map_err(|error| {
                ClientError::message(format!("router is not reachable at {url}: {error}"))
            })?;
        let code = response.status();
        let response_body = response.text().await.unwrap_or_default();
        if code.is_success() {
            return Ok(format!(
                "{} reached {url} successfully ({code})",
                client.display_name()
            ));
        }
        if code.as_u16() == 401 || code.as_u16() == 403 {
            return Err(ClientError::message(format!(
                "router rejected {token_env} ({code}); the token is invalid, expired, or revoked"
            )));
        }
        if code.as_u16() == 503 {
            return Err(ClientError::message(format!(
                "router reached, but its upstream credential is unavailable ({code}): {}",
                compact_body(&response_body)
            )));
        }
        Err(ClientError::message(format!(
            "router request failed at {url} ({code}): {}",
            compact_body(&response_body)
        )))
    }

    fn setup_codex(&self, base_url: &str) -> Result<SetupResult, ClientError> {
        let path = self.config_path(ClientKind::Codex);
        let source = read_or_empty(&path)?;
        let mut document = if source.trim().is_empty() {
            DocumentMut::new()
        } else {
            source.parse::<DocumentMut>().map_err(|error| {
                ClientError::message(format!("invalid TOML in {}: {error}", path.display()))
            })?
        };
        let previous_provider = document
            .get("model_provider")
            .and_then(Item::as_str)
            .map(str::to_string);
        document["model_provider"] = value(CODEX_PROVIDER);
        if document.get("model_providers").is_none() {
            document["model_providers"] = Item::Table(Table::new());
        }
        let providers = document["model_providers"]
            .as_table_like_mut()
            .ok_or_else(|| ClientError::message("model_providers must be a TOML table"))?;
        if providers.get(CODEX_PROVIDER).is_none() {
            providers.insert(CODEX_PROVIDER, Item::Table(Table::new()));
        }
        let provider = providers
            .get_mut(CODEX_PROVIDER)
            .and_then(Item::as_table_like_mut)
            .ok_or_else(|| {
                ClientError::message("model_providers.link-assistant must be a TOML table")
            })?;
        provider.insert("name", value("Link.Assistant.Router"));
        provider.insert("base_url", value(format!("{base_url}/v1")));
        provider.insert("env_key", value(CODEX_TOKEN_ENV));
        provider.insert("wire_api", value("responses"));
        let result = write_if_changed(&path, &source, &document.to_string())?;
        let marker = self.codex_home.join(OWNERSHIP_MARKER);
        if !marker.exists() {
            let previous_provider = previous_provider.filter(|value| value != CODEX_PROVIDER);
            write_codex_marker(&marker, previous_provider.as_deref())?;
        }
        Ok(result)
    }

    fn setup_claude(&self, base_url: &str) -> Result<SetupResult, ClientError> {
        let path = self.config_path(ClientKind::ClaudeCode);
        let source = read_or_empty(&path)?;
        let mut document: Value = if source.trim().is_empty() {
            json!({})
        } else {
            serde_json::from_str(&source).map_err(|error| {
                ClientError::message(format!("invalid JSON in {}: {error}", path.display()))
            })?
        };
        let root = document.as_object_mut().ok_or_else(|| {
            ClientError::message(format!("{} must contain a JSON object", path.display()))
        })?;
        let env = root.entry("env").or_insert_with(|| json!({}));
        let env = env.as_object_mut().ok_or_else(|| {
            ClientError::message(format!("{}.env must be a JSON object", path.display()))
        })?;
        env.insert(CLAUDE_BASE_ENV.into(), Value::String(base_url.into()));
        let rendered = format!("{}\n", serde_json::to_string_pretty(&document)?);
        let result = write_if_changed(&path, &source, &rendered)?;
        write_claude_marker(&self.claude_home.join(OWNERSHIP_MARKER), base_url)?;
        Ok(result)
    }

    fn remove_codex(&self) -> Result<SetupResult, ClientError> {
        let path = self.config_path(ClientKind::Codex);
        let source = read_or_empty(&path)?;
        if source.trim().is_empty() {
            return Ok(unchanged(path));
        }
        let marker_path = self.codex_home.join(OWNERSHIP_MARKER);
        if !marker_path.exists() {
            return Ok(unchanged(path));
        }
        let mut document = source.parse::<DocumentMut>().map_err(|error| {
            ClientError::message(format!("invalid TOML in {}: {error}", path.display()))
        })?;
        let previous_provider = read_codex_marker(&marker_path)?;
        if document.get("model_provider").and_then(Item::as_str) == Some(CODEX_PROVIDER) {
            if let Some(previous_provider) = previous_provider {
                document["model_provider"] = value(previous_provider);
            } else {
                document.as_table_mut().remove("model_provider");
            }
        }
        if let Some(providers) = document
            .get_mut("model_providers")
            .and_then(Item::as_table_like_mut)
        {
            providers.remove(CODEX_PROVIDER);
        }
        let result = write_if_changed(&path, &source, &document.to_string())?;
        if marker_path.exists() {
            fs::remove_file(marker_path)?;
        }
        Ok(result)
    }

    fn remove_claude(&self) -> Result<SetupResult, ClientError> {
        let path = self.config_path(ClientKind::ClaudeCode);
        let source = read_or_empty(&path)?;
        if source.trim().is_empty() {
            return Ok(unchanged(path));
        }
        let marker_path = self.claude_home.join(OWNERSHIP_MARKER);
        let managed_url = read_claude_marker(&marker_path)?;
        let Some(managed_url) = managed_url else {
            return Ok(unchanged(path));
        };
        let mut document: Value = serde_json::from_str(&source).map_err(|error| {
            ClientError::message(format!("invalid JSON in {}: {error}", path.display()))
        })?;
        let current_url = document
            .get("env")
            .and_then(|env| env.get(CLAUDE_BASE_ENV))
            .and_then(Value::as_str);
        if current_url != Some(managed_url.as_str()) {
            fs::remove_file(marker_path)?;
            return Ok(unchanged(path));
        }
        if let Some(env) = document.get_mut("env").and_then(Value::as_object_mut) {
            env.remove(CLAUDE_BASE_ENV);
        }
        let rendered = format!("{}\n", serde_json::to_string_pretty(&document)?);
        let result = write_if_changed(&path, &source, &rendered)?;
        if marker_path.exists() {
            fs::remove_file(marker_path)?;
        }
        Ok(result)
    }
}

fn normalize_base_url(base_url: &str) -> Result<String, ClientError> {
    let trimmed = base_url.trim().trim_end_matches('/');
    if !(trimmed.starts_with("http://") || trimmed.starts_with("https://")) {
        return Err(ClientError::message(
            "base URL must start with http:// or https://",
        ));
    }
    Ok(trimmed.to_string())
}

fn read_codex_base_url(path: &Path) -> Result<Option<String>, ClientError> {
    let source = read_or_empty(path)?;
    if source.trim().is_empty() {
        return Ok(None);
    }
    let document = source.parse::<DocumentMut>().map_err(|error| {
        ClientError::message(format!("invalid TOML in {}: {error}", path.display()))
    })?;
    if document.get("model_provider").and_then(Item::as_str) != Some(CODEX_PROVIDER) {
        return Ok(None);
    }
    let Some(provider) = document
        .get("model_providers")
        .and_then(Item::as_table_like)
        .and_then(|providers| providers.get(CODEX_PROVIDER))
    else {
        return Ok(None);
    };
    let Some(provider) = provider.as_table_like() else {
        return Ok(None);
    };
    let configured = provider.get("wire_api").and_then(Item::as_str) == Some("responses")
        && provider.get("env_key").and_then(Item::as_str) == Some(CODEX_TOKEN_ENV);
    Ok(configured
        .then(|| {
            provider
                .get("base_url")
                .and_then(Item::as_str)
                .map(str::to_string)
        })
        .flatten())
}

fn read_claude_base_url(path: &Path) -> Result<Option<String>, ClientError> {
    let source = read_or_empty(path)?;
    if source.trim().is_empty() {
        return Ok(None);
    }
    let document: Value = serde_json::from_str(&source).map_err(|error| {
        ClientError::message(format!("invalid JSON in {}: {error}", path.display()))
    })?;
    Ok(document
        .get("env")
        .and_then(|env| env.get(CLAUDE_BASE_ENV))
        .and_then(Value::as_str)
        .map(str::to_string))
}

fn read_or_empty(path: &Path) -> Result<String, ClientError> {
    match fs::read_to_string(path) {
        Ok(source) => Ok(source),
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(String::new()),
        Err(error) => Err(ClientError::message(format!(
            "could not read {}: {error}",
            path.display()
        ))),
    }
}

fn write_if_changed(path: &Path, before: &str, after: &str) -> Result<SetupResult, ClientError> {
    if before == after {
        return Ok(unchanged(path.to_path_buf()));
    }
    let parent = path.parent().ok_or_else(|| {
        ClientError::message(format!("{} has no parent directory", path.display()))
    })?;
    fs::create_dir_all(parent)?;
    let backup = path.exists().then(|| backup_file(path)).transpose()?;
    atomic_write(path, after.as_bytes())?;
    Ok(SetupResult {
        path: path.to_path_buf(),
        backup,
        changed: true,
    })
}

const fn unchanged(path: PathBuf) -> SetupResult {
    SetupResult {
        path,
        backup: None,
        changed: false,
    }
}

fn backup_file(path: &Path) -> Result<PathBuf, ClientError> {
    let stamp = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_nanos();
    let file_name = path
        .file_name()
        .and_then(|name| name.to_str())
        .ok_or_else(|| ClientError::message("config file name is not valid UTF-8"))?;
    let backup = path.with_file_name(format!("{file_name}.link-assistant-router.{stamp}.bak"));
    fs::copy(path, &backup)?;
    Ok(backup)
}

fn atomic_write(path: &Path, contents: &[u8]) -> Result<(), ClientError> {
    let parent = path
        .parent()
        .ok_or_else(|| ClientError::message("missing parent directory"))?;
    let temp = parent.join(format!(
        ".link-assistant-router.{}.{}.tmp",
        std::process::id(),
        uuid::Uuid::new_v4()
    ));
    let mut options = OpenOptions::new();
    options.write(true).create_new(true);
    #[cfg(unix)]
    {
        use std::os::unix::fs::OpenOptionsExt;
        options.mode(0o600);
    }
    let mut file = options.open(&temp)?;
    file.write_all(contents)?;
    file.sync_all()?;
    if let Ok(metadata) = fs::metadata(path) {
        fs::set_permissions(&temp, metadata.permissions())?;
    }
    fs::rename(&temp, path)?;
    Ok(())
}

fn write_claude_marker(path: &Path, base_url: &str) -> Result<(), ClientError> {
    let rendered = format!(
        "{}\n",
        serde_json::to_string_pretty(&json!({
            "anthropic_base_url": base_url
        }))?
    );
    if read_or_empty(path)? != rendered {
        let parent = path
            .parent()
            .ok_or_else(|| ClientError::message("missing marker parent"))?;
        fs::create_dir_all(parent)?;
        atomic_write(path, rendered.as_bytes())?;
    }
    Ok(())
}

fn read_claude_marker(path: &Path) -> Result<Option<String>, ClientError> {
    let source = read_or_empty(path)?;
    if source.trim().is_empty() {
        return Ok(None);
    }
    let marker: Value = serde_json::from_str(&source)?;
    Ok(marker
        .get("anthropic_base_url")
        .and_then(Value::as_str)
        .map(str::to_string))
}

fn write_codex_marker(path: &Path, previous_provider: Option<&str>) -> Result<(), ClientError> {
    let rendered = format!(
        "{}\n",
        serde_json::to_string_pretty(&json!({
            "previous_model_provider": previous_provider
        }))?
    );
    let parent = path
        .parent()
        .ok_or_else(|| ClientError::message("missing marker parent"))?;
    fs::create_dir_all(parent)?;
    atomic_write(path, rendered.as_bytes())
}

fn read_codex_marker(path: &Path) -> Result<Option<String>, ClientError> {
    let source = read_or_empty(path)?;
    if source.trim().is_empty() {
        return Ok(None);
    }
    let marker: Value = serde_json::from_str(&source)?;
    Ok(marker
        .get("previous_model_provider")
        .and_then(Value::as_str)
        .map(str::to_string))
}

fn command_exists(command: &str) -> bool {
    std::env::var_os("PATH").is_some_and(|path| {
        std::env::split_paths(&path).any(|directory| directory.join(command).is_file())
    })
}

fn compact_body(body: &str) -> String {
    const MAX: usize = 240;
    let compact = body.split_whitespace().collect::<Vec<_>>().join(" ");
    if compact.chars().count() <= MAX {
        compact
    } else {
        format!("{}", compact.chars().take(MAX).collect::<String>())
    }
}

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

    #[test]
    fn rejects_non_http_router_urls() {
        assert!(normalize_base_url("router.internal:8080").is_err());
    }

    #[test]
    fn compact_diagnostics_do_not_echo_unbounded_upstream_bodies() {
        let body = "x".repeat(500);
        let compact = compact_body(&body);
        assert!(compact.ends_with(''));
        assert!(compact.chars().count() <= 241);
    }
}