dirge-agent 0.13.9

Minimalistic coding agent written in Rust, optimized for memory footprint and performance
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
use std::path::PathBuf;

use crate::auth::openai_oauth::normalize_optional_string;
use crate::auth::store::OpenAiOAuthCredential;
use crate::config::ProviderAuth;

#[derive(Clone, PartialEq, Eq)]
pub struct ProviderAuthHeaders {
    pub bearer_token: String,
    pub chatgpt_account_id: Option<String>,
}

// Hand-written so the live ChatGPT bearer token can never land in a log or
// panic message via `{:?}` — the derived Debug would print it verbatim.
impl std::fmt::Debug for ProviderAuthHeaders {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ProviderAuthHeaders")
            .field(
                "bearer_token",
                &if self.bearer_token.is_empty() {
                    "<unset>"
                } else {
                    "<redacted>"
                },
            )
            .field("chatgpt_account_id", &self.chatgpt_account_id)
            .finish()
    }
}

pub fn resolve_auth_headers(auth: ProviderAuth) -> anyhow::Result<Option<ProviderAuthHeaders>> {
    match auth {
        ProviderAuth::ApiKey => Ok(None),
        ProviderAuth::ChatGpt => Ok(Some(resolve_chatgpt_auth()?)),
        ProviderAuth::Anthropic => Ok(Some(resolve_anthropic_auth()?)),
    }
}

fn resolve_chatgpt_auth() -> anyhow::Result<ProviderAuthHeaders> {
    resolve_chatgpt_auth_from(
        std::env::var("CODEX_ACCESS_TOKEN").ok(),
        std::env::var("CHATGPT_ACCOUNT_ID").ok(),
        codex_auth_file_path(),
    )
}

fn resolve_chatgpt_auth_from(
    codex_access_token: Option<String>,
    chatgpt_account_id: Option<String>,
    auth_file_path: PathBuf,
) -> anyhow::Result<ProviderAuthHeaders> {
    resolve_chatgpt_auth_from_with_dirge_oauth(
        codex_access_token,
        chatgpt_account_id,
        auth_file_path,
        crate::provider::client::load_fresh_openai_oauth,
    )
}

fn resolve_chatgpt_auth_from_with_dirge_oauth(
    codex_access_token: Option<String>,
    chatgpt_account_id: Option<String>,
    auth_file_path: PathBuf,
    load_openai_oauth: impl FnOnce() -> anyhow::Result<Option<OpenAiOAuthCredential>>,
) -> anyhow::Result<ProviderAuthHeaders> {
    if let Some(token) = codex_access_token
        && !token.trim().is_empty()
    {
        return Ok(ProviderAuthHeaders {
            bearer_token: token.trim().to_string(),
            chatgpt_account_id: normalize_optional_string(chatgpt_account_id),
        });
    }

    // `dirge auth openai` writes Dirge's own refreshable OAuth credential.
    // Honor it for explicit `auth: chatgpt` before falling back to legacy
    // `codex login` storage; otherwise a stale ~/.codex/auth.json can keep
    // winning even after the user has completed the newer Dirge login flow.
    //
    // dirge-cu44: a present-but-unusable Dirge credential (expired with no
    // refresh token, refresh failed, or unreadable store) surfaces as Err.
    // Don't propagate it — that would hard-error a session a valid legacy
    // codex file could still serve. Warn and fall through instead.
    match load_openai_oauth() {
        Ok(Some(credential)) => {
            return Ok(ProviderAuthHeaders {
                bearer_token: credential.access_token().to_string(),
                chatgpt_account_id: credential.account_id().map(str::to_string),
            });
        }
        Ok(None) => {}
        Err(e) => {
            tracing::warn!(
                target: "dirge::provider",
                error = %e,
                "Dirge OpenAI OAuth credential present but unusable; falling back to legacy codex auth storage",
            );
        }
    }

    let raw = std::fs::read_to_string(&auth_file_path).map_err(|e| {
        anyhow::anyhow!(
            "ChatGPT auth requested, but CODEX_ACCESS_TOKEN is unset and Codex auth storage could not be read at {}: {e}. Run `codex login` or set CODEX_ACCESS_TOKEN.",
            auth_file_path.display()
        )
    })?;
    let json: serde_json::Value = serde_json::from_str(&raw).map_err(|e| {
        anyhow::anyhow!(
            "ChatGPT auth requested, but Codex auth storage at {} is not valid JSON: {e}",
            auth_file_path.display()
        )
    })?;

    let bearer_token = extract_string_by_keys(&json, &["access_token", "accessToken"])
        .ok_or_else(|| {
            anyhow::anyhow!(
                "ChatGPT auth requested, but no access token was found in {}. Run `codex login` again or set CODEX_ACCESS_TOKEN.",
                auth_file_path.display()
            )
        })?;
    let chatgpt_account_id = extract_string_by_keys(
        &json,
        &[
            "chatgpt_account_id",
            "chatgptAccountId",
            "chatgpt_account",
            "account_id",
            "accountId",
        ],
    );

    Ok(ProviderAuthHeaders {
        bearer_token,
        chatgpt_account_id,
    })
}

fn codex_auth_file_path() -> PathBuf {
    if let Ok(home) = std::env::var("CODEX_HOME")
        && !home.trim().is_empty()
    {
        return PathBuf::from(home).join("auth.json");
    }
    dirs::home_dir()
        .unwrap_or_else(|| PathBuf::from("."))
        .join(".codex")
        .join("auth.json")
}

fn resolve_anthropic_auth() -> anyhow::Result<ProviderAuthHeaders> {
    resolve_anthropic_auth_from(
        std::env::var("ANTHROPIC_OAUTH_TOKEN").ok(),
        anthropic_credentials_file_path(),
    )
}

fn resolve_anthropic_auth_from(
    oauth_token: Option<String>,
    credentials_file_path: PathBuf,
) -> anyhow::Result<ProviderAuthHeaders> {
    if let Some(token) = oauth_token
        && !token.trim().is_empty()
    {
        return Ok(ProviderAuthHeaders {
            bearer_token: token.trim().to_string(),
            chatgpt_account_id: None,
        });
    }

    let raw = std::fs::read_to_string(&credentials_file_path).map_err(|e| {
        anyhow::anyhow!(
            "Anthropic OAuth requested, but ANTHROPIC_OAUTH_TOKEN is unset and Claude credentials could not be read at {}: {e}. Run `claude login` or set ANTHROPIC_OAUTH_TOKEN.",
            credentials_file_path.display()
        )
    })?;
    let json: serde_json::Value = serde_json::from_str(&raw).map_err(|e| {
        anyhow::anyhow!(
            "Anthropic OAuth requested, but Claude credentials at {} are not valid JSON: {e}",
            credentials_file_path.display()
        )
    })?;

    let mut bearer_token = extract_string_by_keys(&json, &["accessToken", "access_token"])
        .ok_or_else(|| {
            anyhow::anyhow!(
                "Anthropic OAuth requested, but no access token was found in {}. Run `dirge auth anthropic` again or set ANTHROPIC_OAUTH_TOKEN.",
                credentials_file_path.display()
            )
        })?;

    if anthropic_token_is_expired(&json)
        && let Some(refresh) = extract_string_by_keys(&json, &["refreshToken", "refresh_token"])
    {
        let refreshed = refresh_anthropic_token_sync(&refresh)?;
        crate::provider::anthropic_oauth::persist_credentials(&refreshed)?;
        bearer_token = refreshed.access_token;
    }

    Ok(ProviderAuthHeaders {
        bearer_token,
        chatgpt_account_id: None,
    })
}

fn anthropic_credentials_file_path() -> PathBuf {
    crate::provider::anthropic_oauth::credentials_file_path()
}

fn anthropic_token_is_expired(value: &serde_json::Value) -> bool {
    let Some(expires_at) = extract_i64_by_keys(value, &["expiresAt", "expires_at", "expires"])
    else {
        return false;
    };
    crate::auth::file_store::epoch_ms_is_expired(expires_at, chrono::Utc::now().timestamp_millis())
}

fn refresh_anthropic_token_sync(
    refresh_token: &str,
) -> anyhow::Result<crate::provider::anthropic_oauth::AnthropicOAuthCredentials> {
    let refresh_token = refresh_token.to_string();
    std::thread::spawn(move || {
        let runtime = tokio::runtime::Runtime::new()?;
        runtime.block_on(crate::provider::anthropic_oauth::refresh_token(
            &refresh_token,
        ))
    })
    .join()
    .map_err(|panic| anyhow::anyhow!("Anthropic OAuth refresh thread panicked: {panic:?}"))?
}

fn extract_i64_by_keys(value: &serde_json::Value, keys: &[&str]) -> Option<i64> {
    if let serde_json::Value::Object(map) = value {
        for key in keys {
            if let Some(n) = map.get(*key).and_then(serde_json::Value::as_i64) {
                return Some(n);
            }
        }
        for child in map.values() {
            if let Some(n) = extract_i64_by_keys(child, keys) {
                return Some(n);
            }
        }
    } else if let serde_json::Value::Array(items) = value {
        for child in items {
            if let Some(n) = extract_i64_by_keys(child, keys) {
                return Some(n);
            }
        }
    }
    None
}

fn extract_string_by_keys(value: &serde_json::Value, keys: &[&str]) -> Option<String> {
    if let serde_json::Value::Object(map) = value {
        for key in keys {
            if let Some(s) = map
                .get(*key)
                .and_then(serde_json::Value::as_str)
                .map(str::trim)
                .filter(|s| !s.is_empty())
            {
                return Some(s.to_string());
            }
        }
        for child in map.values() {
            if let Some(s) = extract_string_by_keys(child, keys) {
                return Some(s);
            }
        }
    } else if let serde_json::Value::Array(items) = value {
        for child in items {
            if let Some(s) = extract_string_by_keys(child, keys) {
                return Some(s);
            }
        }
    }
    None
}

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

    #[test]
    fn extracts_nested_codex_access_token_and_account_id() {
        let value = serde_json::json!({
            "chatgpt_auth_tokens": {
                "access_token": "token-123",
                "refresh_token": "must-not-win"
            },
            "chatgpt_account_id": "acct-456"
        });

        assert_eq!(
            extract_string_by_keys(&value, &["access_token", "accessToken"]).as_deref(),
            Some("token-123")
        );
        assert_eq!(
            extract_string_by_keys(&value, &["chatgpt_account_id"]).as_deref(),
            Some("acct-456")
        );
    }

    #[test]
    fn debug_redacts_bearer_token() {
        let headers = ProviderAuthHeaders {
            bearer_token: "super-secret-token".to_string(),
            chatgpt_account_id: Some("acct-1".to_string()),
        };
        let rendered = format!("{headers:?}");
        assert!(
            !rendered.contains("super-secret-token"),
            "bearer token must not appear in Debug output: {rendered}"
        );
        assert!(rendered.contains("<redacted>"), "{rendered}");
    }

    #[test]
    fn codex_access_token_env_wins() {
        let headers = resolve_chatgpt_auth_from(
            Some(" env-token ".to_string()),
            Some("acct-env".to_string()),
            PathBuf::from("/should/not/be/read"),
        )
        .unwrap();

        assert_eq!(headers.bearer_token, "env-token");
        assert_eq!(headers.chatgpt_account_id.as_deref(), Some("acct-env"));
    }

    #[test]
    fn dirge_openai_oauth_wins_over_codex_auth_file() {
        let dir = std::env::temp_dir().join(format!("dirge-chatgpt-auth-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("auth.json");
        std::fs::write(
            &path,
            r#"{ "tokens": { "access_token": "stale-codex-token", "account_id": "acct-codex" } }"#,
        )
        .unwrap();

        let headers = resolve_chatgpt_auth_from_with_dirge_oauth(None, None, path, || {
            Ok(Some(OpenAiOAuthCredential::new(
                "fresh-dirge-token",
                "refresh-token",
                None,
                Some("acct-dirge".to_string()),
                i64::MAX,
            )))
        })
        .unwrap();

        assert_eq!(headers.bearer_token, "fresh-dirge-token");
        assert_eq!(headers.chatgpt_account_id.as_deref(), Some("acct-dirge"));

        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn unrefreshable_dirge_oauth_falls_back_to_codex_auth_file() {
        // dirge-cu44: an expired Dirge OAuth credential whose refresh fails
        // surfaces as an Err from the loader. That must NOT block a valid
        // legacy codex auth file — otherwise a stale-but-broken Dirge login
        // hard-errors a session that `codex login` could have served.
        let dir = std::env::temp_dir().join(format!(
            "dirge-chatgpt-auth-fallback-{}",
            std::process::id()
        ));
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("auth.json");
        std::fs::write(
            &path,
            r#"{ "tokens": { "access_token": "codex-token", "account_id": "acct-codex" } }"#,
        )
        .unwrap();

        let headers = resolve_chatgpt_auth_from_with_dirge_oauth(None, None, path, || {
            anyhow::bail!("Stored OpenAI OAuth credential is expired and could not be refreshed")
        })
        .unwrap();

        assert_eq!(headers.bearer_token, "codex-token");
        assert_eq!(headers.chatgpt_account_id.as_deref(), Some("acct-codex"));

        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn anthropic_access_token_env_wins() {
        let headers = resolve_anthropic_auth_from(
            Some(" oat-env-token ".to_string()),
            PathBuf::from("/should/not/be/read"),
        )
        .unwrap();

        assert_eq!(headers.bearer_token, "oat-env-token");
        assert_eq!(headers.chatgpt_account_id, None);
    }

    #[test]
    fn anthropic_refresh_sync_does_not_panic_on_current_thread_runtime() {
        let runtime = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .unwrap();
        runtime.block_on(async {
            let result =
                std::panic::catch_unwind(|| refresh_anthropic_token_sync("invalid-refresh-token"));
            assert!(
                result.is_ok(),
                "refresh entrypoint must not panic on current_thread runtime"
            );
        });
    }

    #[test]
    fn anthropic_reads_credentials_file_access_token() {
        let dir = std::env::temp_dir().join(format!("dirge-anthropic-auth-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join(".credentials.json");
        std::fs::write(
            &path,
            r#"{ "claudeAiOauth": { "accessToken": "sk-ant-oat-file", "refreshToken": "no" } }"#,
        )
        .unwrap();

        let headers = resolve_anthropic_auth_from(None, path.clone()).unwrap();
        assert_eq!(headers.bearer_token, "sk-ant-oat-file");

        std::fs::remove_dir_all(&dir).ok();
    }
}