summaryrefslogtreecommitdiffstats
path: root/src/provider.rs
diff options
context:
space:
mode:
Diffstat (limited to '')
-rw-r--r--src/provider.rs163
1 files changed, 138 insertions, 25 deletions
diff --git a/src/provider.rs b/src/provider.rs
index bc1bd99..ba36b70 100644
--- a/src/provider.rs
+++ b/src/provider.rs
@@ -117,6 +117,68 @@ impl SseDecoder {
117 } 117 }
118} 118}
119 119
120const MAX_ATTEMPTS: usize = 4;
121const BACKOFF_BASE_MS: u64 = 1000;
122const BACKOFF_MAX_MS: u64 = 8000;
123
124fn retryable_status(code: u16) -> bool {
125 matches!(code, 408 | 425 | 429 | 500 | 502 | 503 | 504)
126}
127
128fn backoff(attempt: usize) -> Duration {
129 let factor = 1u64 << (attempt.saturating_sub(1).min(4) as u32);
130 Duration::from_millis((BACKOFF_BASE_MS * factor).min(BACKOFF_MAX_MS))
131}
132
133/// Sleeps in slices so a Ctrl-C during backoff is noticed promptly.
134fn sleep_cancellable(total: Duration, cancel: &AtomicBool) -> bool {
135 let step = Duration::from_millis(100);
136 let mut left = total;
137 while left > Duration::ZERO {
138 if cancel.load(Ordering::Relaxed) {
139 return false;
140 }
141 let slice = left.min(step);
142 std::thread::sleep(slice);
143 left -= slice;
144 }
145 true
146}
147
148/// Adds the thing the raw provider message does not say: what to do about it.
149fn explain(status: u16, message: &str) -> String {
150 let lower = message.to_lowercase();
151 if (status == 400 || status == 413)
152 && (lower.contains("context")
153 || lower.contains("too many tokens")
154 || lower.contains("maximum")
155 || lower.contains("too long"))
156 {
157 return format!(
158 "{message}\n\nthis session is longer than the model's context window. The \
159 transcript is append-only and cannot be shortened, so start a new session."
160 );
161 }
162 if status == 400 && lower.contains("session") {
163 return format!(
164 "{message}\n\nthe x-opencode-session header was not accepted; that is a bug in \
165 this harness, not in your setup."
166 );
167 }
168 if status == 401 || status == 403 {
169 return format!(
170 "{message}\n\ncheck the key: OPENCODE_API_KEY or ~/.config/agent686/key"
171 );
172 }
173 if status == 429 {
174 return format!(
175 "{message}\n\nusage limit. Wait for the window to reset, or pick a cheaper \
176 model with --model."
177 );
178 }
179 message.to_string()
180}
181
120pub fn chat( 182pub fn chat(
121 cfg: &Config, 183 cfg: &Config,
122 messages: &[Value], 184 messages: &[Value],
@@ -147,31 +209,82 @@ pub fn chat(
147 .into(); 209 .into();
148 210
149 let started = Instant::now(); 211 let started = Instant::now();
150 let mut resp = agent 212 let mut resp = {
151 .post(&cfg.endpoint()) 213 let mut attempt = 0usize;
152 .header("Content-Type", "application/json") 214 loop {
153 .header("Accept", "text/event-stream") 215 attempt += 1;
154 .header("Authorization", format!("Bearer {}", cfg.api_key)) 216 if cancel.load(Ordering::Relaxed) {
155 .header("User-Agent", concat!("agent686/", env!("CARGO_PKG_VERSION"))) 217 return Err(Error::Aborted);
156 // Required by OpenCode Go: stable per conversation, used for routing and 218 }
157 // prompt caching. 219
158 .header("x-opencode-session", &cfg.session) 220 let sent = agent
159 .send(bytes) 221 .post(&cfg.endpoint())
160 .map_err(|e| Error::Transport(e.to_string()))?; 222 .header("Content-Type", "application/json")
161 223 .header("Accept", "text/event-stream")
162 let status = resp.status().as_u16(); 224 .header("Authorization", format!("Bearer {}", cfg.api_key))
163 if !(200..300).contains(&status) { 225 .header("User-Agent", concat!("agent686/", env!("CARGO_PKG_VERSION")))
164 let text = resp 226 // Required by OpenCode Go: stable per conversation, used for
165 .body_mut() 227 // routing and prompt caching. Without it the gateway answers
166 .with_config() 228 // 400 MissingSessionID.
167 .limit(256 * 1024) 229 .header("x-opencode-session", &cfg.session)
168 .read_to_string() 230 .send(bytes.clone());
169 .unwrap_or_default(); 231
170 return Err(Error::Status { 232 let mut response = match sent {
171 code: status, 233 Ok(response) => response,
172 message: error_message(&text), 234 Err(error) => {
173 }); 235 if attempt < MAX_ATTEMPTS {
174 } 236 let wait = backoff(attempt);
237 eprintln!(
238 "agent686: {error}; retrying in {:.1}s ({attempt}/{MAX_ATTEMPTS})",
239 wait.as_secs_f32()
240 );
241 if !sleep_cancellable(wait, cancel) {
242 return Err(Error::Aborted);
243 }
244 continue;
245 }
246 return Err(Error::Transport(error.to_string()));
247 }
248 };
249
250 let status = response.status().as_u16();
251 if (200..300).contains(&status) {
252 break response;
253 }
254
255 let retry_after = response
256 .headers()
257 .get("retry-after")
258 .and_then(|value| value.to_str().ok())
259 .and_then(|value| value.trim().parse::<u64>().ok())
260 .map(Duration::from_secs);
261
262 let text = response
263 .body_mut()
264 .with_config()
265 .limit(256 * 1024)
266 .read_to_string()
267 .unwrap_or_default();
268 let message = error_message(&text);
269
270 if retryable_status(status) && attempt < MAX_ATTEMPTS {
271 let wait = retry_after.unwrap_or_else(|| backoff(attempt));
272 eprintln!(
273 "agent686: HTTP {status}: {message}; retrying in {:.1}s ({attempt}/{MAX_ATTEMPTS})",
274 wait.as_secs_f32()
275 );
276 if !sleep_cancellable(wait, cancel) {
277 return Err(Error::Aborted);
278 }
279 continue;
280 }
281
282 return Err(Error::Status {
283 code: status,
284 message: explain(status, &message),
285 });
286 }
287 };
175 288
176 let mut outcome = Outcome::default(); 289 let mut outcome = Outcome::default();
177 let mut decoder = SseDecoder::new(); 290 let mut decoder = SseDecoder::new();