unofficial_opencode_sdk/
client.rs1use std::sync::Arc;
2
3use reqwest::{Method, RequestBuilder, Response};
4use serde::Serialize;
5use serde::de::DeserializeOwned;
6use url::Url;
7
8use crate::error::{ApiError, Error};
9use crate::models::{CreateSessionRequest, MessageWithParts, PromptRequest, Session};
10use crate::sse::{EventStream, event_stream_from_response};
11
12#[derive(Clone)]
13pub struct Client {
14 inner: Arc<Inner>,
15}
16
17struct Inner {
18 base_url: Url,
19 http: reqwest::Client,
20 directory: Option<String>,
21 workspace: Option<String>,
22 username: Option<String>,
23 password: Option<String>,
24}
25
26#[derive(Default)]
27pub struct ClientBuilder {
28 base_url: Option<String>,
29 http: Option<reqwest::Client>,
30 directory: Option<String>,
31 workspace: Option<String>,
32 username: Option<String>,
33 password: Option<String>,
34}
35
36impl Client {
37 pub fn builder() -> ClientBuilder {
38 ClientBuilder::default()
39 }
40
41 pub fn session(&self) -> SessionApi<'_> {
42 SessionApi { client: self }
43 }
44
45 pub fn events(&self) -> EventsApi<'_> {
46 EventsApi { client: self }
47 }
48
49 pub fn v2(&self) -> crate::v2::Client {
55 crate::v2::Client::from_current(self.clone())
56 }
57
58 pub(crate) fn url(&self, path: &str) -> Result<Url, Error> {
59 Ok(self.inner.base_url.join(path.trim_start_matches('/'))?)
60 }
61
62 pub(crate) fn request_url(&self, method: Method, url: Url) -> RequestBuilder {
63 let mut request = self.inner.http.request(method, url);
64 if let Some(password) = &self.inner.password {
65 let username = self.inner.username.as_deref().unwrap_or("opencode");
66 request = request.basic_auth(username, Some(password));
67 }
68 request
69 }
70
71 pub(crate) fn request_base(&self, method: Method, path: &str) -> Result<RequestBuilder, Error> {
72 Ok(self.request_url(method, self.url(path)?))
73 }
74
75 pub(crate) fn request(&self, method: Method, path: &str) -> Result<RequestBuilder, Error> {
76 let mut url = self.url(path)?;
77 {
78 let mut query = url.query_pairs_mut();
79 if let Some(directory) = &self.inner.directory {
80 query.append_pair("directory", directory);
81 }
82 if let Some(workspace) = &self.inner.workspace {
83 query.append_pair("workspace", workspace);
84 }
85 }
86 Ok(self.request_url(method, url))
87 }
88
89 pub(crate) fn configured_directory(&self) -> Option<&str> {
90 self.inner.directory.as_deref()
91 }
92
93 pub(crate) fn configured_workspace(&self) -> Option<&str> {
94 self.inner.workspace.as_deref()
95 }
96
97 pub(crate) async fn decode<T: DeserializeOwned>(&self, response: Response) -> Result<T, Error> {
98 if response.status().is_success() {
99 return Ok(response.json().await?);
100 }
101 Err(api_error(response).await.into())
102 }
103
104 pub(crate) async fn ensure_success(&self, response: Response) -> Result<(), Error> {
105 if response.status().is_success() {
106 return Ok(());
107 }
108 Err(api_error(response).await.into())
109 }
110}
111
112impl ClientBuilder {
113 pub fn base_url(mut self, base_url: impl Into<String>) -> Self {
114 self.base_url = Some(base_url.into());
115 self
116 }
117
118 pub fn http_client(mut self, client: reqwest::Client) -> Self {
119 self.http = Some(client);
120 self
121 }
122
123 pub fn directory(mut self, directory: impl Into<String>) -> Self {
125 self.directory = Some(directory.into());
126 self
127 }
128
129 pub fn workspace(mut self, workspace: impl Into<String>) -> Self {
131 self.workspace = Some(workspace.into());
132 self
133 }
134
135 pub fn basic_auth(mut self, username: impl Into<String>, password: impl Into<String>) -> Self {
138 self.username = Some(username.into());
139 self.password = Some(password.into());
140 self
141 }
142
143 pub fn password(mut self, password: impl Into<String>) -> Self {
146 self.password = Some(password.into());
147 self
148 }
149
150 pub fn build(self) -> Result<Client, Error> {
151 let raw = self
152 .base_url
153 .unwrap_or_else(|| "http://127.0.0.1:4096".to_owned());
154 let mut base_url = Url::parse(&raw)?;
155 if !base_url.path().ends_with('/') {
156 base_url.set_path(&format!("{}/", base_url.path()));
157 }
158 Ok(Client {
159 inner: Arc::new(Inner {
160 base_url,
161 http: self.http.unwrap_or_default(),
162 directory: self.directory,
163 workspace: self.workspace,
164 username: self.username,
165 password: self.password,
166 }),
167 })
168 }
169}
170
171pub struct SessionApi<'a> {
172 pub(crate) client: &'a Client,
173}
174
175impl SessionApi<'_> {
176 pub async fn list(&self) -> Result<Vec<Session>, Error> {
177 let response = self.client.request(Method::GET, "session")?.send().await?;
178 self.client.decode(response).await
179 }
180
181 pub async fn get(&self, session_id: &str) -> Result<Session, Error> {
182 let response = self
183 .client
184 .request(Method::GET, &format!("session/{session_id}"))?
185 .send()
186 .await?;
187 self.client.decode(response).await
188 }
189
190 pub async fn create(&self, body: &CreateSessionRequest) -> Result<Session, Error> {
191 let response = self
192 .client
193 .request(Method::POST, "session")?
194 .json(body)
195 .send()
196 .await?;
197 self.client.decode(response).await
198 }
199
200 pub async fn prompt(
201 &self,
202 session_id: &str,
203 body: &PromptRequest,
204 ) -> Result<MessageWithParts, Error> {
205 let response = self
206 .client
207 .request(Method::POST, &format!("session/{session_id}/message"))?
208 .json(body)
209 .send()
210 .await?;
211 self.client.decode(response).await
212 }
213
214 pub async fn abort(&self, session_id: &str) -> Result<bool, Error> {
215 let response = self
216 .client
217 .request(Method::POST, &format!("session/{session_id}/abort"))?
218 .send()
219 .await?;
220 self.client.decode(response).await
221 }
222
223 pub async fn raw_json<T: Serialize + ?Sized, R: DeserializeOwned>(
224 &self,
225 method: Method,
226 path: &str,
227 body: Option<&T>,
228 ) -> Result<R, Error> {
229 let mut request = self.client.request(method, path)?;
230 if let Some(body) = body {
231 request = request.json(body);
232 }
233 let response = request.send().await?;
234 self.client.decode(response).await
235 }
236}
237
238pub struct EventsApi<'a> {
239 client: &'a Client,
240}
241
242impl EventsApi<'_> {
243 pub async fn subscribe(&self) -> Result<EventStream, Error> {
244 let response = self.client.request(Method::GET, "event")?.send().await?;
245 if !response.status().is_success() {
246 return Err(api_error(response).await.into());
247 }
248 Ok(event_stream_from_response(response))
249 }
250}
251
252async fn api_error(response: Response) -> ApiError {
253 let status = response.status().as_u16();
254 let body = response.text().await.unwrap_or_default();
255 let json = serde_json::from_str(&body).ok();
256 ApiError { status, body, json }
257}