1use std::path::{Path, PathBuf};
13
14use anyhow::{Context, Result, anyhow};
15
16use super::presets::{LlmPreset, PresetBackend};
17use crate::llm::quirks::Quirks;
18
19#[derive(Debug, Clone)]
21enum ChoiceBackend {
22 Http {
23 endpoint: String,
24 key_in_store: bool,
25 quirks: Quirks,
26 },
27 Codex,
28}
29
30#[derive(Debug, Clone)]
36pub struct Choice {
37 pub preset: &'static LlmPreset,
40 pub model: String,
42 backend: ChoiceBackend,
44}
45
46impl Choice {
47 pub fn http(
48 preset: &'static LlmPreset,
49 model: String,
50 endpoint: String,
51 key_in_store: bool,
52 quirks: Quirks,
53 ) -> Self {
54 assert!(
55 matches!(preset.backend, PresetBackend::Http(_)),
56 "HTTP choice requires an HTTP preset"
57 );
58 Self {
59 preset,
60 model,
61 backend: ChoiceBackend::Http {
62 endpoint,
63 key_in_store,
64 quirks,
65 },
66 }
67 }
68
69 pub fn codex(preset: &'static LlmPreset, model: String) -> Self {
70 assert!(
71 matches!(preset.backend, PresetBackend::Codex(_)),
72 "Codex choice requires a Codex preset"
73 );
74 Self {
75 preset,
76 model,
77 backend: ChoiceBackend::Codex,
78 }
79 }
80
81 pub fn is_http(&self) -> bool {
82 matches!(self.backend, ChoiceBackend::Http { .. })
83 }
84
85 #[cfg(test)]
86 pub fn endpoint(&self) -> Option<&str> {
87 match &self.backend {
88 ChoiceBackend::Http { endpoint, .. } => Some(endpoint),
89 ChoiceBackend::Codex => None,
90 }
91 }
92
93 pub fn key_in_store(&self) -> bool {
94 match &self.backend {
95 ChoiceBackend::Http { key_in_store, .. } => *key_in_store,
96 ChoiceBackend::Codex => false,
97 }
98 }
99
100 #[cfg(test)]
101 pub fn quirks(&self) -> Quirks {
102 match &self.backend {
103 ChoiceBackend::Http { quirks, .. } => *quirks,
104 ChoiceBackend::Codex => self.preset.quirks(),
105 }
106 }
107}
108
109pub fn render_chain(choices: &[Choice]) -> String {
119 let mut body = String::new();
120 body.push_str("# drep configuration, written by `drep init`.\n");
121 body.push_str("#\n");
122 body.push_str("# Providers are declared as `[[llm]]`, an ordered array of tables: a\n");
123 body.push_str("# preference order. Each one is tried in turn, and a transport failure -\n");
124 body.push_str("# unreachable, timed out, rate limited, 5xx, or an empty answer - falls\n");
125 body.push_str("# through to the next. A 401 or 403 does not: that is a broken key, and\n");
126 body.push_str("# failing over would hide it. Add a fallback by adding another block:\n");
127 body.push_str("#\n");
128 body.push_str("# [[llm]]\n");
129 body.push_str("# endpoint = \"https://openrouter.ai/api/v1\"\n");
130 body.push_str("# model = \"deepseek/deepseek-v4-pro-0813\"\n");
131 body.push_str("#\n");
132 body.push_str("# Set `enabled = false` on a block to park it without deleting it.\n");
133 body.push_str("#\n");
134 if choices.iter().any(Choice::is_http) {
135 body.push_str(
136 "# API keys are NOT in this file. `drep init` stores them per machine, keyed\n",
137 );
138 body.push_str("# by endpoint, so this file carries only the provider choice and can be\n");
139 body.push_str("# committed. `drep auth list` shows what is stored. To pin a key to a\n");
140 body.push_str(
141 "# variable instead - which is what CI wants - add `api_key = \"${VAR}\"` to\n",
142 );
143 body.push_str("# a block; an explicit value always wins over the stored one.\n");
144 }
145 if choices.iter().any(|choice| !choice.is_http()) {
146 body.push_str("# Codex owns ChatGPT subscription login and token refresh.\n");
147 body.push_str("# Run `codex login`; drep never reads or stores those credentials.\n");
148 }
149
150 for choice in choices {
151 body.push('\n');
152 render_one(&mut body, choice);
153 }
154
155 body
156}
157
158fn render_one(body: &mut String, choice: &Choice) {
160 let preset = choice.preset;
161
162 body.push_str("[[llm]]\n");
163 body.push_str("enabled = true\n");
164 if let (PresetBackend::Codex(codex), ChoiceBackend::Codex) = (&preset.backend, &choice.backend)
165 {
166 body.push_str("backend = \"codex\"\n");
167 body.push_str(&format!("model = \"{}\"\n", escape(&choice.model)));
168 if let Some(effort) = &codex.reasoning_effort {
169 body.push_str(&format!("reasoning_effort = \"{}\"\n", effort.as_str()));
170 }
171 if let Some(timeout) = preset.timeout_secs {
172 body.push_str(&format!("timeout_secs = {timeout}\n"));
173 }
174 body.push_str(&format!("max_concurrent = {}\n", codex.max_concurrent));
175 body.push_str(
176 "# Reviews consume ChatGPT/Codex subscription allowance, not OpenAI API billing.\n",
177 );
178 return;
179 }
180
181 let (http, endpoint, key_in_store, quirks) = match (&preset.backend, &choice.backend) {
182 (
183 PresetBackend::Http(http),
184 ChoiceBackend::Http {
185 endpoint,
186 key_in_store,
187 quirks,
188 },
189 ) => (http, endpoint.as_str(), *key_in_store, quirks),
190 _ => panic!("choice backend does not match preset `{}`", preset.key),
191 };
192 body.push_str(&format!("endpoint = \"{}\"\n", escape(endpoint)));
193 body.push_str(&format!("model = \"{}\"\n", escape(&choice.model)));
194
195 if !key_in_store && let Some(env) = http.api_key_env {
199 body.push_str(&format!("api_key = \"${{{env}}}\"\n"));
200 }
201
202 if let Some(protocol) = http.protocol {
205 body.push_str("# This endpoint speaks Anthropic's messages API, not chat completions.\n");
206 body.push_str(&format!("protocol = \"{}\"\n", escape(protocol)));
207 }
208
209 if let Some(max_tokens) = quirks.max_tokens {
216 body.push_str("# Required by this endpoint: it refuses a request that omits the field.\n");
217 if quirks.max_tokens_from_registry {
218 body.push_str(
219 "# This is the model's own published output limit, not a cap drep chose.\n",
220 );
221 } else {
222 body.push_str(
223 "# This model's own limit is not known here, so it is the provider's fallback:\n\
224 # set well above any review-sized response.\n",
225 );
226 }
227 body.push_str(&format!("max_tokens = {max_tokens}\n"));
228 }
229
230 match quirks.temperature {
234 Some(temperature) => {
235 body.push_str(&format!("temperature = {temperature:?}\n"));
239 }
240 None => {
241 body.push_str("# `temperature` is deliberately absent: this model rejects the\n");
242 body.push_str("# parameter, and the resulting 400 neither fails over nor retries.\n");
243 }
244 }
245
246 if let Some(timeout) = preset.timeout_secs {
247 body.push_str(
248 "# A reasoning model can spend minutes on one file; the wall clock has to match.\n",
249 );
250 body.push_str(&format!("timeout_secs = {timeout}\n"));
251 }
252
253 if quirks.max_tokens.is_none() {
254 body.push_str(
255 "# max_tokens is deliberately unset: with no completion cap, a reasoning model\n",
256 );
257 body.push_str("# is never truncated mid-thought. Set it only to cap spend.\n");
258 }
259}
260
261pub fn already_exists(path: &Path) -> anyhow::Error {
268 anyhow!(
269 "{} already exists. Re-run with --force to replace it.",
270 path.display()
271 )
272}
273
274fn escape(s: &str) -> String {
288 let mut out = String::with_capacity(s.len());
289 for ch in s.chars() {
290 match ch {
291 '\\' => out.push_str("\\\\"),
292 '"' => out.push_str("\\\""),
293 '\n' => out.push_str("\\n"),
294 '\r' => out.push_str("\\r"),
295 '\t' => out.push_str("\\t"),
296 '\u{8}' => out.push_str("\\b"),
297 '\u{c}' => out.push_str("\\f"),
298 c if c.is_control() => out.push_str(&format!("\\u{:04X}", c as u32)),
300 other => out.push(other),
301 }
302 }
303 out
304}
305
306pub fn write(root: &Path, body: &str, force: bool) -> Result<PathBuf> {
312 use std::io::Write;
313
314 let path = root.join(crate::config::default_config_path());
315 let mut temporary = tempfile::NamedTempFile::new_in(root)
316 .with_context(|| format!("could not write {}", path.display()))?;
317 temporary
318 .write_all(body.as_bytes())
319 .with_context(|| format!("could not write {}", path.display()))?;
320 temporary
321 .as_file()
322 .sync_all()
323 .with_context(|| format!("could not write {}", path.display()))?;
324
325 let published = if force {
329 temporary.persist(&path)
330 } else {
331 temporary.persist_noclobber(&path)
332 };
333 match published {
334 Ok(_) => Ok(path),
335 Err(err) => match (force, err.error.kind()) {
336 (false, std::io::ErrorKind::AlreadyExists) => Err(already_exists(&path)),
337 _ => Err(anyhow::Error::new(err.error)
338 .context(format!("could not write {}", path.display()))),
339 },
340 }
341}
342
343#[cfg(test)]
344mod tests {
345 use super::*;
346
347 #[test]
348 fn a_write_that_fails_for_another_reason_is_not_reported_as_already_existing() {
349 let dir = tempfile::tempdir().expect("tempdir");
354 let missing = dir.path().join("no-such-directory");
355
356 let err = write(&missing, "model = \"x\"\n", false)
357 .expect_err("there is no directory to write into");
358
359 assert!(
360 !err.to_string().contains("already exists"),
361 "nothing exists here; got {err}"
362 );
363 assert!(err.to_string().contains("could not write"), "got {err}");
364 }
365
366 #[cfg(unix)]
367 #[test]
368 fn a_dangling_symlink_named_drep_toml_is_refused_rather_than_followed() {
369 let dir = tempfile::tempdir().expect("tempdir");
373 let elsewhere = dir.path().join("elsewhere.toml");
374 std::os::unix::fs::symlink(&elsewhere, dir.path().join("drep.toml")).expect("symlink");
375
376 let err = write(dir.path(), "model = \"x\"\n", false)
377 .expect_err("a dangling symlink is still something being there");
378
379 assert!(err.to_string().contains("drep.toml"), "got {err}");
380 assert!(
381 !elsewhere.exists(),
382 "and nothing was written through it to {}",
383 elsewhere.display()
384 );
385 }
386
387 #[test]
388 fn escape_handles_backslash_and_quote() {
389 assert_eq!(escape("plain"), "plain");
390 assert_eq!(escape(r#"a"b"#), r#"a\"b"#);
391 assert_eq!(escape(r"a\b"), r"a\\b");
392 assert_eq!(escape(r#"a"b\c"#), r#"a\"b\\c"#);
393 }
394}