lean_ctx_cli/proxy_setup/
grok.rs1use std::path::Path;
5
6use super::util::{GROK_OMITTED_NOTE, is_local_lean_ctx_url, is_proxy_reachable};
7
8pub(crate) fn install_grok_env(home: &Path, port: u16, quiet: bool, force: bool) {
20 let grok_dir = home.join(".grok");
21 let mode = effective_grok_auth_mode(home, force);
22 if grok_dir.exists() && mode != GrokAuthMode::None {
23 match mode {
27 GrokAuthMode::Subscription => {
28 ensure_proxy_provider(GROK_CHAT_PROVIDER_ID, GROK_CHAT_UPSTREAM, quiet);
29 }
30 GrokAuthMode::ApiKey => ensure_proxy_provider(XAI_PROVIDER_ID, XAI_UPSTREAM, quiet),
31 GrokAuthMode::None => {}
32 }
33 }
34 install_grok_env_at(&grok_dir, port, quiet, force, mode);
35}
36
37pub(crate) fn effective_grok_auth_mode(home: &Path, force: bool) -> GrokAuthMode {
43 match grok_auth_mode(home) {
44 GrokAuthMode::None if force => GrokAuthMode::Subscription,
45 other => other,
46 }
47}
48
49pub(crate) fn uninstall_grok_env(home: &Path, quiet: bool) {
50 uninstall_grok_env_at(&home.join(".grok"), quiet);
51}
52
53pub fn xai_api_key_available() -> bool {
55 for var in ["XAI_API_KEY", "GROK_CODE_XAI_API_KEY"] {
56 if let Ok(v) = std::env::var(var)
57 && !v.trim().is_empty()
58 {
59 return true;
60 }
61 }
62 false
63}
64
65pub fn grok_session_auth_available(home: &Path) -> bool {
67 let path = home.join(".grok/auth.json");
68 let Ok(raw) = std::fs::read_to_string(path) else {
69 return false;
70 };
71 let Ok(doc) = serde_json::from_str::<serde_json::Value>(&raw) else {
72 return false;
73 };
74 doc.as_object().is_some_and(|entries| {
76 entries.values().any(|v| {
77 v.get("key")
78 .and_then(serde_json::Value::as_str)
79 .is_some_and(|k| !k.trim().is_empty())
80 })
81 })
82}
83
84#[derive(Debug, Clone, Copy, PartialEq, Eq)]
85pub(crate) enum GrokAuthMode {
86 Subscription,
88 ApiKey,
90 None,
91}
92
93pub(crate) fn grok_auth_mode(home: &Path) -> GrokAuthMode {
96 if grok_session_auth_available(home) {
97 GrokAuthMode::Subscription
98 } else if xai_api_key_available() {
99 GrokAuthMode::ApiKey
100 } else {
101 GrokAuthMode::None
102 }
103}
104
105pub(crate) const XAI_PROVIDER_ID: &str = "xai";
106pub(crate) const XAI_UPSTREAM: &str = "https://api.x.ai";
107pub(crate) const GROK_CHAT_PROVIDER_ID: &str = "grok-chat";
108pub(crate) const GROK_CHAT_UPSTREAM: &str = "https://cli-chat-proxy.grok.com";
109
110#[derive(Debug, Clone, Copy)]
111pub(crate) enum ShellFlavor {
112 Posix,
113 Fish,
114 PowerShell,
115}
116
117pub(crate) fn grok_proxy_base_url(port: u16, mode: GrokAuthMode) -> Option<String> {
118 let base = format!("http://127.0.0.1:{port}");
119 match mode {
120 GrokAuthMode::Subscription => Some(format!("{base}/providers/{GROK_CHAT_PROVIDER_ID}/v1")),
121 GrokAuthMode::ApiKey => Some(format!("{base}/providers/{XAI_PROVIDER_ID}/v1")),
122 GrokAuthMode::None => None,
123 }
124}
125
126pub(crate) fn render_grok_shell_exports(
127 base: &str,
128 mode: GrokAuthMode,
129 flavor: ShellFlavor,
130) -> String {
131 match mode {
132 GrokAuthMode::None => format!("# {GROK_OMITTED_NOTE}"),
133 GrokAuthMode::Subscription => {
134 let url = format!("{base}/providers/{GROK_CHAT_PROVIDER_ID}/v1");
137 match flavor {
138 ShellFlavor::Posix => {
139 format!(r#"export GROK_CLI_CHAT_PROXY_BASE_URL="{url}""#)
140 }
141 ShellFlavor::Fish => {
142 format!(r#"set -gx GROK_CLI_CHAT_PROXY_BASE_URL "{url}""#)
143 }
144 ShellFlavor::PowerShell => {
145 format!(r#"$env:GROK_CLI_CHAT_PROXY_BASE_URL = "{url}""#)
146 }
147 }
148 }
149 GrokAuthMode::ApiKey => {
150 let url = format!("{base}/providers/{XAI_PROVIDER_ID}/v1");
151 match flavor {
152 ShellFlavor::Posix => format!(
153 r#"export GROK_MODELS_BASE_URL="{url}"
154export GROK_CLI_CHAT_PROXY_BASE_URL="{url}""#
155 ),
156 ShellFlavor::Fish => format!(
157 r#"set -gx GROK_MODELS_BASE_URL "{url}"
158set -gx GROK_CLI_CHAT_PROXY_BASE_URL "{url}""#
159 ),
160 ShellFlavor::PowerShell => format!(
161 r#"$env:GROK_MODELS_BASE_URL = "{url}"
162$env:GROK_CLI_CHAT_PROXY_BASE_URL = "{url}""#
163 ),
164 }
165 }
166 }
167}
168
169#[derive(Debug, Clone, PartialEq, Eq)]
172pub(super) enum ProviderEnsureAction {
173 Unchanged,
175 Seeded,
177 Updated { previous: String },
179}
180
181pub(super) fn reconcile_proxy_provider(
187 providers: &mut Vec<lean_ctx::core::config::ProviderEntry>,
188 id: &str,
189 base_url: &str,
190) -> ProviderEnsureAction {
191 use lean_ctx::core::config::{ProviderEntry, WireShape, normalize_url};
192
193 let desired = normalize_url(base_url);
194 if let Some(existing) = providers
195 .iter_mut()
196 .find(|p| p.id.trim().eq_ignore_ascii_case(id))
197 {
198 if normalize_url(&existing.base_url) == desired {
199 return ProviderEnsureAction::Unchanged;
200 }
201 let previous = existing.base_url.clone();
202 existing.base_url = desired;
203 return ProviderEnsureAction::Updated { previous };
204 }
205
206 providers.push(ProviderEntry {
207 id: id.to_string(),
208 shape: WireShape::OpenAi,
209 base_url: desired,
210 api_key_env: None, aws_region: None,
212 account_ref: None,
213 region: None,
214 enabled: None,
215 local: None,
216 });
217 ProviderEnsureAction::Seeded
218}
219
220pub(crate) fn ensure_proxy_provider(id: &str, base_url: &str, quiet: bool) {
225 use lean_ctx::core::config::normalize_url;
226
227 let desired = normalize_url(base_url);
228 let cfg = lean_ctx::core::config::Config::load();
229 if cfg
230 .proxy
231 .providers
232 .iter()
233 .any(|p| p.id.trim().eq_ignore_ascii_case(id) && normalize_url(&p.base_url) == desired)
234 {
235 return;
236 }
237
238 let mut action = ProviderEnsureAction::Unchanged;
239 match lean_ctx::core::config::Config::update_global(|c| {
240 action = reconcile_proxy_provider(&mut c.proxy.providers, id, &desired);
241 }) {
242 Ok(_) => {
243 if quiet {
244 return;
245 }
246 match action {
247 ProviderEnsureAction::Unchanged => {}
248 ProviderEnsureAction::Seeded => {
249 println!(" \x1b[32m✓\x1b[0m Seeded [[proxy.providers]] id={id} → {desired}");
250 }
251 ProviderEnsureAction::Updated { previous } => {
252 println!(
253 " \x1b[33m!\x1b[0m Updated [[proxy.providers]] id={id} base_url\n was: {previous}\n now: {desired}"
254 );
255 }
256 }
257 }
258 Err(e) => {
259 tracing::warn!("could not ensure {id} proxy provider: {e}");
260 if !quiet {
261 eprintln!(
262 " \u{26a0} Could not ensure {id} provider in config.toml: {e}\n \
263 Fix manually:\n [[proxy.providers]]\n id = \"{id}\"\n \
264 shape = \"openai\"\n base_url = \"{desired}\""
265 );
266 }
267 }
268 }
269}
270
271pub(crate) fn install_grok_env_at(
273 grok_dir: &Path,
274 port: u16,
275 quiet: bool,
276 force: bool,
277 mode: GrokAuthMode,
278) {
279 use lean_ctx::core::config::normalize_url_opt;
280
281 if !grok_dir.exists() {
282 return;
283 }
284 if mode == GrokAuthMode::None && !force {
285 if !quiet {
286 eprintln!(" \u{26a0} Grok: no session token and no XAI_API_KEY.");
287 eprintln!(" Subscription: run `grok login`, then `lean-ctx proxy enable`.");
288 eprintln!(" API key: export XAI_API_KEY=…, then re-run proxy enable.");
289 }
290 return;
291 }
292 let mode = if mode == GrokAuthMode::None && force {
294 GrokAuthMode::Subscription
295 } else {
296 mode
297 };
298
299 if !is_proxy_reachable(port) {
300 if !quiet {
301 println!(" Skipping Grok proxy env (proxy not running on port {port})");
302 }
303 return;
304 }
305
306 let Some(proxy_url) = grok_proxy_base_url(port, mode) else {
307 return;
308 };
309 let config_path = grok_dir.join("config.toml");
310 let existing = std::fs::read_to_string(&config_path).unwrap_or_default();
311
312 match mode {
313 GrokAuthMode::Subscription => {
314 if grok_config_has_local_proxy_entry(&existing) {
317 let cleaned = strip_grok_proxy_entries(&existing);
318 if cleaned != existing {
319 let _ = std::fs::write(&config_path, cleaned);
320 if !quiet {
321 println!(
322 " \x1b[32m✓\x1b[0m Grok subscription: removed [endpoints].models_base_url \
323 (would force API-key auth)"
324 );
325 }
326 }
327 }
328 if !quiet {
329 println!(
330 " Configured Grok subscription rail: GROK_CLI_CHAT_PROXY_BASE_URL → {proxy_url}"
331 );
332 println!(
333 " (session Bearer forwarded to {GROK_CHAT_UPSTREAM}; shell export applied)"
334 );
335 }
336 }
337 GrokAuthMode::ApiKey => {
338 if let Some(current) = grok_models_base_url(&existing) {
341 if current == proxy_url {
342 if !quiet {
343 println!(" Grok API-key rail already configured");
344 }
345 return;
346 }
347 if !force
348 && let Some(custom) = normalize_url_opt(¤t)
349 && !is_local_lean_ctx_url(&custom)
350 && !custom.contains("/providers/xai/")
351 {
352 if !quiet {
353 eprintln!(
354 " \u{26a0} Grok: kept custom models_base_url ({current}); \
355 use `lean-ctx proxy enable --force` to override."
356 );
357 }
358 return;
359 }
360 }
361
362 let updated = upsert_grok_models_base_url(&existing, &proxy_url);
363 if updated != existing {
364 if let Some(parent) = config_path.parent() {
365 let _ = std::fs::create_dir_all(parent);
366 }
367 let _ = std::fs::write(&config_path, updated);
368 if !quiet {
369 println!(" Configured Grok [endpoints].models_base_url → proxy ({proxy_url})");
370 }
371 }
372 }
373 GrokAuthMode::None => {}
374 }
375}
376
377pub(crate) fn uninstall_grok_env_at(grok_dir: &Path, quiet: bool) {
378 let config_path = grok_dir.join("config.toml");
379 let existing = match std::fs::read_to_string(&config_path) {
380 Ok(s) if !s.trim().is_empty() => s,
381 _ => return,
382 };
383 if !grok_config_has_local_proxy_entry(&existing) {
384 return;
385 }
386 let cleaned = strip_grok_proxy_entries(&existing);
387 let _ = std::fs::write(&config_path, cleaned);
388 if !quiet {
389 println!(" \x1b[32m✓\x1b[0m Removed Grok proxy models_base_url from ~/.grok/config.toml");
390 }
391}
392
393pub(crate) fn grok_models_base_url(content: &str) -> Option<String> {
395 let doc = content.parse::<toml_edit::DocumentMut>().ok()?;
396 doc.get("endpoints")?
397 .get("models_base_url")?
398 .as_str()
399 .map(String::from)
400}
401
402pub(crate) fn grok_config_has_local_proxy_entry(content: &str) -> bool {
403 grok_models_base_url(content).is_some_and(|u| {
404 is_local_lean_ctx_url(&u) && (u.contains("/providers/xai") || u.contains("127.0.0.1"))
405 })
406}
407
408pub(crate) fn upsert_grok_models_base_url(existing: &str, proxy_url: &str) -> String {
414 let Ok(mut doc) = existing.parse::<toml_edit::DocumentMut>() else {
415 return existing.to_string();
416 };
417 if doc
419 .get("endpoints")
420 .is_some_and(|item| !item.is_table() && !item.is_inline_table() && !item.is_none())
421 {
422 doc["endpoints"] = toml_edit::table();
423 }
424 let endpoints = doc["endpoints"].or_insert(toml_edit::table());
425 endpoints["models_base_url"] = toml_edit::value(proxy_url);
426 doc.to_string()
427}
428
429pub(crate) fn strip_grok_proxy_entries(content: &str) -> String {
434 let Ok(mut doc) = content.parse::<toml_edit::DocumentMut>() else {
435 return content.to_string();
436 };
437 let should_strip = doc
438 .get("endpoints")
439 .and_then(|e| e.get("models_base_url"))
440 .and_then(|v| v.as_str())
441 .is_some_and(is_local_lean_ctx_url);
442 if !should_strip {
443 return content.to_string();
444 }
445 let empty = if let Some(tbl) = doc["endpoints"].as_table_mut() {
446 tbl.remove("models_base_url");
447 tbl.is_empty()
448 } else if let Some(tbl) = doc["endpoints"].as_inline_table_mut() {
449 tbl.remove("models_base_url");
450 tbl.is_empty()
451 } else {
452 return content.to_string();
453 };
454 if empty {
455 doc.remove("endpoints");
456 }
457 doc.to_string()
458}