seher-cli 0.0.39

Seher CLI: pick the highest-priority coding agent and run a plan/build prompt
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
//! Shared "resolve + stream prompt through pi" flow used by both build and plan modes.
//!
//! Implements the retry-on-limit loop: on a `LimitError`, the resolved YAML
//! provider name is added to `exclude_providers` and resolution is retried.

use std::path::PathBuf;

use seher::claude_terminal::{
    default_transcript_root, encode_transcript_path, new_sdk_with_defaults, stream_via_thread,
};
use seher::sdk::{
    CodexBarProbe, Config, PiRunner, PiRunnerOptions, ResolveOptions, ResolvedAgent, TimeoutError,
    load_config, pi_session_path, resolve_agent, split_thinking_suffix, unsupported_sdk_providers,
};

use crate::args::Args;
use crate::logger::Logger;
use crate::stream::{Outcome, drain_to_stdout};

/// Run the full "resolve → stream" loop, returning the concatenated assistant
/// text on success.
///
/// # Errors
///
/// Returns a stringified error for resolve / timeout / non-limit pi errors.
pub fn resolve_and_stream(
    rt: &tokio::runtime::Runtime,
    prompt: &str,
    args: &Args,
    mode_key: &str,
    system_prompt: Option<&str>,
    logger: &Logger,
) -> Result<String, String> {
    // Load config + detect browser session once; reuse across retry attempts.
    let config: Config = load_config(args.config.as_deref()).map_err(|e| e.to_string())?;

    // One-time warning for non-executable providers (e.g. `sdk: claude` from
    // seher-ts configs). They are silently filtered out of candidates by the
    // resolver; we surface the skip here so the user knows why.
    for (provider, sdk) in unsupported_sdk_providers(&config) {
        logger.warn(&format!(
            "Skipping provider '{provider}' (sdk='{sdk}'): not supported by this build (supported: 'pi', 'claude-terminal')"
        ));
    }

    // Resuming pins to the backend that owns the session — the retry-on-limit provider
    // switch is disabled, since a session id is meaningless to a different backend.
    if let Some(resume_id) = args.resume.clone() {
        return resume_and_stream(
            rt,
            prompt,
            args,
            mode_key,
            system_prompt,
            logger,
            &config,
            &resume_id,
        );
    }

    let resolver = |excluded: &[String]| -> Result<ResolvedAgent, String> {
        resolve_once(rt, args, mode_key, excluded, &config)
    };
    let stream_runner = |resolved: &ResolvedAgent| -> Outcome {
        let rx = dispatch_stream(resolved, prompt, system_prompt, args, None);
        drain_to_stdout(rx, args.timeout)
    };
    stream_with_retry(args.timeout, logger, resolver, stream_runner)
}

/// Effective working directory for this run: the canonicalized `--cwd` if given,
/// otherwise the canonicalized process cwd. Used to locate session storage.
fn effective_cwd(args: &Args) -> String {
    args.cwd.clone().unwrap_or_else(|| {
        std::env::current_dir()
            .and_then(|p| p.canonicalize())
            .map_or_else(|_| ".".to_string(), |p| p.to_string_lossy().into_owned())
    })
}

/// Detect which backend owns a session id by probing on-disk storage under `cwd`.
/// Returns the sdk kind (`"claude-terminal"` / `"pi"`) or `None` if neither has it.
fn probe_session_backend(cwd: &str, session_id: &str) -> Option<&'static str> {
    let claude_path = encode_transcript_path(&default_transcript_root(), cwd, session_id);
    if std::path::Path::new(&claude_path).exists() {
        return Some("claude-terminal");
    }
    let pi_path = pi_session_path(Some(std::path::Path::new(cwd)), session_id);
    if pi_path.exists() {
        return Some("pi");
    }
    None
}

/// Resume an existing session. Probes storage to pin the owning backend, resolves a
/// matching agent, and runs a single attempt (no provider-switch retry).
///
/// # Errors
///
/// Errors if the session is not found, the resolver selects a different backend, or the
/// run hits a limit / error / timeout.
#[expect(
    clippy::too_many_arguments,
    reason = "mirrors resolve_and_stream inputs"
)]
fn resume_and_stream(
    rt: &tokio::runtime::Runtime,
    prompt: &str,
    args: &Args,
    mode_key: &str,
    system_prompt: Option<&str>,
    logger: &Logger,
    config: &Config,
    resume_id: &str,
) -> Result<String, String> {
    let cwd = effective_cwd(args);
    let pinned = probe_session_backend(&cwd, resume_id).ok_or_else(|| {
        format!("session '{resume_id}' not found under cwd '{cwd}' (resume requires the same --cwd used to create it)")
    })?;

    let resolved = resolve_once(rt, args, mode_key, &[], config)?;
    if resolved.sdk != pinned {
        return Err(format!(
            "resumed session '{resume_id}' belongs to backend '{pinned}', but the resolver selected '{}' (provider '{}') — it may be rate-limited or lower priority; pass --provider to force the matching one",
            resolved.sdk, resolved.provider
        ));
    }
    logger.info(&format!(
        "Resuming session {resume_id} on provider: {} ({}/{})",
        resolved.provider, resolved.sdk, resolved.model_id
    ));

    let rx = dispatch_stream(&resolved, prompt, system_prompt, args, Some(resume_id));
    match drain_to_stdout(rx, args.timeout) {
        Outcome::Done(t) => Ok(t),
        Outcome::Limit => Err(format!(
            "provider '{}' is rate-limited; cannot switch providers while resuming session {resume_id}",
            resolved.provider
        )),
        Outcome::Error(message) => Err(message),
        Outcome::Timeout => Err(TimeoutError {
            ms: args.timeout.unwrap_or(0),
            label: "stream",
        }
        .to_string()),
    }
}

/// Retry-on-limit loop. Pure: takes `resolver` (produces a `ResolvedAgent` given
/// the current excluded set) and `stream_runner` (produces an `Outcome` for a
/// resolved agent). Used by both production and tests.
///
/// On `Outcome::Limit`, the resolved YAML provider name is added to `excluded`
/// and `resolver` is called again. The loop exits with `Done` text on success
/// or a stringified error on terminal failure.
///
/// # Errors
///
/// Returns a stringified error when `resolver` fails, the stream errors out,
/// or the stream times out.
pub fn stream_with_retry<R, S>(
    timeout_ms: Option<u64>,
    logger: &Logger,
    mut resolver: R,
    mut stream_runner: S,
) -> Result<String, String>
where
    R: FnMut(&[String]) -> Result<ResolvedAgent, String>,
    S: FnMut(&ResolvedAgent) -> Outcome,
{
    let mut excluded: Vec<String> = Vec::new();
    loop {
        let agent = resolver(&excluded)?;
        logger.info(&format!(
            "Selected provider: {} ({}/{})",
            agent.provider, agent.sdk, agent.model_id
        ));
        match stream_runner(&agent) {
            Outcome::Done(t) => return Ok(t),
            Outcome::Limit => {
                logger.warn(&format!(
                    "Provider '{}' hit API limit; retrying with next provider...",
                    agent.provider
                ));
                // Exclude by the resolved YAML provider name (matches what
                // `resolve_agent` compares against), not by pi's provider id
                // which lives in a different namespace.
                if !excluded.contains(&agent.provider) {
                    excluded.push(agent.provider.clone());
                }
            }
            Outcome::Error(message) => return Err(message),
            Outcome::Timeout => {
                return Err(TimeoutError {
                    ms: timeout_ms.unwrap_or(0),
                    label: "stream",
                }
                .to_string());
            }
        }
    }
}

fn resolve_once(
    rt: &tokio::runtime::Runtime,
    args: &Args,
    mode_key: &str,
    excluded: &[String],
    config: &Config,
) -> Result<ResolvedAgent, String> {
    let opts = ResolveOptions {
        mode_key: mode_key.to_string(),
        provider_filter: args.provider.clone(),
        config: Some(config.clone()),
        exclude_providers: excluded.to_vec(),
        quiet: args.quiet,
        ..Default::default()
    };

    // Limit determination is delegated to the external `codexbar` binary
    // (mirrors seher-ts), so no browser/cookie session is needed here.
    let mut probe = CodexBarProbe;
    rt.block_on(async move { resolve_agent(opts, &mut probe).await })
        .map_err(|e| e.to_string())
}

fn dispatch_stream(
    resolved: &ResolvedAgent,
    prompt: &str,
    system_prompt: Option<&str>,
    args: &Args,
    resume: Option<&str>,
) -> std::sync::mpsc::Receiver<seher::sdk::StreamChunk> {
    if resolved.sdk == "claude-terminal" {
        // claude-terminal has no thinking-level support; strip a recognized
        // `:level` suffix so it never leaks into the model name.
        let (model_name, _) = split_thinking_suffix(&resolved.model_id);
        let model = Some(model_name.to_string()).filter(|s| !s.is_empty());
        let sdk = new_sdk_with_defaults(
            None,
            None,
            model,
            system_prompt.map(str::to_string),
            args.timeout,
            args.cwd.clone(),
        );
        stream_via_thread(
            sdk,
            prompt.to_string(),
            resolved.provider.clone(),
            resume.map(str::to_string),
        )
    } else {
        let runner = build_pi_runner(resolved, system_prompt.map(str::to_string), args);
        runner.stream(prompt.to_string(), resume.map(str::to_string))
    }
}

fn build_pi_runner(
    resolved: &ResolvedAgent,
    system_prompt: Option<String>,
    args: &Args,
) -> PiRunner {
    let (provider, model, thinking) = parse_provider_model(&resolved.model_id);
    let api_key = resolved
        .api
        .as_ref()
        .and_then(|a| a.key.clone())
        .or_else(|| env_api_key_for(provider.as_deref()));
    PiRunner::new(PiRunnerOptions {
        provider,
        model,
        api_key,
        thinking,
        system_prompt,
        working_directory: args.cwd.as_deref().map(PathBuf::from),
        // The CLI has no way to define custom tools; only SDK consumers do.
        tools: Vec::new(),
    })
}

/// Splits a config model id into `(provider, model, thinking)`.
///
/// The segment before the first `/` is the provider. A trailing `:` suffix on
/// the remainder selects pi's thinking level (e.g. `anthropic/opus-4.7:high`),
/// but only when it is a recognized level — see [`split_thinking_suffix`].
fn parse_provider_model(model_id: &str) -> (Option<String>, Option<String>, Option<String>) {
    let (provider, rest) = match model_id.split_once('/') {
        Some((p, m)) => (Some(p.to_string()), m),
        None => (None, model_id),
    };
    let (model, thinking) = split_thinking_suffix(rest);
    (
        provider,
        Some(model.to_string()),
        thinking.map(str::to_string),
    )
}

fn env_api_key_for(provider: Option<&str>) -> Option<String> {
    let var = match provider {
        Some("anthropic") => "ANTHROPIC_API_KEY",
        Some("openai") => "OPENAI_API_KEY",
        _ => return None,
    };
    std::env::var(var).ok()
}

#[cfg(test)]
#[expect(clippy::expect_used, reason = "tests may panic on unexpected fixtures")]
mod tests {
    use super::*;
    use seher::sdk::ResolvedSkillsConfig;
    use std::cell::RefCell;

    fn make_resolved(provider: &str, model: &str) -> ResolvedAgent {
        ResolvedAgent {
            provider: provider.to_string(),
            model_id: model.to_string(),
            mode_key: "build".to_string(),
            sdk: "pi".to_string(),
            api: None,
            skills: ResolvedSkillsConfig::default(),
        }
    }

    fn silent_logger() -> Logger {
        Logger::new(true)
    }

    #[test]
    fn returns_done_on_first_success() {
        let logger = silent_logger();
        let resolver = |_excluded: &[String]| Ok(make_resolved("a", "anthropic/x"));
        let stream_runner = |_r: &ResolvedAgent| Outcome::Done("hi".to_string());
        let result = stream_with_retry(None, &logger, resolver, stream_runner).expect("done");
        assert_eq!(result, "hi");
    }

    #[test]
    fn retry_on_limit_excludes_resolved_provider_and_retries() {
        let logger = silent_logger();
        // Sequence of resolved providers: first "a" (limit), then "b" (done).
        let calls = RefCell::new(0u32);
        let resolver = |excluded: &[String]| {
            let n = *calls.borrow();
            *calls.borrow_mut() = n + 1;
            if n == 0 {
                // First call: excluded should be empty.
                assert!(excluded.is_empty(), "first resolve sees empty excluded");
                Ok(make_resolved("a", "anthropic/x"))
            } else {
                // Second call: excluded should contain "a" (the YAML provider name).
                assert_eq!(excluded, &["a".to_string()]);
                Ok(make_resolved("b", "openai/y"))
            }
        };
        let outcomes = RefCell::new(vec![Outcome::Limit, Outcome::Done("ok".to_string())]);
        let stream_runner = |_r: &ResolvedAgent| outcomes.borrow_mut().remove(0);
        let result = stream_with_retry(None, &logger, resolver, stream_runner).expect("done");
        assert_eq!(result, "ok");
        assert_eq!(*calls.borrow(), 2);
    }

    #[test]
    fn duplicate_limit_does_not_grow_excluded() {
        // Resolver bug simulation: resolver keeps returning provider "a" even after
        // it's in `excluded`. The loop must not push "a" twice; it should terminate
        // when the resolver itself starts returning an error (no more candidates).
        let logger = silent_logger();
        let attempts = RefCell::new(0u32);
        let resolver = |excluded: &[String]| {
            let n = *attempts.borrow();
            *attempts.borrow_mut() = n + 1;
            if n >= 2 {
                return Err("no more candidates".to_string());
            }
            // Pretend resolver returns "a" regardless of excluded — checks dedup.
            let _ = excluded;
            Ok(make_resolved("a", "anthropic/x"))
        };
        let stream_runner = |_r: &ResolvedAgent| Outcome::Limit;
        let err =
            stream_with_retry(None, &logger, resolver, stream_runner).expect_err("should error");
        assert!(err.contains("no more candidates"), "got: {err}");
    }

    #[test]
    fn returns_error_on_stream_error() {
        let logger = silent_logger();
        let resolver = |_excluded: &[String]| Ok(make_resolved("a", "anthropic/x"));
        let stream_runner = |_r: &ResolvedAgent| Outcome::Error("boom".to_string());
        let err =
            stream_with_retry(None, &logger, resolver, stream_runner).expect_err("should error");
        assert_eq!(err, "boom");
    }

    #[test]
    fn returns_timeout_error_with_ms() {
        let logger = silent_logger();
        let resolver = |_excluded: &[String]| Ok(make_resolved("a", "anthropic/x"));
        let stream_runner = |_r: &ResolvedAgent| Outcome::Timeout;
        let err = stream_with_retry(Some(5000), &logger, resolver, stream_runner)
            .expect_err("should error");
        assert!(err.contains("5000"), "got: {err}");
        assert!(err.contains("timed out"), "got: {err}");
    }

    #[test]
    fn resolver_error_propagates() {
        let logger = silent_logger();
        let resolver = |_excluded: &[String]| Err("config broken".to_string());
        let stream_runner = |_r: &ResolvedAgent| Outcome::Done(String::new());
        let err =
            stream_with_retry(None, &logger, resolver, stream_runner).expect_err("should error");
        assert_eq!(err, "config broken");
    }

    #[test]
    fn parse_provider_model_with_slash() {
        let (p, m, t) = parse_provider_model("anthropic/claude-sonnet");
        assert_eq!(p.as_deref(), Some("anthropic"));
        assert_eq!(m.as_deref(), Some("claude-sonnet"));
        assert_eq!(t, None);
    }

    #[test]
    fn parse_provider_model_without_slash() {
        let (p, m, t) = parse_provider_model("just-a-model");
        assert_eq!(p, None);
        assert_eq!(m.as_deref(), Some("just-a-model"));
        assert_eq!(t, None);
    }

    #[test]
    fn parse_provider_model_with_thinking() {
        let (p, m, t) = parse_provider_model("anthropic/claude-sonnet:high");
        assert_eq!(p.as_deref(), Some("anthropic"));
        assert_eq!(m.as_deref(), Some("claude-sonnet"));
        assert_eq!(t.as_deref(), Some("high"));
    }

    #[test]
    fn parse_provider_model_with_thinking_without_slash() {
        let (p, m, t) = parse_provider_model("just-a-model:medium");
        assert_eq!(p, None);
        assert_eq!(m.as_deref(), Some("just-a-model"));
        assert_eq!(t.as_deref(), Some("medium"));
    }

    #[test]
    fn parse_provider_model_keeps_unrecognized_suffix_in_model() {
        // OpenRouter-style variant suffixes are not thinking levels and must
        // stay part of the model name.
        let (p, m, t) = parse_provider_model("openrouter/meta-llama/llama-3.1-8b-instruct:free");
        assert_eq!(p.as_deref(), Some("openrouter"));
        assert_eq!(m.as_deref(), Some("meta-llama/llama-3.1-8b-instruct:free"));
        assert_eq!(t, None);
    }

    #[test]
    fn env_api_key_for_unknown_returns_none() {
        assert_eq!(env_api_key_for(None), None);
        assert_eq!(env_api_key_for(Some("cohere")), None);
        assert_eq!(env_api_key_for(Some("google")), None);
    }
}