pulpod 0.0.42

Pulpo daemon — manages agent sessions via tmux/Docker
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
use std::path::Path;

/// Extracted authentication info from agent credentials.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AuthInfo {
    pub provider: String,
    pub plan: Option<String>,
    pub email: Option<String>,
}

/// Known agent command names mapped to their credential extractors.
const KNOWN_AGENTS: &[(&str, &str)] = &[
    ("claude", "claude.ai"),
    ("codex", "openai"),
    ("gemini", "google"),
];

/// Check if a command string contains a known agent name.
/// Returns the provider string if found.
pub fn agent_provider_for_command(command: &str) -> Option<&'static str> {
    let lower = command.to_lowercase();
    for &(agent, provider) in KNOWN_AGENTS {
        // Match the agent name as a word boundary: at start, after whitespace, or after /
        for (i, _) in lower.match_indices(agent) {
            let before_ok = i == 0
                || lower.as_bytes().get(i - 1).is_some_and(|&b| {
                    b == b' ' || b == b'/' || b == b'\t' || b == b'\n' || b == b';' || b == b'&'
                });
            let after = i + agent.len();
            let after_ok = after >= lower.len()
                || lower.as_bytes().get(after).is_some_and(|&b| {
                    b == b' ' || b == b'\t' || b == b'\n' || b == b';' || b == b'&'
                });
            if before_ok && after_ok {
                return Some(provider);
            }
        }
    }
    None
}

/// Extract auth info from Claude Code credentials.
///
/// Reads `<claude_dir>/.credentials.json` and parses the JSON to find
/// `subscriptionType` and email fields from the OAuth data.
///
/// On macOS, tries the keychain first via `security find-generic-password`.
pub fn extract_claude_auth(claude_dir: &Path) -> Option<AuthInfo> {
    let creds_path = claude_dir.join(".credentials.json");
    let json_str = read_file_to_string(&creds_path)?;
    parse_claude_credentials(&json_str)
}

/// Parse Claude credentials JSON and extract auth info.
fn parse_claude_credentials(json_str: &str) -> Option<AuthInfo> {
    let value: serde_json::Value = serde_json::from_str(json_str).ok()?;

    // The credentials file may have different structures.
    // Common patterns:
    // - Top-level object with claudeAiOauth key containing { accessToken, ... }
    // - Or a direct object with subscriptionType, email fields

    let mut plan = None;
    let mut email = None;

    // Try claudeAiOauth path first
    if let Some(oauth) = value.get("claudeAiOauth") {
        plan = oauth
            .get("subscriptionType")
            .and_then(|v| v.as_str())
            .map(str::to_lowercase);
        email = oauth
            .get("email")
            .and_then(|v| v.as_str())
            .map(String::from);
        if email.is_none() {
            email = oauth
                .get("account")
                .and_then(|a| a.get("email"))
                .and_then(|v| v.as_str())
                .map(String::from);
        }
    }

    // Fall back to top-level fields
    if plan.is_none() {
        plan = value
            .get("subscriptionType")
            .and_then(|v| v.as_str())
            .map(str::to_lowercase);
    }
    if email.is_none() {
        email = value
            .get("email")
            .and_then(|v| v.as_str())
            .map(String::from);
    }

    // If we found nothing useful, return None
    if plan.is_none() && email.is_none() {
        return None;
    }

    Some(AuthInfo {
        provider: "claude.ai".to_owned(),
        plan,
        email,
    })
}

/// Extract auth info from `OpenAI` Codex credentials.
///
/// Reads `<codex_dir>/auth.json` and looks for plan/account info.
pub fn extract_codex_auth(codex_dir: &Path) -> Option<AuthInfo> {
    let auth_path = codex_dir.join("auth.json");
    let json_str = read_file_to_string(&auth_path)?;
    parse_codex_credentials(&json_str)
}

/// Parse Codex auth JSON and extract auth info.
fn parse_codex_credentials(json_str: &str) -> Option<AuthInfo> {
    let value: serde_json::Value = serde_json::from_str(json_str).ok()?;

    let plan = value
        .get("plan")
        .and_then(|v| v.as_str())
        .map(str::to_lowercase);
    let email = value
        .get("email")
        .and_then(|v| v.as_str())
        .map(String::from);

    if plan.is_none() && email.is_none() {
        return None;
    }

    Some(AuthInfo {
        provider: "openai".to_owned(),
        plan,
        email,
    })
}

/// Extract auth info from Google Gemini credentials.
///
/// Reads files under `<gemini_dir>/` for Google account info.
pub fn extract_gemini_auth(gemini_dir: &Path) -> Option<AuthInfo> {
    // Try config.json first, then credentials.json
    for filename in &["config.json", "credentials.json"] {
        let path = gemini_dir.join(filename);
        if let Some(json_str) = read_file_to_string(&path)
            && let Some(info) = parse_gemini_credentials(&json_str)
        {
            return Some(info);
        }
    }
    None
}

/// Parse Gemini credentials JSON and extract auth info.
fn parse_gemini_credentials(json_str: &str) -> Option<AuthInfo> {
    let value: serde_json::Value = serde_json::from_str(json_str).ok()?;

    let plan = value
        .get("plan")
        .or_else(|| value.get("tier"))
        .and_then(|v| v.as_str())
        .map(str::to_lowercase);
    let email = value
        .get("email")
        .or_else(|| value.get("account"))
        .and_then(|v| v.as_str())
        .map(String::from);

    if plan.is_none() && email.is_none() {
        return None;
    }

    Some(AuthInfo {
        provider: "google".to_owned(),
        plan,
        email,
    })
}

/// Try all known credential sources and return whatever is found.
/// Tries Claude, Codex, and Gemini in order.
#[cfg(not(coverage))]
pub fn detect_auth_info() -> Vec<AuthInfo> {
    let mut results = Vec::new();
    if let Some(home) = dirs::home_dir() {
        if let Some(info) = extract_claude_auth(&home.join(".claude")) {
            results.push(info);
        }
        if let Some(info) = extract_codex_auth(&home.join(".codex")) {
            results.push(info);
        }
        if let Some(info) = extract_gemini_auth(&home.join(".gemini")) {
            results.push(info);
        }
    }
    results
}

/// Under coverage builds, return empty (no real filesystem access).
#[cfg(coverage)]
pub fn detect_auth_info() -> Vec<AuthInfo> {
    Vec::new()
}

/// Detect auth info for a specific provider based on the session command.
/// Only reads credentials for the agent detected in the command.
#[cfg(not(coverage))]
pub fn detect_auth_for_command(command: &str) -> Option<AuthInfo> {
    let provider = agent_provider_for_command(command)?;
    let home = dirs::home_dir()?;
    match provider {
        "claude.ai" => extract_claude_auth(&home.join(".claude")),
        "openai" => extract_codex_auth(&home.join(".codex")),
        "google" => extract_gemini_auth(&home.join(".gemini")),
        _ => None,
    }
}

/// Under coverage builds, return None (no real filesystem access).
#[cfg(coverage)]
pub fn detect_auth_for_command(command: &str) -> Option<AuthInfo> {
    // Still validate the command contains a known agent
    agent_provider_for_command(command)?;
    None
}

/// Read a file to string, returning None on any error.
#[cfg(not(coverage))]
fn read_file_to_string(path: &Path) -> Option<String> {
    std::fs::read_to_string(path).ok()
}

/// Under coverage, never read real files.
#[cfg(coverage)]
fn read_file_to_string(_path: &Path) -> Option<String> {
    None
}

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

    // -- agent_provider_for_command tests --

    #[test]
    fn test_detects_claude_command() {
        assert_eq!(
            agent_provider_for_command("claude -p 'review code'"),
            Some("claude.ai")
        );
    }

    #[test]
    fn test_detects_claude_with_path() {
        assert_eq!(
            agent_provider_for_command("/usr/local/bin/claude --help"),
            Some("claude.ai")
        );
    }

    #[test]
    fn test_detects_codex_command() {
        assert_eq!(
            agent_provider_for_command("codex run tests"),
            Some("openai")
        );
    }

    #[test]
    fn test_detects_gemini_command() {
        assert_eq!(agent_provider_for_command("gemini chat"), Some("google"));
    }

    #[test]
    fn test_no_agent_in_command() {
        assert_eq!(agent_provider_for_command("cargo test --workspace"), None);
    }

    #[test]
    fn test_no_partial_match() {
        // "claudette" should not match "claude"
        assert_eq!(agent_provider_for_command("claudette run"), None);
    }

    #[test]
    fn test_agent_after_semicolon() {
        assert_eq!(
            agent_provider_for_command("cd /repo; claude -p 'fix'"),
            Some("claude.ai")
        );
    }

    #[test]
    fn test_agent_after_ampersand() {
        assert_eq!(
            agent_provider_for_command("export FOO=1 && codex run"),
            Some("openai")
        );
    }

    #[test]
    fn test_agent_at_end_of_command() {
        assert_eq!(agent_provider_for_command("exec claude"), Some("claude.ai"));
    }

    #[test]
    fn test_empty_command() {
        assert_eq!(agent_provider_for_command(""), None);
    }

    // -- parse_claude_credentials tests --

    #[test]
    fn test_parse_claude_with_oauth() {
        let json = r#"{
            "claudeAiOauth": {
                "subscriptionType": "Max",
                "email": "user@example.com"
            }
        }"#;
        let info = parse_claude_credentials(json).unwrap();
        assert_eq!(info.provider, "claude.ai");
        assert_eq!(info.plan.as_deref(), Some("max"));
        assert_eq!(info.email.as_deref(), Some("user@example.com"));
    }

    #[test]
    fn test_parse_claude_with_oauth_account_email() {
        let json = r#"{
            "claudeAiOauth": {
                "subscriptionType": "Pro",
                "account": { "email": "nested@example.com" }
            }
        }"#;
        let info = parse_claude_credentials(json).unwrap();
        assert_eq!(info.plan.as_deref(), Some("pro"));
        assert_eq!(info.email.as_deref(), Some("nested@example.com"));
    }

    #[test]
    fn test_parse_claude_top_level_fields() {
        let json = r#"{
            "subscriptionType": "Plus",
            "email": "toplevel@example.com"
        }"#;
        let info = parse_claude_credentials(json).unwrap();
        assert_eq!(info.plan.as_deref(), Some("plus"));
        assert_eq!(info.email.as_deref(), Some("toplevel@example.com"));
    }

    #[test]
    fn test_parse_claude_no_useful_fields() {
        let json = r#"{"accessToken": "abc123"}"#;
        assert!(parse_claude_credentials(json).is_none());
    }

    #[test]
    fn test_parse_claude_invalid_json() {
        assert!(parse_claude_credentials("not json").is_none());
    }

    #[test]
    fn test_parse_claude_empty() {
        assert!(parse_claude_credentials("").is_none());
    }

    #[test]
    fn test_parse_claude_plan_only() {
        let json = r#"{"claudeAiOauth": {"subscriptionType": "Max"}}"#;
        let info = parse_claude_credentials(json).unwrap();
        assert_eq!(info.plan.as_deref(), Some("max"));
        assert!(info.email.is_none());
    }

    // -- parse_codex_credentials tests --

    #[test]
    fn test_parse_codex_full() {
        let json = r#"{"plan": "Plus", "email": "codex@example.com"}"#;
        let info = parse_codex_credentials(json).unwrap();
        assert_eq!(info.provider, "openai");
        assert_eq!(info.plan.as_deref(), Some("plus"));
        assert_eq!(info.email.as_deref(), Some("codex@example.com"));
    }

    #[test]
    fn test_parse_codex_no_useful_fields() {
        let json = r#"{"apiKey": "sk-..."}"#;
        assert!(parse_codex_credentials(json).is_none());
    }

    #[test]
    fn test_parse_codex_invalid_json() {
        assert!(parse_codex_credentials("{bad}").is_none());
    }

    #[test]
    fn test_parse_codex_plan_only() {
        let json = r#"{"plan": "Pro"}"#;
        let info = parse_codex_credentials(json).unwrap();
        assert_eq!(info.plan.as_deref(), Some("pro"));
        assert!(info.email.is_none());
    }

    // -- parse_gemini_credentials tests --

    #[test]
    fn test_parse_gemini_full() {
        let json = r#"{"plan": "Ultra", "email": "gemini@google.com"}"#;
        let info = parse_gemini_credentials(json).unwrap();
        assert_eq!(info.provider, "google");
        assert_eq!(info.plan.as_deref(), Some("ultra"));
        assert_eq!(info.email.as_deref(), Some("gemini@google.com"));
    }

    #[test]
    fn test_parse_gemini_with_tier() {
        let json = r#"{"tier": "Pro", "account": "user@gmail.com"}"#;
        let info = parse_gemini_credentials(json).unwrap();
        assert_eq!(info.plan.as_deref(), Some("pro"));
        assert_eq!(info.email.as_deref(), Some("user@gmail.com"));
    }

    #[test]
    fn test_parse_gemini_no_useful_fields() {
        let json = r#"{"token": "abc"}"#;
        assert!(parse_gemini_credentials(json).is_none());
    }

    #[test]
    fn test_parse_gemini_invalid_json() {
        assert!(parse_gemini_credentials("???").is_none());
    }

    // -- extract functions with temp dirs --

    #[test]
    fn test_extract_claude_auth_nonexistent_dir() {
        let info = extract_claude_auth(Path::new("/nonexistent/path/.claude"));
        // Under coverage, read_file_to_string returns None; in normal builds,
        // the file doesn't exist so it also returns None.
        assert!(info.is_none());
    }

    #[test]
    fn test_extract_codex_auth_nonexistent_dir() {
        assert!(extract_codex_auth(Path::new("/nonexistent/.codex")).is_none());
    }

    #[test]
    fn test_extract_gemini_auth_nonexistent_dir() {
        assert!(extract_gemini_auth(Path::new("/nonexistent/.gemini")).is_none());
    }

    // -- detect_auth_info / detect_auth_for_command --

    #[test]
    fn test_detect_auth_info_returns_vec() {
        // In test/coverage mode, this returns empty or whatever is on disk.
        // The important thing is it doesn't panic.
        let _ = detect_auth_info();
    }

    #[test]
    fn test_detect_auth_for_command_no_agent() {
        assert!(detect_auth_for_command("cargo build").is_none());
    }

    #[test]
    fn test_detect_auth_for_command_with_agent() {
        // Won't find credentials in test env, but shouldn't panic
        let result = detect_auth_for_command("claude -p 'test'");
        // Under coverage: returns None (agent found but no fs access)
        // Under normal: returns None (no credentials on disk in CI)
        // Either way, no panic
        let _ = result;
    }

    // -- agent_provider_for_command edge cases --

    #[test]
    fn test_no_match_for_substring_codex() {
        // "mycodex" should not match "codex"
        assert_eq!(agent_provider_for_command("mycodex run"), None);
    }

    #[test]
    fn test_agent_with_pipe() {
        // "claude" appears after a pipe — the | is not in the boundary chars,
        // but it's preceded by space: "| claude"
        assert_eq!(
            agent_provider_for_command("echo foo | claude -p 'fix'"),
            Some("claude.ai")
        );
    }

    #[test]
    fn test_agent_case_insensitive() {
        assert_eq!(
            agent_provider_for_command("Claude -p 'test'"),
            Some("claude.ai")
        );
        assert_eq!(agent_provider_for_command("CODEX run"), Some("openai"));
        assert_eq!(agent_provider_for_command("GEMINI chat"), Some("google"));
    }

    #[test]
    fn test_agent_after_tab() {
        assert_eq!(
            agent_provider_for_command("cd /repo\tclaude -p 'fix'"),
            Some("claude.ai")
        );
    }

    #[test]
    fn test_agent_after_newline() {
        assert_eq!(
            agent_provider_for_command("export FOO=1\nclaude -p 'fix'"),
            Some("claude.ai")
        );
    }

    #[test]
    fn test_agent_gemini_at_end() {
        assert_eq!(agent_provider_for_command("exec gemini"), Some("google"));
    }

    #[test]
    fn test_no_match_agent_in_middle_of_word() {
        // "geminist" should not match "gemini"
        assert_eq!(agent_provider_for_command("geminist run"), None);
    }

    // -- Parse credential edge cases --

    #[test]
    fn test_parse_claude_credentials_array_json() {
        // JSON is an array, not an object — should return None
        assert!(parse_claude_credentials("[1, 2, 3]").is_none());
    }

    #[test]
    fn test_parse_claude_credentials_number_json() {
        assert!(parse_claude_credentials("42").is_none());
    }

    #[test]
    fn test_parse_claude_credentials_null() {
        assert!(parse_claude_credentials("null").is_none());
    }

    #[test]
    fn test_parse_codex_credentials_array_json() {
        assert!(parse_codex_credentials("[\"a\", \"b\"]").is_none());
    }

    #[test]
    fn test_parse_codex_credentials_empty_object() {
        assert!(parse_codex_credentials("{}").is_none());
    }

    #[test]
    fn test_parse_gemini_credentials_array_json() {
        assert!(parse_gemini_credentials("[1]").is_none());
    }

    #[test]
    fn test_parse_gemini_credentials_empty_object() {
        assert!(parse_gemini_credentials("{}").is_none());
    }

    #[test]
    fn test_parse_claude_email_only() {
        let json = r#"{"email": "user@example.com"}"#;
        let info = parse_claude_credentials(json).unwrap();
        assert!(info.plan.is_none());
        assert_eq!(info.email.as_deref(), Some("user@example.com"));
    }

    #[test]
    fn test_parse_codex_email_only() {
        let json = r#"{"email": "codex@example.com"}"#;
        let info = parse_codex_credentials(json).unwrap();
        assert!(info.plan.is_none());
        assert_eq!(info.email.as_deref(), Some("codex@example.com"));
    }

    #[test]
    fn test_parse_gemini_email_via_account_field() {
        let json = r#"{"account": "user@gmail.com"}"#;
        let info = parse_gemini_credentials(json).unwrap();
        assert!(info.plan.is_none());
        assert_eq!(info.email.as_deref(), Some("user@gmail.com"));
    }

    #[test]
    fn test_parse_gemini_plan_via_tier_field() {
        let json = r#"{"tier": "Enterprise"}"#;
        let info = parse_gemini_credentials(json).unwrap();
        assert_eq!(info.plan.as_deref(), Some("enterprise"));
        assert!(info.email.is_none());
    }

    #[test]
    fn test_parse_claude_oauth_with_non_string_fields() {
        // subscriptionType is a number, not string — should be ignored
        let json = r#"{"claudeAiOauth": {"subscriptionType": 42, "email": "user@test.com"}}"#;
        let info = parse_claude_credentials(json).unwrap();
        assert!(info.plan.is_none());
        assert_eq!(info.email.as_deref(), Some("user@test.com"));
    }
}