opencode_rs 0.10.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
//! Error types for `opencode_rs`.

use thiserror::Error;

/// Result type alias for `opencode_rs` operations.
pub type Result<T> = std::result::Result<T, OpencodeError>;

/// Error type for `opencode_rs` operations.
#[derive(Debug, Error)]
pub enum OpencodeError {
    /// HTTP error with structured response from `OpenCode`.
    #[error("HTTP error {status}: {message}")]
    Http {
        /// HTTP status code.
        status: u16,
        /// Error name from `OpenCode`'s `NamedError` (e.g., "`NotFound`", "`ValidationError`").
        name: Option<String>,
        /// Error message.
        message: String,
        /// Additional error data.
        data: Option<serde_json::Value>,
    },

    /// Transport/network error.
    #[error("Transport error: {0}")]
    Transport(#[from] reqwest::Error),

    /// SSE streaming error.
    #[error("SSE error: {0}")]
    Sse(String),

    /// JSON serialization/deserialization error.
    #[error("JSON error: {0}")]
    Json(#[from] serde_json::Error),

    /// URL parsing error.
    #[error("URL error: {0}")]
    Url(#[from] url::ParseError),

    /// Failed to spawn server process.
    #[error("Failed to spawn server: {message}")]
    SpawnServer {
        /// Error message.
        message: String,
    },

    /// Server not ready within timeout.
    #[error("Server not ready within {timeout_ms}ms")]
    ServerTimeout {
        /// Timeout in milliseconds.
        timeout_ms: u64,
    },

    /// Process execution error.
    #[error("Process error: {0}")]
    Process(String),

    /// Invalid configuration.
    #[error("Invalid configuration: {0}")]
    InvalidConfig(String),

    /// IO error.
    #[error("IO error: {0}")]
    Io(#[from] std::io::Error),

    /// Stream closed unexpectedly.
    #[error("Stream closed unexpectedly")]
    StreamClosed,

    /// Session not found.
    #[error("Session not found: {0}")]
    SessionNotFound(String),

    /// Internal state error.
    #[error("Internal state error: {0}")]
    State(String),

    /// Version mismatch between SDK expectation and server response.
    #[error("Version mismatch: expected {expected}, got {actual}")]
    VersionMismatch {
        /// Expected version.
        expected: String,
        /// Actual version.
        actual: String,
    },
}

/// Helper to parse `OpenCode`'s `NamedError` response body.
#[derive(Debug, Clone)]
pub struct HttpErrorBody {
    /// Error name (e.g., "`NotFound`", "`ValidationError`").
    pub name: Option<String>,
    /// Error message.
    pub message: Option<String>,
    /// Additional error data.
    pub data: Option<serde_json::Value>,
}

fn format_error_path(path: &[serde_json::Value]) -> Option<String> {
    let formatted: Vec<String> = path
        .iter()
        .map(|segment| match segment {
            serde_json::Value::String(value) => value.clone(),
            other => other.to_string(),
        })
        .collect();

    if formatted.is_empty() {
        None
    } else {
        Some(formatted.join("."))
    }
}

fn format_validator_entry(entry: &serde_json::Value) -> String {
    let path = entry
        .get("path")
        .and_then(serde_json::Value::as_array)
        .and_then(|segments| format_error_path(segments));
    let message = entry
        .get("message")
        .and_then(serde_json::Value::as_str)
        .map(std::string::ToString::to_string);

    match (path, message) {
        (Some(path), Some(message)) => format!("{path}: {message}"),
        (Some(path), None) => format!("{path}: {entry}"),
        (None, Some(message)) => message,
        (None, None) => entry.to_string(),
    }
}

fn extract_http_error_message(v: &serde_json::Value) -> Option<String> {
    if matches!(v.get("success"), Some(serde_json::Value::Bool(false)))
        && let Some(errors) = v.get("error").and_then(serde_json::Value::as_array)
    {
        let messages: Vec<String> = errors.iter().map(format_validator_entry).collect();
        if !messages.is_empty() {
            return Some(messages.join("; "));
        }
    }

    if let (Some(name), Some(message)) = (
        v.get("name").and_then(serde_json::Value::as_str),
        v.get("data")
            .and_then(|data| data.get("message"))
            .and_then(serde_json::Value::as_str),
    ) {
        return Some(format!("{name}: {message}"));
    }

    v.get("message")
        .and_then(serde_json::Value::as_str)
        .map(std::string::ToString::to_string)
}

fn truncate_body_text(body_text: &str, max_chars: usize) -> String {
    match body_text.char_indices().nth(max_chars) {
        Some((idx, _)) => format!("{}…", &body_text[..idx]),
        None => body_text.to_string(),
    }
}

impl HttpErrorBody {
    /// Parse from a JSON value.
    pub fn from_json(v: &serde_json::Value) -> Self {
        Self {
            name: v
                .get("name")
                .and_then(|x| x.as_str())
                .map(std::string::ToString::to_string),
            message: extract_http_error_message(v),
            data: v.get("data").cloned(),
        }
    }
}

impl OpencodeError {
    /// Create an HTTP error from status and optional JSON body.
    pub fn http(status: u16, body_text: &str) -> Self {
        let parsed: Option<serde_json::Value> = serde_json::from_str(body_text).ok();
        let info = parsed.as_ref().map(HttpErrorBody::from_json);
        let message = info
            .as_ref()
            .and_then(|i| i.message.clone())
            .unwrap_or_else(|| {
                let truncated = truncate_body_text(body_text, 1024);
                if truncated.trim().is_empty() {
                    format!("HTTP {status}")
                } else {
                    truncated
                }
            });

        Self::Http {
            status,
            name: info.as_ref().and_then(|i| i.name.clone()),
            message,
            data: info.and_then(|i| i.data),
        }
    }

    /// Check if this is a "not found" error (404).
    pub fn is_not_found(&self) -> bool {
        matches!(self, Self::Http { status: 404, .. })
    }

    /// Check if this is a validation error (400).
    pub fn is_validation_error(&self) -> bool {
        matches!(self, Self::Http { status: 400, .. })
    }

    /// Check if this is a server error (5xx).
    pub fn is_server_error(&self) -> bool {
        matches!(self, Self::Http { status, .. } if *status >= 500)
    }

    /// Get the error name if this is an HTTP error.
    pub fn error_name(&self) -> Option<&str> {
        match self {
            Self::Http { name, .. } => name.as_deref(),
            _ => None,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_http_error_from_named_error() {
        let body = r#"{"name":"NotFound","data":{"message":"Session not found","id":"123"}}"#;
        let err = OpencodeError::http(404, body);

        match err {
            OpencodeError::Http {
                status,
                name,
                message,
                data,
            } => {
                assert_eq!(status, 404);
                assert_eq!(name, Some("NotFound".to_string()));
                assert_eq!(message, "NotFound: Session not found");
                assert!(data.is_some());
            }
            _ => panic!("Expected Http error"),
        }
    }

    #[test]
    fn test_http_error_from_plain_text() {
        let err = OpencodeError::http(500, "Internal Server Error");

        match err {
            OpencodeError::Http {
                status,
                name,
                message,
                ..
            } => {
                assert_eq!(status, 500);
                assert!(name.is_none());
                assert_eq!(message, "Internal Server Error");
            }
            _ => panic!("Expected Http error"),
        }
    }

    #[test]
    fn test_http_error_from_empty_body_uses_status_fallback() {
        let err = OpencodeError::http(502, "");

        match err {
            OpencodeError::Http {
                status,
                name,
                message,
                ..
            } => {
                assert_eq!(status, 502);
                assert!(name.is_none());
                assert_eq!(message, "HTTP 502");
            }
            _ => panic!("Expected Http error"),
        }
    }

    #[test]
    fn test_http_error_from_whitespace_body_uses_status_fallback() {
        let err = OpencodeError::http(503, "   \n");

        match err {
            OpencodeError::Http {
                status,
                name,
                message,
                ..
            } => {
                assert_eq!(status, 503);
                assert!(name.is_none());
                assert_eq!(message, "HTTP 503");
            }
            _ => panic!("Expected Http error"),
        }
    }

    #[test]
    fn test_http_error_from_legacy_top_level_message() {
        let body = r#"{"name":"ValidationError","message":"Legacy message"}"#;
        let err = OpencodeError::http(400, body);

        match err {
            OpencodeError::Http { name, message, .. } => {
                assert_eq!(name, Some("ValidationError".to_string()));
                assert_eq!(message, "Legacy message");
            }
            _ => panic!("Expected Http error"),
        }
    }

    #[test]
    fn test_http_error_from_validator_messageid_invalid() {
        let body = r#"{
  "data": {"command":"linear","arguments":"hello","messageID":"550e8400-e29b-41d4-a716-446655440000"},
  "error": [
    {
      "origin": "string",
      "code": "invalid_format",
      "format": "starts_with",
      "prefix": "msg",
      "path": ["messageID"],
      "message": "Invalid string: must start with \"msg\""
    }
  ],
  "success": false
}"#;
        let err = OpencodeError::http(400, body);

        match err {
            OpencodeError::Http { message, .. } => {
                assert!(message.contains("messageID"), "message was: {message}");
                assert!(
                    message.contains("must start with"),
                    "message was: {message}"
                );
            }
            _ => panic!("Expected Http error"),
        }
    }

    #[test]
    fn test_http_error_from_named_error_unknown_command() {
        let body = r#"{
  "name": "UnknownError",
  "data": {
    "message": "Command not found: \"___definitely_not_a_real_command___\". Available commands: init, review, ..."
  }
}"#;
        let err = OpencodeError::http(400, body);

        match err {
            OpencodeError::Http { message, .. } => {
                assert!(
                    message.contains("Command not found"),
                    "message was: {message}"
                );
                assert!(
                    message.contains("___definitely_not_a_real_command___"),
                    "message was: {message}"
                );
            }
            _ => panic!("Expected Http error"),
        }
    }

    #[test]
    fn test_http_error_from_unknown_shape_preserves_body() {
        let body = r#"{ "weird": "shape" }"#;
        let err = OpencodeError::http(418, body);

        match err {
            OpencodeError::Http { message, .. } => {
                assert!(message.contains(body), "message was: {message}");
            }
            _ => panic!("Expected Http error"),
        }
    }

    #[test]
    fn test_is_not_found() {
        let err = OpencodeError::http(404, "{}");
        assert!(err.is_not_found());

        let err = OpencodeError::http(200, "{}");
        assert!(!err.is_not_found());
    }

    #[test]
    fn test_is_validation_error() {
        let err = OpencodeError::http(400, r#"{"name":"ValidationError"}"#);
        assert!(err.is_validation_error());
        assert_eq!(err.error_name(), Some("ValidationError"));
    }

    #[test]
    fn test_is_server_error() {
        let err = OpencodeError::http(500, "{}");
        assert!(err.is_server_error());

        let err = OpencodeError::http(503, "{}");
        assert!(err.is_server_error());

        let err = OpencodeError::http(400, "{}");
        assert!(!err.is_server_error());
    }
}