rotom 1.5.1

OpenAI- and Anthropic-compatible local API gateway backed by OAuth providers.
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
fn resolve_model_fallback(
    cli_or_option: Option<String>,
    config: Option<&AppConfig>,
) -> Option<String> {
    cli_or_option
        .or_else(|| config_string(config, |item| item.model_fallback.clone()))
        .or_else(|| Some(DEFAULT_MODEL_FALLBACK.to_owned()))
}

fn resolve_login_provider(
    store: &AuthStore,
    provider: Option<String>,
    kiro: bool,
    cursor: bool,
) -> Result<Provider> {
    if kiro {
        return Ok(Provider::Kiro);
    }
    if cursor {
        return Ok(Provider::Cursor);
    }
    provider.map_or_else(|| prompt_login_provider(store), |value| value.parse())
}

fn prompt_login_provider(store: &AuthStore) -> Result<Provider> {
    let credentials = store.load_all()?;
    println!("Select OAuth provider:");
    for (index, provider) in LOGIN_PROVIDERS.iter().enumerate() {
        println!(
            "[{}] {}",
            index + 1,
            format_login_provider_choice(*provider, &credentials)
        );
    }
    print!("Provider [1]: ");
    io::stdout().flush()?;

    let mut input = String::new();
    io::stdin().read_line(&mut input)?;
    parse_login_provider_choice(input.trim())
}

const LOGIN_PROVIDERS: [Provider; 4] = [
    Provider::Codex,
    Provider::Grok,
    Provider::Kiro,
    Provider::Cursor,
];

fn parse_login_provider_choice(value: &str) -> Result<Provider> {
    match value {
        "" | "1" => Ok(Provider::Codex),
        "2" => Ok(Provider::Grok),
        "3" => Ok(Provider::Kiro),
        "4" => Ok(Provider::Cursor),
        other => other.parse(),
    }
}

fn format_login_provider_choice(provider: Provider, credentials: &[Credentials]) -> String {
    let label = login_provider_label(provider);
    credentials
        .iter()
        .find(|item| item.provider == provider)
        .map_or_else(
            || label.to_owned(),
            |item| format!("{label} ({})", login_provider_status(item)),
        )
}

const fn login_provider_label(provider: Provider) -> &'static str {
    match provider {
        Provider::Codex => "openai",
        Provider::Grok => "grok",
        Provider::Kiro => "kiro",
        Provider::Cursor => "cursor",
    }
}

fn login_provider_status(credentials: &Credentials) -> String {
    let remaining_secs = credentials.expires_at.saturating_sub(now_unix());
    if remaining_secs == 0 {
        "logged in, expired".to_owned()
    } else {
        format!("logged in, expires in {}", format_duration(remaining_secs))
    }
}

fn resolve_served_providers(
    store: &AuthStore,
    cli_or_option: Option<String>,
    config: Option<&AppConfig>,
) -> Result<Vec<Provider>> {
    if let Some(value) = cli_or_option {
        return Ok(vec![value.parse()?]);
    }

    let mut providers = store
        .load_all()?
        .into_iter()
        .map(|credentials| credentials.provider)
        .collect::<Vec<_>>();
    if providers.is_empty() {
        providers.push(config.and_then(|item| item.provider).unwrap_or_default());
    }
    providers.sort_unstable();
    providers.dedup();
    Ok(providers)
}

fn reset_config(store: &AppConfigStore) -> Result<()> {
    store.delete()?;
    println!("removed runtime config at {}", store.path().display());
    Ok(())
}

/// Runs the interactive OAuth login flow and persists the resulting credentials.
async fn login(store: AuthStore, provider: Provider, originator: &str) -> Result<()> {
    let http = Client::new();
    let existing_providers = store
        .load_all()?
        .into_iter()
        .map(|credentials| credentials.provider)
        .collect::<Vec<_>>();
    let is_new_provider = !existing_providers.contains(&provider);
    let show_daemon_restart_hint = is_new_provider && !existing_providers.is_empty();
    if provider == Provider::Kiro {
        return login_kiro(store, http, show_daemon_restart_hint).await;
    }
    if provider == Provider::Cursor {
        return login_cursor(store, http, show_daemon_restart_hint).await;
    }
    let flow = match provider {
        Provider::Codex => create_authorization_flow(originator)?,
        Provider::Grok => {
            GrokOAuthClient::default()
                .create_authorization_flow()
                .await?
        }
        Provider::Kiro => unreachable!("Kiro login is handled before generic OAuth flow"),
        Provider::Cursor => unreachable!("Cursor login is handled before generic OAuth flow"),
    };
    println!(
        "Open this URL to authenticate with {}:\n{}\n",
        provider.display_name(),
        flow.authorize_url
    );
    println!(
        "After login, your browser may fail to load the localhost callback. Copy the full address from the browser address bar and paste it here."
    );

    let code = prompt_authorization_code(&flow.state)?;
    let credentials = match provider {
        Provider::Codex => {
            CodexOAuthClient::new(http)
                .exchange_authorization_code(&code, &flow.verifier)
                .await?
        }
        Provider::Grok => {
            GrokOAuthClient::default()
                .exchange_authorization_code(&code, &flow.verifier)
                .await?
        }
        Provider::Kiro => unreachable!("Kiro login is handled before generic OAuth flow"),
        Provider::Cursor => unreachable!("Cursor login is handled before generic OAuth flow"),
    };
    store.save(&credentials)?;
    let subject = credential_subject(&credentials);
    println!(
        "logged in {subject} and saved credentials to {}",
        store.path().display()
    );
    if show_daemon_restart_hint {
        println!("{}", new_provider_daemon_restart_hint(provider));
    }
    Ok(())
}

async fn login_cursor(
    store: AuthStore,
    http: Client,
    show_daemon_restart_hint: bool,
) -> Result<()> {
    let client = CursorOAuthClient::new(http);
    let flow = client.create_authorization_flow()?;
    if open_browser_url(flow.authorize_url.as_str()) {
        println!("Signing in with the browser...");
        println!(
            "If your browser didn't open, open this URL to authenticate with Cursor:\n{}\n",
            flow.authorize_url
        );
    } else {
        println!(
            "Open this URL to authenticate with Cursor:\n{}\n",
            flow.authorize_url
        );
    }
    println!("After login, leave this command running; rotom will poll Cursor for the result.");

    let credentials = client.wait_for_browser_login(&flow).await?;
    store.save(&credentials)?;
    let subject = credential_subject(&credentials);
    println!(
        "logged in {subject} and saved credentials to {}",
        store.path().display()
    );
    if show_daemon_restart_hint {
        println!("{}", new_provider_daemon_restart_hint(Provider::Cursor));
    }
    Ok(())
}

fn open_browser_url(url: &str) -> bool {
    if std::env::var_os("NO_OPEN_BROWSER").is_some() {
        return false;
    }

    open_browser_command(url)
        .status()
        .is_ok_and(|status| status.success())
}

#[cfg(target_os = "macos")]
fn open_browser_command(url: &str) -> ProcessCommand {
    let mut command = ProcessCommand::new("open");
    command.arg(url);
    command
}

#[cfg(target_os = "windows")]
fn open_browser_command(url: &str) -> ProcessCommand {
    let mut command = ProcessCommand::new("cmd");
    command.args(["/C", "start", "", url]);
    command
}

#[cfg(all(unix, not(target_os = "macos")))]
fn open_browser_command(url: &str) -> ProcessCommand {
    let mut command = ProcessCommand::new("xdg-open");
    command.arg(url);
    command
}

async fn login_kiro(store: AuthStore, http: Client, show_daemon_restart_hint: bool) -> Result<()> {
    let flow = KiroOAuthClient::create_authorization_flow()?;
    println!(
        "Open this URL to authenticate with Kiro:\n{}\n",
        flow.authorize_url
    );
    println!(
        "After login, paste the full Kiro callback URL from the browser address bar, including login_option and code."
    );

    let callback = prompt_kiro_authorization_callback(&flow.state)?;
    let credentials = KiroOAuthClient::new(http)
        .exchange_authorization_callback(&callback, &flow.verifier)
        .await?;
    store.save(&credentials)?;
    let subject = credential_subject(&credentials);
    println!(
        "logged in {subject} and saved credentials to {}",
        store.path().display()
    );
    if show_daemon_restart_hint {
        println!("{}", new_provider_daemon_restart_hint(Provider::Kiro));
    }
    Ok(())
}

fn prompt_kiro_authorization_callback(expected_state: &str) -> Result<KiroAuthorizationCallback> {
    print!("Paste the full Kiro callback URL: ");
    io::stdout().flush()?;

    let mut input = String::new();
    io::stdin().read_line(&mut input)?;
    let callback = parse_kiro_authorization_callback(&input)?;
    if callback
        .state
        .as_deref()
        .is_some_and(|state| state != expected_state)
    {
        return Err(Error::oauth("state mismatch"));
    }
    Ok(callback)
}

fn new_provider_daemon_restart_hint(provider: Provider) -> String {
    format!(
        "If rotom daemon is already running, run `rotom daemon restart` to serve newly logged-in {} models.",
        provider.display_name()
    )
}

/// Forces a refresh of the saved OAuth credentials and writes them back to disk.
async fn refresh(store: AuthStore, provider: Option<String>) -> Result<()> {
    let credentials = if let Some(provider) = provider {
        let provider = provider.parse::<Provider>()?;
        store.load_provider(provider)?.ok_or_else(|| {
            Error::config(format!(
                "not logged in for {provider}; run `rotom login --provider {provider}` first"
            ))
        })?
    } else {
        let all = store.load_all()?;
        if all.is_empty() {
            return Err(Error::config("not logged in; run `rotom login` first"));
        }
        for credentials in all {
            let refreshed = refresh_credentials(&credentials).await?;
            store.save(&refreshed)?;
            println!("refreshed {}", credential_subject(&refreshed));
        }
        return Ok(());
    };

    let refreshed = refresh_credentials(&credentials).await?;
    store.save(&refreshed)?;
    println!("refreshed {}", credential_subject(&refreshed));
    Ok(())
}

async fn refresh_credentials(credentials: &Credentials) -> Result<Credentials> {
    match credentials.provider {
        Provider::Codex => {
            CodexOAuthClient::default()
                .refresh_token(&credentials.refresh_token)
                .await
        }
        Provider::Grok => {
            GrokOAuthClient::default()
                .refresh_token(&credentials.refresh_token)
                .await
        }
        Provider::Kiro => {
            KiroOAuthClient::default()
                .refresh_token(&credentials.refresh_token)
                .await
        }
        Provider::Cursor => {
            CursorOAuthClient::default()
                .refresh_token(&credentials.refresh_token)
                .await
        }
    }
}

fn kiro_command(command: KiroCommand) -> Result<()> {
    match command {
        KiroCommand::Import {
            auth_file,
            source,
            path,
        } => import_kiro(auth_file, &source, path.as_deref()),
    }
}

fn import_kiro(
    auth_file: Option<PathBuf>,
    source: &str,
    path: Option<&std::path::Path>,
) -> Result<()> {
    let store = auth_store(auth_file)?;
    let (credentials, imported_from) = import_kiro_credentials(source, path)?;
    store.save(&credentials)?;
    println!(
        "imported Kiro credentials from {imported_from} and saved them to {}",
        store.path().display()
    );
    println!("Kiro credentials are ready for refresh, status, model listing, and API serving.");
    Ok(())
}

fn import_kiro_credentials(
    source: &str,
    path: Option<&std::path::Path>,
) -> Result<(Credentials, String)> {
    match source.trim().to_ascii_lowercase().as_str() {
        "auto" => {
            if path.is_some() {
                return Err(Error::config(
                    "use --from cli or --from desktop when passing an explicit Kiro credential path",
                ));
            }
            let cli_path = default_cli_database_path()?;
            if cli_path.exists() {
                return Ok((
                    KiroOAuthClient::import_cli_database(&cli_path)?,
                    cli_path.display().to_string(),
                ));
            }
            let desktop_path = default_desktop_token_path()?;
            if desktop_path.exists() {
                return Ok((
                    KiroOAuthClient::import_desktop_file(&desktop_path)?,
                    desktop_path.display().to_string(),
                ));
            }
            Err(Error::config(
                "no Kiro CLI or desktop credential store found; pass --from cli --path ... or --from desktop --path ...",
            ))
        }
        "cli" => {
            let owned;
            let path = if let Some(path) = path {
                path
            } else {
                owned = default_cli_database_path()?;
                &owned
            };
            Ok((
                KiroOAuthClient::import_cli_database(path)?,
                path.display().to_string(),
            ))
        }
        "desktop" | "ide" => {
            let owned;
            let path = if let Some(path) = path {
                path
            } else {
                owned = default_desktop_token_path()?;
                &owned
            };
            Ok((
                KiroOAuthClient::import_desktop_file(path)?,
                path.display().to_string(),
            ))
        }
        other => Err(Error::config(format!(
            "unknown Kiro credential source: {other}; expected auto, cli, or desktop"
        ))),
    }
}