Skip to main content

unofficial_opencode_sdk/v2/
resources.rs

1use std::collections::BTreeMap;
2
3use bytes::Bytes;
4use reqwest::Method;
5use serde::{Deserialize, Serialize};
6use serde_json::Value;
7
8use super::{Client, ServeDialect};
9use crate::Error;
10
11/// Per-request V2 location override.
12///
13/// Query endpoints encode this using OpenCode's deep-object parameters:
14/// `location[directory]` and `location[workspace]`.
15#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
16pub struct LocationQuery {
17    #[serde(default, skip_serializing_if = "Option::is_none")]
18    pub directory: Option<String>,
19    #[serde(default, skip_serializing_if = "Option::is_none")]
20    pub workspace: Option<String>,
21}
22
23#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
24pub struct ProjectLocationInfo {
25    pub id: String,
26    pub directory: String,
27}
28
29#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
30#[serde(rename_all = "camelCase")]
31pub struct LocationInfo {
32    pub directory: String,
33    #[serde(default, rename = "workspaceID")]
34    pub workspace_id: Option<String>,
35    /// `GET api/location` fills this; 2.x list envelopes return the
36    /// public location ref without `project`.
37    #[serde(default)]
38    pub project: Option<ProjectLocationInfo>,
39}
40
41#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
42pub struct Located<T> {
43    pub location: LocationInfo,
44    pub data: T,
45}
46
47/// Stable top-level fields from OpenCode's preview `ModelV2Info`.
48///
49/// The deeply nested provider-specific model contract is retained losslessly as
50/// JSON while V2 remains preview.
51#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
52#[serde(rename_all = "camelCase")]
53pub struct ModelInfo {
54    pub id: String,
55    #[serde(rename = "providerID")]
56    pub provider_id: String,
57    #[serde(default)]
58    pub family: Option<String>,
59    pub name: String,
60    /// 1.x-preview fields; 2.x reports `package`/`compatibility` instead.
61    #[serde(default)]
62    pub api: Value,
63    pub capabilities: Value,
64    #[serde(default)]
65    pub request: Value,
66    #[serde(default)]
67    pub variants: Vec<Value>,
68    pub time: Value,
69    #[serde(default)]
70    pub cost: Vec<Value>,
71    pub status: String,
72    pub enabled: bool,
73    pub limit: Value,
74    #[serde(flatten)]
75    pub extra: BTreeMap<String, Value>,
76}
77
78#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
79#[serde(rename_all = "camelCase")]
80pub struct ProviderInfo {
81    pub id: String,
82    #[serde(default, rename = "integrationID")]
83    pub integration_id: Option<String>,
84    pub name: String,
85    /// 1.x-preview flag; 2.x reports readiness as `activation` instead.
86    #[serde(default)]
87    pub disabled: Option<bool>,
88    /// 1.x-preview fields; 2.x exposes `package`/`settings` instead.
89    #[serde(default)]
90    pub api: Value,
91    #[serde(default)]
92    pub request: Value,
93    #[serde(flatten)]
94    pub extra: BTreeMap<String, Value>,
95}
96
97#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
98#[serde(rename_all = "lowercase")]
99pub enum FileSystemEntryType {
100    File,
101    Directory,
102}
103
104impl FileSystemEntryType {
105    fn as_query(self) -> &'static str {
106        match self {
107            Self::File => "file",
108            Self::Directory => "directory",
109        }
110    }
111}
112
113#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
114pub struct FileSystemEntry {
115    pub path: String,
116    #[serde(rename = "type")]
117    pub entry_type: FileSystemEntryType,
118}
119
120#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
121#[serde(rename_all = "camelCase")]
122pub struct PermissionRequest {
123    pub id: String,
124    #[serde(rename = "sessionID")]
125    pub session_id: String,
126    pub action: String,
127    pub resources: Vec<String>,
128    #[serde(default)]
129    pub save: Vec<String>,
130    #[serde(default)]
131    pub metadata: Option<Value>,
132    #[serde(default)]
133    pub source: Option<Value>,
134    #[serde(flatten)]
135    pub extra: BTreeMap<String, Value>,
136}
137
138#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
139#[serde(rename_all = "camelCase")]
140pub struct SavedPermission {
141    pub id: String,
142    #[serde(rename = "projectID")]
143    pub project_id: String,
144    pub action: String,
145    pub resource: String,
146}
147
148/// Pending question (1.x `api/question/*`) or form (2.x `api/form*`);
149/// both decode into this type — 1.x fills `questions`/`tool`, 2.x fills
150/// `title`/`fields`.
151#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
152#[serde(rename_all = "camelCase")]
153pub struct QuestionRequest {
154    pub id: String,
155    #[serde(rename = "sessionID")]
156    pub session_id: String,
157    #[serde(default)]
158    pub questions: Vec<Value>,
159    #[serde(default)]
160    pub tool: Option<Value>,
161    /// OpenCode 2.x `FormInfo` fields.
162    #[serde(default)]
163    pub title: Option<String>,
164    #[serde(default)]
165    pub fields: Vec<Value>,
166    #[serde(flatten)]
167    pub extra: BTreeMap<String, Value>,
168}
169
170#[derive(Debug, Clone, Default, PartialEq, Eq)]
171pub struct FindFilesOptions {
172    pub query: String,
173    pub entry_type: Option<FileSystemEntryType>,
174    /// Upstream currently exposes this query parameter as a string.
175    pub limit: Option<String>,
176    pub location: Option<LocationQuery>,
177}
178
179#[derive(Debug, Deserialize)]
180struct DataEnvelope<T> {
181    data: T,
182}
183
184pub(super) fn apply_location(
185    url: &mut url::Url,
186    client: &Client,
187    location: Option<&LocationQuery>,
188) {
189    let directory = location
190        .and_then(|value| value.directory.as_deref())
191        .or(client.directory.as_deref());
192    let workspace = location
193        .and_then(|value| value.workspace.as_deref())
194        .or(client.workspace_id.as_deref());
195
196    let mut query = url.query_pairs_mut();
197    if let Some(directory) = directory {
198        query.append_pair("location[directory]", directory);
199    }
200    if let Some(workspace) = workspace {
201        query.append_pair("location[workspace]", workspace);
202    }
203}
204
205pub struct ModelApi<'a> {
206    client: &'a Client,
207}
208
209impl ModelApi<'_> {
210    pub async fn list(
211        &self,
212        location: Option<&LocationQuery>,
213    ) -> Result<Located<Vec<ModelInfo>>, Error> {
214        let mut url = self.client.inner.url("api/model")?;
215        apply_location(&mut url, self.client, location);
216        let response = self
217            .client
218            .inner
219            .request_url(Method::GET, url)
220            .send()
221            .await?;
222        self.client.inner.decode(response).await
223    }
224}
225
226pub struct ProviderApi<'a> {
227    client: &'a Client,
228}
229
230impl ProviderApi<'_> {
231    pub async fn list(
232        &self,
233        location: Option<&LocationQuery>,
234    ) -> Result<Located<Vec<ProviderInfo>>, Error> {
235        let mut url = self.client.inner.url("api/provider")?;
236        apply_location(&mut url, self.client, location);
237        let response = self
238            .client
239            .inner
240            .request_url(Method::GET, url)
241            .send()
242            .await?;
243        self.client.inner.decode(response).await
244    }
245
246    pub async fn get(
247        &self,
248        provider_id: &str,
249        location: Option<&LocationQuery>,
250    ) -> Result<Located<ProviderInfo>, Error> {
251        let mut url = self
252            .client
253            .inner
254            .url(&format!("api/provider/{provider_id}"))?;
255        apply_location(&mut url, self.client, location);
256        let response = self
257            .client
258            .inner
259            .request_url(Method::GET, url)
260            .send()
261            .await?;
262        self.client.inner.decode(response).await
263    }
264}
265
266pub struct FsApi<'a> {
267    client: &'a Client,
268}
269
270impl FsApi<'_> {
271    /// Read a file relative to the requested V2 location.
272    pub async fn read(&self, path: &str, location: Option<&LocationQuery>) -> Result<Bytes, Error> {
273        let mut url = self
274            .client
275            .inner
276            .url(&format!("api/fs/read/{}", path.trim_start_matches('/')))?;
277        apply_location(&mut url, self.client, location);
278        let response = self
279            .client
280            .inner
281            .request_url(Method::GET, url)
282            .send()
283            .await?;
284        if !response.status().is_success() {
285            self.client.inner.ensure_success(response).await?;
286            unreachable!();
287        }
288        Ok(response.bytes().await?)
289    }
290
291    pub async fn list(
292        &self,
293        path: Option<&str>,
294        location: Option<&LocationQuery>,
295    ) -> Result<Located<Vec<FileSystemEntry>>, Error> {
296        let mut url = self.client.inner.url("api/fs/list")?;
297        apply_location(&mut url, self.client, location);
298        if let Some(path) = path {
299            url.query_pairs_mut().append_pair("path", path);
300        }
301        let response = self
302            .client
303            .inner
304            .request_url(Method::GET, url)
305            .send()
306            .await?;
307        self.client.inner.decode(response).await
308    }
309
310    pub async fn find(
311        &self,
312        options: &FindFilesOptions,
313    ) -> Result<Located<Vec<FileSystemEntry>>, Error> {
314        let mut url = self.client.inner.url("api/fs/find")?;
315        apply_location(&mut url, self.client, options.location.as_ref());
316        {
317            let mut query = url.query_pairs_mut();
318            query.append_pair("query", &options.query);
319            if let Some(entry_type) = options.entry_type {
320                query.append_pair("type", entry_type.as_query());
321            }
322            if let Some(limit) = options.limit.as_deref() {
323                query.append_pair("limit", limit);
324            }
325        }
326        let response = self
327            .client
328            .inner
329            .request_url(Method::GET, url)
330            .send()
331            .await?;
332        self.client.inner.decode(response).await
333    }
334}
335
336pub struct PermissionApi<'a> {
337    client: &'a Client,
338}
339
340impl PermissionApi<'_> {
341    pub fn request(&self) -> PermissionRequestApi<'_> {
342        PermissionRequestApi {
343            client: self.client,
344        }
345    }
346
347    pub fn saved(&self) -> SavedPermissionApi<'_> {
348        SavedPermissionApi {
349            client: self.client,
350        }
351    }
352}
353
354pub struct PermissionRequestApi<'a> {
355    client: &'a Client,
356}
357
358impl PermissionRequestApi<'_> {
359    pub async fn list(
360        &self,
361        location: Option<&LocationQuery>,
362    ) -> Result<Located<Vec<PermissionRequest>>, Error> {
363        let mut url = self.client.inner.url("api/permission/request")?;
364        apply_location(&mut url, self.client, location);
365        let response = self
366            .client
367            .inner
368            .request_url(Method::GET, url)
369            .send()
370            .await?;
371        self.client.inner.decode(response).await
372    }
373}
374
375pub struct SavedPermissionApi<'a> {
376    client: &'a Client,
377}
378
379impl SavedPermissionApi<'_> {
380    pub async fn list(&self, project_id: Option<&str>) -> Result<Vec<SavedPermission>, Error> {
381        let mut url = self.client.inner.url("api/permission/saved")?;
382        if let Some(project_id) = project_id {
383            url.query_pairs_mut().append_pair("projectID", project_id);
384        }
385        let response = self
386            .client
387            .inner
388            .request_url(Method::GET, url)
389            .send()
390            .await?;
391        let envelope: DataEnvelope<Vec<SavedPermission>> =
392            self.client.inner.decode(response).await?;
393        Ok(envelope.data)
394    }
395
396    pub async fn remove(&self, id: &str) -> Result<(), Error> {
397        let response = self
398            .client
399            .inner
400            .request_base(Method::DELETE, &format!("api/permission/saved/{id}"))?
401            .send()
402            .await?;
403        self.client.inner.ensure_success(response).await
404    }
405}
406
407pub struct QuestionApi<'a> {
408    client: &'a Client,
409}
410
411impl QuestionApi<'_> {
412    pub fn request(&self) -> QuestionRequestApi<'_> {
413        QuestionRequestApi {
414            client: self.client,
415        }
416    }
417}
418
419pub struct QuestionRequestApi<'a> {
420    client: &'a Client,
421}
422
423impl QuestionRequestApi<'_> {
424    pub async fn list(
425        &self,
426        location: Option<&LocationQuery>,
427    ) -> Result<Located<Vec<QuestionRequest>>, Error> {
428        let path = match self.client.serve_dialect().await? {
429            ServeDialect::Preview1x => "api/question/request",
430            ServeDialect::Native2x => "api/form",
431        };
432        let mut url = self.client.inner.url(path)?;
433        apply_location(&mut url, self.client, location);
434        let response = self
435            .client
436            .inner
437            .request_url(Method::GET, url)
438            .send()
439            .await?;
440        self.client.inner.decode(response).await
441    }
442}
443
444impl Client {
445    pub fn model(&self) -> ModelApi<'_> {
446        ModelApi { client: self }
447    }
448
449    pub fn provider(&self) -> ProviderApi<'_> {
450        ProviderApi { client: self }
451    }
452
453    pub fn fs(&self) -> FsApi<'_> {
454        FsApi { client: self }
455    }
456
457    pub fn permission(&self) -> PermissionApi<'_> {
458        PermissionApi { client: self }
459    }
460
461    pub fn question(&self) -> QuestionApi<'_> {
462        QuestionApi { client: self }
463    }
464}