opencode_rs 0.9.0

Rust SDK for OpenCode (HTTP-first hybrid with SSE streaming)
Documentation
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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
//! High-level client API for `OpenCode`.
//!
//! This module provides the ergonomic `Client` and `ClientBuilder` types.

#[cfg(not(feature = "http"))]
use crate::error::OpencodeError;
use crate::error::Result;
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::RwLock;

#[cfg(feature = "http")]
use crate::http::HttpClient;
#[cfg(feature = "http")]
use crate::http::HttpConfig;

/// `OpenCode` client for interacting with the server.
#[derive(Clone)]
pub struct Client {
    #[cfg(feature = "http")]
    http: HttpClient,
    /// Last event ID for SSE reconnection (used by SSE subscriber).
    last_event_id: Arc<RwLock<Option<String>>>,
}

/// Builder for creating a [`Client`].
#[derive(Clone)]
pub struct ClientBuilder {
    base_url: String,
    directory: Option<String>,
    workspace: Option<String>,
    timeout: Duration,
}

impl Default for ClientBuilder {
    fn default() -> Self {
        Self {
            base_url: "http://127.0.0.1:4096".to_string(),
            directory: None,
            workspace: None,
            timeout: Duration::from_secs(1800), // 30 min for long-running tool calls
        }
    }
}

impl ClientBuilder {
    /// Create a new client builder with default settings.
    ///
    /// Default settings:
    /// - Base URL: `http://127.0.0.1:4096`
    /// - Timeout: 1800 seconds (30 minutes)
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the base URL for the `OpenCode` server.
    #[must_use]
    pub fn base_url(mut self, url: impl Into<String>) -> Self {
        self.base_url = url.into();
        self
    }

    /// Set the directory context for requests.
    ///
    /// This sets the `directory` query parameter on non-global requests.
    #[must_use]
    pub fn directory(mut self, dir: impl Into<String>) -> Self {
        self.directory = Some(dir.into());
        self
    }

    /// Set the workspace context for requests.
    #[must_use]
    pub fn workspace(mut self, workspace: impl Into<String>) -> Self {
        self.workspace = Some(workspace.into());
        self
    }

    /// Set the request timeout in seconds.
    #[must_use]
    pub fn timeout_secs(mut self, secs: u64) -> Self {
        self.timeout = Duration::from_secs(secs);
        self
    }

    /// Build the client.
    ///
    /// # Errors
    ///
    /// Returns an error if the HTTP client cannot be built or if the
    /// `http` feature is not enabled.
    #[cfg(feature = "http")]
    pub fn build(self) -> Result<Client> {
        let http = HttpClient::new(HttpConfig {
            base_url: self.base_url,
            directory: self.directory,
            workspace: self.workspace,
            timeout: self.timeout,
        })?;

        Ok(Client {
            http,
            last_event_id: Arc::new(RwLock::new(None)),
        })
    }

    /// Build the client.
    ///
    /// # Errors
    ///
    /// Returns an error because the `http` feature is required.
    #[cfg(not(feature = "http"))]
    pub fn build(self) -> Result<Client> {
        Err(OpencodeError::InvalidConfig(
            "http feature required to build client".into(),
        ))
    }
}

impl Client {
    /// Create a new client builder.
    pub fn builder() -> ClientBuilder {
        ClientBuilder::new()
    }

    /// Get the sessions API.
    #[cfg(feature = "http")]
    pub fn sessions(&self) -> crate::http::sessions::SessionsApi {
        crate::http::sessions::SessionsApi::new(self.http.clone())
    }

    /// Get the messages API.
    #[cfg(feature = "http")]
    pub fn messages(&self) -> crate::http::messages::MessagesApi {
        crate::http::messages::MessagesApi::new(self.http.clone())
    }

    /// Get the parts API.
    #[cfg(feature = "http")]
    pub fn parts(&self) -> crate::http::parts::PartsApi {
        crate::http::parts::PartsApi::new(self.http.clone())
    }

    /// Get the permissions API.
    #[cfg(feature = "http")]
    pub fn permissions(&self) -> crate::http::permissions::PermissionsApi {
        crate::http::permissions::PermissionsApi::new(self.http.clone())
    }

    /// Get the files API.
    #[cfg(feature = "http")]
    pub fn files(&self) -> crate::http::files::FilesApi {
        crate::http::files::FilesApi::new(self.http.clone())
    }

    /// Get the find API.
    #[cfg(feature = "http")]
    pub fn find(&self) -> crate::http::find::FindApi {
        crate::http::find::FindApi::new(self.http.clone())
    }

    /// Get the providers API.
    #[cfg(feature = "http")]
    pub fn providers(&self) -> crate::http::providers::ProvidersApi {
        crate::http::providers::ProvidersApi::new(self.http.clone())
    }

    /// Get the MCP API.
    #[cfg(feature = "http")]
    pub fn mcp(&self) -> crate::http::mcp::McpApi {
        crate::http::mcp::McpApi::new(self.http.clone())
    }

    /// Get the PTY API.
    #[cfg(feature = "http")]
    pub fn pty(&self) -> crate::http::pty::PtyApi {
        crate::http::pty::PtyApi::new(self.http.clone())
    }

    /// Get the config API.
    #[cfg(feature = "http")]
    pub fn config(&self) -> crate::http::config::ConfigApi {
        crate::http::config::ConfigApi::new(self.http.clone())
    }

    /// Get the tools API.
    #[cfg(feature = "http")]
    pub fn tools(&self) -> crate::http::tools::ToolsApi {
        crate::http::tools::ToolsApi::new(self.http.clone())
    }

    /// Get the project API.
    #[cfg(feature = "http")]
    pub fn project(&self) -> crate::http::project::ProjectApi {
        crate::http::project::ProjectApi::new(self.http.clone())
    }

    /// Get the worktree API.
    #[cfg(feature = "http")]
    pub fn worktree(&self) -> crate::http::worktree::WorktreeApi {
        crate::http::worktree::WorktreeApi::new(self.http.clone())
    }

    /// Get the sync API.
    #[cfg(feature = "http")]
    pub fn sync(&self) -> crate::http::sync::SyncApi {
        crate::http::sync::SyncApi::new(self.http.clone())
    }

    /// Get the TUI API.
    #[cfg(feature = "http")]
    pub fn tui(&self) -> crate::http::tui::TuiApi {
        crate::http::tui::TuiApi::new(self.http.clone())
    }

    /// Get the workspaces API.
    #[cfg(feature = "http")]
    pub fn workspaces(&self) -> crate::http::workspaces::WorkspacesApi {
        crate::http::workspaces::WorkspacesApi::new(self.http.clone())
    }

    /// Get the console API.
    #[cfg(feature = "http")]
    pub fn console(&self) -> crate::http::console::ConsoleApi {
        crate::http::console::ConsoleApi::new(self.http.clone())
    }

    /// Get the experimental session API.
    #[cfg(feature = "http")]
    pub fn experimental_session(
        &self,
    ) -> crate::http::experimental_session::ExperimentalSessionApi {
        crate::http::experimental_session::ExperimentalSessionApi::new(self.http.clone())
    }

    /// Get the misc API.
    #[cfg(feature = "http")]
    pub fn misc(&self) -> crate::http::misc::MiscApi {
        crate::http::misc::MiscApi::new(self.http.clone())
    }

    /// Get the question API.
    #[cfg(feature = "http")]
    pub fn question(&self) -> crate::http::question::QuestionApi {
        crate::http::question::QuestionApi::new(self.http.clone())
    }

    /// Get the skills API.
    #[cfg(feature = "http")]
    pub fn skills(&self) -> crate::http::skills::SkillsApi {
        crate::http::skills::SkillsApi::new(self.http.clone())
    }

    /// Get the resource API (experimental).
    #[cfg(feature = "http")]
    pub fn resource(&self) -> crate::http::resource::ResourceApi {
        crate::http::resource::ResourceApi::new(self.http.clone())
    }

    /// Get the global API for event stream metadata and health checks.
    #[cfg(feature = "http")]
    pub fn global(&self) -> crate::http::global::GlobalApi {
        crate::http::global::GlobalApi::new(self.http.clone())
    }

    /// Simple helper to create session and send a text prompt.
    ///
    /// Note: This method returns immediately after sending the prompt.
    /// The AI response will arrive asynchronously via SSE events.
    /// Use [`subscribe_session`] to receive the response.
    ///
    /// # Errors
    ///
    /// Returns an error if session creation or prompt fails.
    #[cfg(feature = "http")]
    pub async fn run_simple_text(
        &self,
        text: impl Into<String>,
    ) -> Result<crate::types::session::Session> {
        use crate::types::message::PromptPart;
        use crate::types::message::PromptRequest;
        use crate::types::session::CreateSessionRequest;

        let session = self
            .sessions()
            .create(&CreateSessionRequest::default())
            .await?;

        let _ = self
            .messages()
            .prompt(
                &session.id,
                &PromptRequest {
                    parts: vec![PromptPart::Text {
                        text: text.into(),
                        synthetic: None,
                        ignored: None,
                        metadata: None,
                    }],
                    message_id: None,
                    model: None,
                    agent: None,
                    no_reply: None,
                    system: None,
                    variant: None,
                },
            )
            .await?;

        Ok(session)
    }

    /// Set the last event ID (for SSE reconnection).
    #[cfg(feature = "sse")]
    #[expect(dead_code)] // Used by SSE subscriber in Phase 5
    pub(crate) async fn set_last_event_id(&self, id: Option<String>) {
        *self.last_event_id.write().await = id;
    }

    /// Get the last event ID.
    #[cfg(feature = "sse")]
    #[expect(dead_code)] // Used by SSE subscriber in Phase 5
    pub(crate) async fn last_event_id(&self) -> Option<String> {
        self.last_event_id.read().await.clone()
    }

    /// Get the HTTP client.
    #[cfg(feature = "http")]
    #[expect(dead_code)] // May be used by external crates
    pub(crate) fn http(&self) -> &HttpClient {
        &self.http
    }

    /// Get the last event ID handle for SSE.
    #[cfg(feature = "sse")]
    #[expect(dead_code)] // May be used by external crates
    pub(crate) fn last_event_id_handle(&self) -> Arc<RwLock<Option<String>>> {
        Arc::clone(&self.last_event_id)
    }
}

#[cfg(all(feature = "http", feature = "sse"))]
impl Client {
    /// Get an SSE subscriber for streaming events.
    pub fn sse_subscriber(&self) -> crate::sse::SseSubscriber {
        crate::sse::SseSubscriber::new(
            self.http.base().to_string(),
            self.http.directory().map(std::string::ToString::to_string),
            self.http.workspace().map(std::string::ToString::to_string),
            Arc::clone(&self.last_event_id),
        )
    }

    /// Subscribe to all events for the configured directory with default options.
    ///
    /// This subscribes to the `/event` endpoint which streams all events
    /// for the directory specified in the client configuration.
    ///
    /// # Errors
    ///
    /// Returns an error if the subscription cannot be created.
    pub fn subscribe(&self) -> Result<crate::sse::SseSubscription<crate::types::event::Event>> {
        self.sse_subscriber()
            .subscribe(crate::sse::SseOptions::default())
    }

    /// Subscribe to events filtered by session ID with default options.
    ///
    /// Events are filtered client-side to only include events matching
    /// the specified session ID.
    ///
    /// # Errors
    ///
    /// Returns an error if the subscription cannot be created.
    pub fn subscribe_session(
        &self,
        session_id: &str,
    ) -> Result<crate::sse::SseSubscription<crate::types::event::Event>> {
        self.sse_subscriber()
            .subscribe_session(session_id, crate::sse::SseOptions::default())
    }

    /// Subscribe to global events with default options (all directories).
    ///
    /// # Errors
    ///
    /// Returns an error if the subscription cannot be created.
    pub fn subscribe_global(
        &self,
    ) -> Result<crate::sse::SseSubscription<crate::types::event::GlobalEvent>> {
        self.sse_subscriber()
            .subscribe_global(crate::sse::SseOptions::default())
    }
}

#[cfg(test)]
mod tests {
    // TODO(3): Add integration tests with mocked HTTP/SSE backends for Client API methods
    use super::*;

    #[test]
    fn test_client_builder_defaults() {
        let builder = ClientBuilder::new();
        assert_eq!(builder.base_url, "http://127.0.0.1:4096");
        assert_eq!(builder.timeout, Duration::from_secs(1800));
        assert!(builder.directory.is_none());
        assert!(builder.workspace.is_none());
    }

    #[test]
    fn test_client_builder_customization() {
        let builder = ClientBuilder::new()
            .base_url("http://localhost:8080")
            .directory("/my/project")
            .workspace("workspace-1")
            .timeout_secs(60);

        assert_eq!(builder.base_url, "http://localhost:8080");
        assert_eq!(builder.directory, Some("/my/project".to_string()));
        assert_eq!(builder.workspace, Some("workspace-1".to_string()));
        assert_eq!(builder.timeout, Duration::from_secs(60));
    }

    #[cfg(feature = "http")]
    #[test]
    fn test_client_build() {
        let client = ClientBuilder::new().build();
        assert!(client.is_ok());
    }
}