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
//! High-level Ollama client for server interaction and model management.
//!
//! Adapted from [openai/codex] `codex-ollama/src/client.rs` (Apache-2.0).
//! Copyright 2025 OpenAI. See the repository `THIRD-PARTY-NOTICES` file for
//! full attribution and change notice.
//!
//! [openai/codex]: https://github.com/openai/codex
use std::io;
use futures::StreamExt;
use futures::stream::BoxStream;
use semver::Version;
use serde_json::Value as JsonValue;
use super::OLLAMA_CONNECTION_ERROR;
use super::ollama_model_name_from_fields;
use super::pull::{OllamaPullEvent, OllamaPullProgressReporter};
use super::url::base_url_to_host_root;
/// Client for interacting with a local or remote Ollama instance.
pub(crate) struct OllamaClient {
client: reqwest::Client,
host_root: String,
}
impl OllamaClient {
/// Create a client from a base URL and verify the server is reachable.
pub(crate) async fn try_from_base_url(base_url: &str) -> io::Result<Self> {
let host_root = base_url_to_host_root(base_url);
// Connect-only timeouts are not enough: a local server that accepts the
// socket and then stalls (loading weights, deadlock) would hang the
// probe forever. These are metadata GETs, so the installed request
// budget is the right bound.
let client = vtcode_commons::http::create_default_client();
let instance = Self { client, host_root };
instance.probe_server().await?;
Ok(instance)
}
/// Probe whether the server is reachable.
async fn probe_server(&self) -> io::Result<()> {
let url = format!("{}/api/tags", self.host_root.trim_end_matches('/'));
let resp = self.client.get(url).send().await.map_err(|err| {
tracing::warn!("Failed to connect to Ollama server: {err:?}");
io::Error::other(OLLAMA_CONNECTION_ERROR)
})?;
if resp.status().is_success() {
Ok(())
} else {
tracing::warn!("Failed to probe server at {}: HTTP {}", self.host_root, resp.status());
Err(io::Error::other(OLLAMA_CONNECTION_ERROR))
}
}
/// Fetch the list of model names available on the server.
pub(crate) async fn fetch_models(&self) -> io::Result<Vec<String>> {
let tags_url = format!("{}/api/tags", self.host_root.trim_end_matches('/'));
let resp = self.client.get(tags_url).send().await.map_err(io::Error::other)?;
if !resp.status().is_success() {
return Ok(Vec::new());
}
let val = resp.json::<JsonValue>().await.map_err(io::Error::other)?;
let names = val
.get("models")
.and_then(|m| m.as_array())
.map(|arr| {
arr.iter()
.filter_map(|v| {
ollama_model_name_from_fields(
v.get("name").and_then(|n| n.as_str()),
v.get("model").and_then(|n| n.as_str()),
)
})
.map(str::to_string)
.collect::<Vec<_>>()
})
.unwrap_or_default();
Ok(names)
}
/// Query the server for its version string, returning `None` when unavailable.
/// Adapted from OpenAI Codex's codex-ollama/src/client.rs
pub async fn fetch_version(&self) -> io::Result<Option<Version>> {
let version_url = format!("{}/api/version", self.host_root.trim_end_matches('/'));
let resp = self.client.get(version_url).send().await.map_err(io::Error::other)?;
if !resp.status().is_success() {
return Ok(None);
}
let val = resp.json::<JsonValue>().await.map_err(io::Error::other)?;
let Some(version_str) = val.get("version").and_then(|v| v.as_str()).map(str::trim) else {
return Ok(None);
};
let normalized = version_str.trim_start_matches('v');
match Version::parse(normalized) {
Ok(version) => Ok(Some(version)),
Err(err) => {
tracing::warn!("Failed to parse Ollama version `{version_str}`: {err}");
Ok(None)
}
}
}
/// Start a model pull and return a stream of events.
async fn pull_model_stream(&self, model: &str) -> io::Result<BoxStream<'static, OllamaPullEvent>> {
let url = format!("{}/api/pull", self.host_root.trim_end_matches('/'));
let resp = self
.client
.post(url)
.json(&serde_json::json!({"model": model, "stream": true}))
.send()
.await
.map_err(io::Error::other)?;
if !resp.status().is_success() {
return Err(io::Error::other(format!("failed to start pull: HTTP {}", resp.status())));
}
let mut stream = resp.bytes_stream();
let mut buf = String::new();
let s = async_stream::stream! {
while let Some(chunk) = stream.next().await {
match chunk {
Ok(bytes) => {
if let Ok(text) = std::str::from_utf8(&bytes) {
buf.push_str(text);
while let Some(pos) = buf.find('\n') {
let line = buf[..pos].to_string();
buf.drain(..=pos + 1);
let text = line.trim();
if text.is_empty() { continue; }
if let Ok(value) = serde_json::from_str::<JsonValue>(text) {
for ev in super::parser::pull_events_from_value(&value) {
yield ev;
}
if let Some(err_msg) = value.get("error").and_then(|e| e.as_str()) {
yield OllamaPullEvent::Error(err_msg.to_string());
return;
}
}
}
// Fail closed when the retained tail tops the shared
// SSE bound, so a peer that never emits a newline
// cannot grow memory for the pull lifetime. The pull
// stream carries no `Result`, so overflow surfaces
// as an error event like a server-side failure.
if let Err(overflow) =
crate::providers::shared::check_sse_tail_bound(buf.len())
{
yield OllamaPullEvent::Error(format!(
"Ollama pull stream error: {overflow}"
));
return;
}
}
}
Err(_) => {
// Connection error: end the stream.
return;
}
}
}
};
Ok(Box::pin(s))
}
/// High-level helper to pull a model and drive a progress reporter.
/// Adapted from OpenAI Codex's codex-ollama/src/client.rs
pub(crate) async fn pull_with_reporter(
&self,
model: &str,
reporter: &mut (dyn OllamaPullProgressReporter + Send),
) -> io::Result<()> {
reporter.on_event(&OllamaPullEvent::Status(format!("Pulling model {model}...")))?;
let mut stream = self.pull_model_stream(model).await?;
while let Some(event) = stream.next().await {
reporter.on_event(&event)?;
match event {
OllamaPullEvent::Success => {
return Ok(());
}
OllamaPullEvent::Error(err) => {
// Empirically, ollama returns a 200 OK response even when
// the output stream includes an error message. Verify with:
//
// `curl -i http://localhost:11434/api/pull -d '{ "model": "foobarbaz" }'`
//
// When we see an error in the stream, we return it to the
// caller as an I/O error.
return Err(io::Error::other(err));
}
_ => {}
}
}
// Stream ended without explicit success or error.
Err(io::Error::other("Pull stream ended unexpectedly"))
}
}
#[cfg(test)]
mod tests {
use semver::Version;
#[test]
fn test_client_creation_requires_valid_base_url() {
// This would require a running Ollama server to test properly.
// For now, we verify the URL parsing logic in url.rs tests.
}
#[test]
fn test_version_parsing() {
// Test that semver::Version parses Ollama version strings correctly
let v = Version::parse("0.14.1").expect("parse version");
assert_eq!(v.major, 0);
assert_eq!(v.minor, 14);
assert_eq!(v.patch, 1);
}
#[test]
fn test_version_parsing_strips_v_prefix() {
// Ollama may return versions with 'v' prefix
let version_str = "v0.13.4";
let normalized = version_str.trim_start_matches('v');
let v = Version::parse(normalized).expect("parse version");
assert_eq!(v, Version::new(0, 13, 4));
}
#[tokio::test]
async fn pull_stream_fails_closed_on_boundary_less_tail() {
use futures::StreamExt;
use wiremock::matchers::{method, path};
use wiremock::{Mock, ResponseTemplate};
use super::OllamaClient;
use crate::providers::ollama::pull::OllamaPullEvent;
use crate::providers::shared::MAX_SSE_TAIL_BYTES;
use crate::providers::test_support::start_mock_server_or_skip;
let Some(server) = start_mock_server_or_skip().await else {
return;
};
Mock::given(method("GET"))
.and(path("/api/tags"))
.respond_with(ResponseTemplate::new(200).set_body_string("{\"models\":[]}"))
.expect(1)
.mount(&server)
.await;
// No newline anywhere: the whole body stays retained past the cap.
let body = "x".repeat(MAX_SSE_TAIL_BYTES + 1);
Mock::given(method("POST"))
.and(path("/api/pull"))
.respond_with(ResponseTemplate::new(200).set_body_string(body))
.expect(1)
.mount(&server)
.await;
let client = OllamaClient::try_from_base_url(&server.uri())
.await
.expect("client should probe");
let mut stream = client.pull_model_stream("test-model").await.expect("pull should start");
// The pull stream carries no `Result`: overflow must surface as an
// error event like a server-side failure.
let mut saw_overflow = false;
while let Some(event) = stream.next().await {
if let OllamaPullEvent::Error(message) = event {
assert!(message.contains("without an event boundary"), "{message}");
saw_overflow = true;
}
}
assert!(saw_overflow, "boundary-less tail past the cap must trip");
}
}