aboutsummaryrefslogtreecommitdiffstats
path: root/src/provider.rs
blob: 16c90132e4b074ceb2f6922e67976d1e0f007689 (plain) (blame)
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
use std::io::Read;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};

use serde::Deserialize;
use serde_json::Value;

use crate::config::Config;

#[derive(Debug)]
pub enum Error {
    Transport(String),
    Status { code: u16, message: String },
    Aborted,
}

impl std::fmt::Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Error::Transport(m) => write!(f, "{m}"),
            Error::Status { code, message } => write!(f, "HTTP {code}: {message}"),
            Error::Aborted => write!(f, "aborted"),
        }
    }
}

impl std::error::Error for Error {}

/// One completed tool call, assembled from streamed deltas.
#[derive(Debug, Default, Clone)]
pub struct ToolCall {
    pub index: usize,
    pub id: String,
    pub name: String,
    /// The argument JSON exactly as the model emitted it. Never re-serialised:
    /// re-encoding can change key order and invalidate the provider's cache.
    pub arguments: String,
}

#[derive(Debug, Default)]
pub struct Outcome {
    pub content: String,
    pub reasoning: String,
    pub tool_calls: Vec<ToolCall>,
    pub finish: Option<String>,
    pub usage: Option<Value>,
}

impl Outcome {
    pub fn allowance(&self) -> Option<f64> {
        self.usage
            .as_ref()?
            .get("opencode")?
            .get("allowance")?
            .as_f64()
    }

    pub fn list_cost(&self) -> Option<f64> {
        self.usage
            .as_ref()?
            .get("opencode")?
            .get("list_cost")?
            .as_f64()
    }

    pub fn tokens(&self) -> (Option<u64>, Option<u64>) {
        let usage = match &self.usage {
            Some(u) => u,
            None => return (None, None),
        };
        (
            usage.get("prompt_tokens").and_then(|v| v.as_u64()),
            usage.get("completion_tokens").and_then(|v| v.as_u64()),
        )
    }
}

pub trait Sink {
    fn text(&mut self, s: &str);
    fn reasoning(&mut self, s: &str);
    fn done(&mut self, outcome: &Outcome, elapsed: Duration);
}

/// Decodes an SSE byte stream into `data:` payloads.
///
/// Kept as a state machine so that chunk boundaries can fall anywhere: inside a
/// line, or inside a multi-byte UTF-8 character. Only complete lines are ever
/// converted to text.
#[derive(Default)]
pub struct SseDecoder {
    buf: Vec<u8>,
}

impl SseDecoder {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn feed(&mut self, chunk: &[u8]) -> Vec<String> {
        self.buf.extend_from_slice(chunk);
        let mut out = Vec::new();
        let mut start = 0;
        while let Some(rel) = self.buf[start..].iter().position(|&b| b == b'\n') {
            let end = start + rel;
            let mut line = &self.buf[start..end];
            if line.last() == Some(&b'\r') {
                line = &line[..line.len() - 1];
            }
            start = end + 1;
            if let Some(payload) = line.strip_prefix(b"data:") {
                let payload = payload.strip_prefix(b" ").unwrap_or(payload);
                out.push(String::from_utf8_lossy(payload).into_owned());
            }
        }
        self.buf.drain(..start);
        out
    }
}

const MAX_ATTEMPTS: usize = 4;
const BACKOFF_BASE_MS: u64 = 1000;
const BACKOFF_MAX_MS: u64 = 8000;

fn retryable_status(code: u16) -> bool {
    matches!(code, 408 | 425 | 429 | 500 | 502 | 503 | 504)
}

fn backoff(attempt: usize) -> Duration {
    let factor = 1u64 << (attempt.saturating_sub(1).min(4) as u32);
    Duration::from_millis((BACKOFF_BASE_MS * factor).min(BACKOFF_MAX_MS))
}

/// Sleeps in slices so a Ctrl-C during backoff is noticed promptly.
fn sleep_cancellable(total: Duration, cancel: &AtomicBool) -> bool {
    let step = Duration::from_millis(100);
    let mut left = total;
    while left > Duration::ZERO {
        if cancel.load(Ordering::Relaxed) {
            return false;
        }
        let slice = left.min(step);
        std::thread::sleep(slice);
        left -= slice;
    }
    true
}

/// Adds the thing the raw provider message does not say: what to do about it.
fn explain(status: u16, message: &str) -> String {
    let lower = message.to_lowercase();
    if (status == 400 || status == 413)
        && (lower.contains("context")
            || lower.contains("too many tokens")
            || lower.contains("maximum")
            || lower.contains("too long"))
    {
        return format!(
            "{message}\n\nthis session is longer than the model's context window. The \
             transcript is append-only and cannot be shortened, so start a new session."
        );
    }
    if status == 400 && lower.contains("session") {
        return format!(
            "{message}\n\nthe x-opencode-session header was not accepted; that is a bug in \
             this harness, not in your setup."
        );
    }
    if status == 401 || status == 403 {
        return format!(
            "{message}\n\ncheck the key: OPENCODE_API_KEY or ~/.config/agent686/key"
        );
    }
    if status == 429 {
        return format!(
            "{message}\n\nusage limit. Wait for the window to reset, or pick a cheaper \
             model with --model."
        );
    }
    message.to_string()
}

pub fn chat(
    cfg: &Config,
    messages: &[Value],
    tools: &[Value],
    cancel: &AtomicBool,
    sink: &mut dyn Sink,
) -> Result<Outcome, Error> {
    // serde_json::Value orders objects by key, so the serialised bytes are
    // stable for the same input. That is what keeps the provider's prompt cache
    // warm. Do not add anything session-varying here.
    let mut body = serde_json::json!({
        "model": cfg.model,
        "messages": messages,
        "stream": true,
        "stream_options": { "include_usage": true },
    });
    if !tools.is_empty() {
        body["tools"] = Value::Array(tools.to_vec());
    }
    let bytes = serde_json::to_vec(&body).map_err(|e| Error::Transport(e.to_string()))?;

    let agent: ureq::Agent = ureq::Agent::config_builder()
        .http_status_as_error(false)
        .timeout_connect(Some(Duration::from_secs(10)))
        .timeout_recv_response(Some(Duration::from_secs(180)))
        .timeout_per_read(Some(Duration::from_secs(180)))
        .build()
        .into();

    let started = Instant::now();
    let mut resp = {
        let mut attempt = 0usize;
        loop {
            attempt += 1;
            if cancel.load(Ordering::Relaxed) {
                return Err(Error::Aborted);
            }

            let sent = agent
                .post(&cfg.endpoint())
                .header("Content-Type", "application/json")
                .header("Accept", "text/event-stream")
                .header("Authorization", format!("Bearer {}", cfg.api_key))
                .header("User-Agent", concat!("agent686/", env!("CARGO_PKG_VERSION")))
                // Required by OpenCode Go: stable per conversation, used for
                // routing and prompt caching. Without it the gateway answers
                // 400 MissingSessionID.
                .header("x-opencode-session", &cfg.session)
                .send(bytes.clone());

            let mut response = match sent {
                Ok(response) => response,
                Err(error) => {
                    if attempt < MAX_ATTEMPTS {
                        let wait = backoff(attempt);
                        eprintln!(
                            "agent686: {error}; retrying in {:.1}s ({attempt}/{MAX_ATTEMPTS})",
                            wait.as_secs_f32()
                        );
                        if !sleep_cancellable(wait, cancel) {
                            return Err(Error::Aborted);
                        }
                        continue;
                    }
                    return Err(Error::Transport(error.to_string()));
                }
            };

            let status = response.status().as_u16();
            if (200..300).contains(&status) {
                break response;
            }

            let retry_after = response
                .headers()
                .get("retry-after")
                .and_then(|value| value.to_str().ok())
                .and_then(|value| value.trim().parse::<u64>().ok())
                .map(Duration::from_secs);

            let text = response
                .body_mut()
                .with_config()
                .limit(256 * 1024)
                .read_to_string()
                .unwrap_or_default();
            let message = error_message(&text);

            if retryable_status(status) && attempt < MAX_ATTEMPTS {
                let wait = retry_after.unwrap_or_else(|| backoff(attempt));
                eprintln!(
                    "agent686: HTTP {status}: {message}; retrying in {:.1}s ({attempt}/{MAX_ATTEMPTS})",
                    wait.as_secs_f32()
                );
                if !sleep_cancellable(wait, cancel) {
                    return Err(Error::Aborted);
                }
                continue;
            }

            return Err(Error::Status {
                code: status,
                message: explain(status, &message),
            });
        }
    };

    let mut outcome = Outcome::default();
    let mut decoder = SseDecoder::new();
    let mut buf = [0u8; 8192];
    let mut reader = resp.body_mut().as_reader();
    let mut done = false;

    while !done {
        // Blocking reads mean an abort is only noticed when bytes arrive or the
        // per-read timeout fires. Good enough: the model streams constantly.
        if cancel.load(Ordering::Relaxed) {
            return Err(Error::Aborted);
        }
        let n = match reader.read(&mut buf) {
            Ok(0) => break,
            Ok(n) => n,
            Err(e) => return Err(Error::Transport(e.to_string())),
        };
        for data in decoder.feed(&buf[..n]) {
            if data.is_empty() {
                continue;
            }
            if data.trim() == "[DONE]" {
                done = true;
                break;
            }
            let chunk: Chunk = match serde_json::from_str(&data) {
                Ok(c) => c,
                // A malformed frame is dropped rather than killing the turn.
                Err(_) => continue,
            };
            apply_chunk(&chunk, &mut outcome, sink);
        }
    }

    if outcome.usage.as_ref().is_some_and(|u| u.is_null()) {
        outcome.usage = None;
    }

    sink.done(&outcome, started.elapsed());
    Ok(outcome)
}

fn apply_chunk(chunk: &Chunk, outcome: &mut Outcome, sink: &mut dyn Sink) {
    if let Some(usage) = &chunk.usage {
        outcome.usage = Some(usage.clone());
    }
    for choice in &chunk.choices {
        if let Some(r) = &choice.delta.reasoning_content {
            if !r.is_empty() {
                outcome.reasoning.push_str(r);
                sink.reasoning(r);
            }
        }
        if let Some(t) = &choice.delta.content {
            if !t.is_empty() {
                outcome.content.push_str(t);
                sink.text(t);
            }
        }
        if let Some(calls) = &choice.delta.tool_calls {
            for call in calls {
                accumulate_tool_call(&mut outcome.tool_calls, call);
            }
        }
        if let Some(finish) = &choice.finish_reason {
            outcome.finish = Some(finish.clone());
        }
    }
}

/// Tool call deltas arrive split across chunks and are keyed by `index`: the
/// name and id usually come once, the arguments a fragment at a time.
fn accumulate_tool_call(calls: &mut Vec<ToolCall>, delta: &ToolCallDelta) {
    while calls.len() <= delta.index {
        let index = calls.len();
        calls.push(ToolCall {
            index,
            id: String::new(),
            name: String::new(),
            arguments: String::new(),
        });
    }
    let call = &mut calls[delta.index];
    if let Some(id) = &delta.id {
        call.id.push_str(id);
    }
    if let Some(function) = &delta.function {
        if let Some(name) = &function.name {
            call.name.push_str(name);
        }
        if let Some(args) = &function.arguments {
            call.arguments.push_str(args);
        }
    }
}

fn error_message(body: &str) -> String {
    if let Ok(v) = serde_json::from_str::<Value>(body) {
        if let Some(err) = v.get("error") {
            if let Some(message) = err.get("message").and_then(|m| m.as_str()) {
                return match err.get("code").and_then(|c| c.as_str()) {
                    Some(code) if !code.is_empty() => format!("{message} ({code})"),
                    _ => message.to_string(),
                };
            }
        }
        if let Some(message) = v.get("message").and_then(|m| m.as_str()) {
            return message.to_string();
        }
    }
    truncate(body.trim(), 500)
}

pub fn truncate(s: &str, max: usize) -> String {
    match s.char_indices().nth(max) {
        Some((i, _)) => format!("{}…", &s[..i]),
        None => s.to_string(),
    }
}

#[derive(Debug, Deserialize)]
struct Chunk {
    #[serde(default)]
    choices: Vec<Choice>,
    #[serde(default)]
    usage: Option<Value>,
}

#[derive(Debug, Deserialize)]
struct Choice {
    #[serde(default)]
    delta: Delta,
    #[serde(default)]
    finish_reason: Option<String>,
}

#[derive(Debug, Default, Deserialize)]
struct Delta {
    #[serde(default)]
    content: Option<String>,
    #[serde(default)]
    reasoning_content: Option<String>,
    #[serde(default)]
    tool_calls: Option<Vec<ToolCallDelta>>,
}

#[derive(Debug, Deserialize)]
struct ToolCallDelta {
    index: usize,
    #[serde(default)]
    id: Option<String>,
    #[serde(default)]
    function: Option<FunctionDelta>,
}

#[derive(Debug, Deserialize)]
struct FunctionDelta {
    #[serde(default)]
    name: Option<String>,
    #[serde(default)]
    arguments: Option<String>,
}

/// Lists the models the provider offers for this key, for `--doctor`.
pub fn models(cfg: &Config) -> Result<Vec<String>, Error> {
    let agent: ureq::Agent = ureq::Agent::config_builder()
        .http_status_as_error(false)
        .timeout_connect(Some(Duration::from_secs(10)))
        .timeout_recv_response(Some(Duration::from_secs(20)))
        .timeout_per_read(Some(Duration::from_secs(20)))
        .build()
        .into();

    let url = format!("{}/models", cfg.base_url.trim_end_matches('/'));
    let mut response = agent
        .get(&url)
        .header("Authorization", format!("Bearer {}", cfg.api_key))
        .header("User-Agent", concat!("agent686/", env!("CARGO_PKG_VERSION")))
        .header("x-opencode-session", &cfg.session)
        .call()
        .map_err(|e| Error::Transport(e.to_string()))?;

    let status = response.status().as_u16();
    let body = response
        .body_mut()
        .with_config()
        .limit(8 * 1024 * 1024)
        .read_to_string()
        .unwrap_or_default();

    if !(200..300).contains(&status) {
        return Err(Error::Status {
            code: status,
            message: explain(status, &error_message(&body)),
        });
    }

    let value: Value = serde_json::from_str(&body)
        .map_err(|e| Error::Transport(format!("could not parse the model list: {e}")))?;
    Ok(value
        .get("data")
        .and_then(|data| data.as_array())
        .map(|models| {
            models
                .iter()
                .filter_map(|model| model.get("id").and_then(|id| id.as_str()))
                .map(|id| id.to_string())
                .collect()
        })
        .unwrap_or_default())
}