summaryrefslogtreecommitdiffstats
path: root/src/provider.rs
diff options
context:
space:
mode:
Diffstat (limited to '')
-rw-r--r--src/provider.rs319
1 files changed, 319 insertions, 0 deletions
diff --git a/src/provider.rs b/src/provider.rs
new file mode 100644
index 0000000..a2aed64
--- /dev/null
+++ b/src/provider.rs
@@ -0,0 +1,319 @@
1use std::io::Read;
2use std::sync::atomic::{AtomicBool, Ordering};
3use std::time::{Duration, Instant};
4
5use serde::Deserialize;
6use serde_json::Value;
7
8use crate::config::Config;
9
10#[derive(Debug)]
11pub enum Error {
12 Transport(String),
13 Status { code: u16, message: String },
14 Aborted,
15}
16
17impl std::fmt::Display for Error {
18 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
19 match self {
20 Error::Transport(m) => write!(f, "{m}"),
21 Error::Status { code, message } => write!(f, "HTTP {code}: {message}"),
22 Error::Aborted => write!(f, "aborted"),
23 }
24 }
25}
26
27impl std::error::Error for Error {}
28
29/// One completed tool call, assembled from streamed deltas.
30#[derive(Debug, Default, Clone)]
31pub struct ToolCall {
32 pub index: usize,
33 pub id: String,
34 pub name: String,
35 /// The argument JSON exactly as the model emitted it. Never re-serialised:
36 /// re-encoding can change key order and invalidate the provider's cache.
37 pub arguments: String,
38}
39
40#[derive(Debug, Default)]
41pub struct Outcome {
42 pub content: String,
43 pub reasoning: String,
44 pub tool_calls: Vec<ToolCall>,
45 pub finish: Option<String>,
46 pub usage: Option<Value>,
47 pub opencode: Option<Value>,
48}
49
50pub trait Sink {
51 fn text(&mut self, s: &str);
52 fn reasoning(&mut self, s: &str);
53 fn done(&mut self, outcome: &Outcome, elapsed: Duration);
54}
55
56/// Decodes an SSE byte stream into `data:` payloads.
57///
58/// Kept as a state machine so that chunk boundaries can fall anywhere: inside a
59/// line, or inside a multi-byte UTF-8 character. Only complete lines are ever
60/// converted to text.
61#[derive(Default)]
62pub struct SseDecoder {
63 buf: Vec<u8>,
64}
65
66impl SseDecoder {
67 pub fn new() -> Self {
68 Self::default()
69 }
70
71 pub fn feed(&mut self, chunk: &[u8]) -> Vec<String> {
72 self.buf.extend_from_slice(chunk);
73 let mut out = Vec::new();
74 let mut start = 0;
75 while let Some(rel) = self.buf[start..].iter().position(|&b| b == b'\n') {
76 let end = start + rel;
77 let mut line = &self.buf[start..end];
78 if line.last() == Some(&b'\r') {
79 line = &line[..line.len() - 1];
80 }
81 start = end + 1;
82 if let Some(payload) = line.strip_prefix(b"data:") {
83 let payload = payload.strip_prefix(b" ").unwrap_or(payload);
84 out.push(String::from_utf8_lossy(payload).into_owned());
85 }
86 }
87 self.buf.drain(..start);
88 out
89 }
90}
91
92pub fn chat(
93 cfg: &Config,
94 messages: &[Value],
95 cancel: &AtomicBool,
96 sink: &mut dyn Sink,
97) -> Result<Outcome, Error> {
98 // serde_json::Value is ordered by key, not by insertion, so the serialised
99 // bytes are stable for the same input. That is what keeps the cache warm;
100 // do not switch this to a struct with fields in a different order, and do
101 // not add anything session-varying to the system message.
102 let body = serde_json::json!({
103 "model": cfg.model,
104 "messages": messages,
105 "stream": true,
106 "stream_options": { "include_usage": true },
107 });
108 let bytes = serde_json::to_vec(&body).map_err(|e| Error::Transport(e.to_string()))?;
109
110 let agent: ureq::Agent = ureq::Agent::config_builder()
111 .http_status_as_error(false)
112 .timeout_connect(Some(Duration::from_secs(10)))
113 .timeout_recv_response(Some(Duration::from_secs(180)))
114 .timeout_per_read(Some(Duration::from_secs(180)))
115 .build()
116 .into();
117
118 let started = Instant::now();
119 let mut resp = agent
120 .post(&cfg.endpoint())
121 .header("Content-Type", "application/json")
122 .header("Accept", "text/event-stream")
123 .header("Authorization", format!("Bearer {}", cfg.api_key))
124 .header("User-Agent", concat!("agent686/", env!("CARGO_PKG_VERSION")))
125 // Required by OpenCode Go: stable per conversation, used for routing and
126 // prompt caching.
127 .header("x-opencode-session", &cfg.session)
128 .send(bytes)
129 .map_err(|e| Error::Transport(e.to_string()))?;
130
131 let status = resp.status().as_u16();
132 if !(200..300).contains(&status) {
133 let text = resp
134 .body_mut()
135 .with_config()
136 .limit(256 * 1024)
137 .read_to_string()
138 .unwrap_or_default();
139 return Err(Error::Status {
140 code: status,
141 message: error_message(&text),
142 });
143 }
144
145 let mut outcome = Outcome::default();
146 let mut decoder = SseDecoder::new();
147 let mut buf = [0u8; 8192];
148 let mut reader = resp.body_mut().as_reader();
149 let mut done = false;
150
151 while !done {
152 // Blocking reads mean an abort is only noticed when bytes arrive or the
153 // per-read timeout fires. Good enough: the model streams constantly.
154 if cancel.load(Ordering::Relaxed) {
155 return Err(Error::Aborted);
156 }
157 let n = match reader.read(&mut buf) {
158 Ok(0) => break,
159 Ok(n) => n,
160 Err(e) => return Err(Error::Transport(e.to_string())),
161 };
162 for data in decoder.feed(&buf[..n]) {
163 if data.is_empty() {
164 continue;
165 }
166 if data.trim() == "[DONE]" {
167 done = true;
168 break;
169 }
170 let chunk: Chunk = match serde_json::from_str(&data) {
171 Ok(c) => c,
172 // A malformed frame is dropped rather than killing the turn; the
173 // stream is the only recovery path and it is still valid SSE.
174 Err(_) => continue,
175 };
176 apply_chunk(&chunk, &mut outcome, sink);
177 }
178 }
179
180 if let Some(usage) = &outcome.usage {
181 if usage.is_null() {
182 outcome.usage = None;
183 }
184 }
185 if let Some(opencode) = &outcome.opencode {
186 if opencode.is_null() {
187 outcome.opencode = None;
188 }
189 }
190
191 sink.done(&outcome, started.elapsed());
192 Ok(outcome)
193}
194
195fn apply_chunk(chunk: &Chunk, outcome: &mut Outcome, sink: &mut dyn Sink) {
196 if let Some(usage) = &chunk.usage {
197 outcome.usage = Some(usage.clone());
198 }
199 if let Some(opencode) = &chunk.opencode {
200 outcome.opencode = Some(opencode.clone());
201 }
202 for choice in &chunk.choices {
203 if let Some(r) = &choice.delta.reasoning_content {
204 if !r.is_empty() {
205 outcome.reasoning.push_str(r);
206 sink.reasoning(r);
207 }
208 }
209 if let Some(t) = &choice.delta.content {
210 if !t.is_empty() {
211 outcome.content.push_str(t);
212 sink.text(t);
213 }
214 }
215 if let Some(calls) = &choice.delta.tool_calls {
216 for call in calls {
217 accumulate_tool_call(&mut outcome.tool_calls, call);
218 }
219 }
220 if let Some(finish) = &choice.finish_reason {
221 outcome.finish = Some(finish.clone());
222 }
223 }
224}
225
226/// Tool call deltas arrive split across chunks and are keyed by `index`: the
227/// name and id usually come once, the arguments a fragment at a time.
228fn accumulate_tool_call(calls: &mut Vec<ToolCall>, delta: &ToolCallDelta) {
229 while calls.len() <= delta.index {
230 let index = calls.len();
231 calls.push(ToolCall {
232 index,
233 id: String::new(),
234 name: String::new(),
235 arguments: String::new(),
236 });
237 }
238 let call = &mut calls[delta.index];
239 if let Some(id) = &delta.id {
240 call.id.push_str(id);
241 }
242 if let Some(function) = &delta.function {
243 if let Some(name) = &function.name {
244 call.name.push_str(name);
245 }
246 if let Some(args) = &function.arguments {
247 call.arguments.push_str(args);
248 }
249 }
250}
251
252fn error_message(body: &str) -> String {
253 if let Ok(v) = serde_json::from_str::<Value>(body) {
254 if let Some(err) = v.get("error") {
255 if let Some(message) = err.get("message").and_then(|m| m.as_str()) {
256 return match err.get("code").and_then(|c| c.as_str()) {
257 Some(code) if !code.is_empty() => format!("{message} ({code})"),
258 _ => message.to_string(),
259 };
260 }
261 }
262 if let Some(message) = v.get("message").and_then(|m| m.as_str()) {
263 return message.to_string();
264 }
265 }
266 truncate(body.trim(), 500)
267}
268
269fn truncate(s: &str, max: usize) -> String {
270 match s.char_indices().nth(max) {
271 Some((i, _)) => format!("{}…", &s[..i]),
272 None => s.to_string(),
273 }
274}
275
276#[derive(Debug, Deserialize)]
277struct Chunk {
278 #[serde(default)]
279 choices: Vec<Choice>,
280 #[serde(default)]
281 usage: Option<Value>,
282 #[serde(default)]
283 opencode: Option<Value>,
284}
285
286#[derive(Debug, Deserialize)]
287struct Choice {
288 #[serde(default)]
289 delta: Delta,
290 #[serde(default)]
291 finish_reason: Option<String>,
292}
293
294#[derive(Debug, Default, Deserialize)]
295struct Delta {
296 #[serde(default)]
297 content: Option<String>,
298 #[serde(default)]
299 reasoning_content: Option<String>,
300 #[serde(default)]
301 tool_calls: Option<Vec<ToolCallDelta>>,
302}
303
304#[derive(Debug, Deserialize)]
305struct ToolCallDelta {
306 index: usize,
307 #[serde(default)]
308 id: Option<String>,
309 #[serde(default)]
310 function: Option<FunctionDelta>,
311}
312
313#[derive(Debug, Deserialize)]
314struct FunctionDelta {
315 #[serde(default)]
316 name: Option<String>,
317 #[serde(default)]
318 arguments: Option<String>,
319}