opencode_rs 0.6.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
//! Provider types for `opencode_rs`.

use serde::Deserialize;
use serde::Serialize;
use std::collections::HashMap;

/// Response from the provider list endpoint.
///
/// Contains all available providers along with defaults and connection status.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ProviderListResponse {
    /// All available providers.
    #[serde(default)]
    pub all: Vec<Provider>,
    /// Default model for each provider (`provider_id` -> `model_id`).
    #[serde(default)]
    pub default: HashMap<String, String>,
    /// List of connected/authenticated provider IDs.
    #[serde(default)]
    pub connected: Vec<String>,
}

/// Provider source type.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[non_exhaustive]
#[serde(rename_all = "lowercase")]
pub enum ProviderSource {
    /// From environment variable.
    Env,
    /// From config file.
    Config,
    /// Custom provider.
    Custom,
    /// From API.
    Api,
    /// Unknown source (forward compatibility).
    #[serde(other)]
    Unknown,
}

/// A provider configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Provider {
    /// Provider identifier.
    pub id: String,
    /// Provider display name.
    pub name: String,
    /// Source of this provider configuration.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub source: Option<ProviderSource>,
    /// Environment variable names for this provider.
    #[serde(default)]
    pub env: Vec<String>,
    /// API key if set.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub key: Option<String>,
    /// Provider options.
    #[serde(default)]
    pub options: HashMap<String, serde_json::Value>,
    /// Available models for this provider (keyed by model ID).
    #[serde(default)]
    pub models: HashMap<String, Model>,
    /// Additional fields.
    #[serde(flatten)]
    pub extra: serde_json::Value,
}

/// A model available from a provider.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Model {
    /// Model identifier.
    pub id: String,
    /// Model display name.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// Model API configuration.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub api: Option<ModelApi>,
    /// Model capabilities.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub capabilities: Option<ModelCapabilities>,
    /// Model cost information.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cost: Option<ModelCost>,
    /// Model limits.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub limit: Option<ModelLimit>,
    /// Model status.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub status: Option<ModelStatus>,
    /// Custom headers for this model.
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub headers: HashMap<String, String>,
    /// Model release date.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub release_date: Option<String>,
    /// Model variants.
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub variants: HashMap<String, serde_json::Value>,
    /// Additional fields.
    #[serde(flatten)]
    pub extra: serde_json::Value,
}

/// Model API configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ModelApi {
    /// API endpoint override.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub endpoint: Option<String>,
    /// Additional fields.
    #[serde(flatten)]
    pub extra: serde_json::Value,
}

/// Model cost information.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ModelCost {
    /// Cost per input token (in USD per million tokens).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub input: Option<f64>,
    /// Cost per output token (in USD per million tokens).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub output: Option<f64>,
    /// Cost per cache read token.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cache_read: Option<f64>,
    /// Cost per cache write token.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cache_write: Option<f64>,
    /// Additional fields.
    #[serde(flatten)]
    pub extra: serde_json::Value,
}

/// Model limits.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ModelLimit {
    /// Maximum context window size.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub context: Option<u64>,
    /// Maximum output tokens.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub output: Option<u64>,
    /// Additional fields.
    #[serde(flatten)]
    pub extra: serde_json::Value,
}

/// Model status.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[non_exhaustive]
#[serde(rename_all = "lowercase")]
pub enum ModelStatus {
    /// Model is available.
    Available,
    /// Model is deprecated.
    Deprecated,
    /// Model is in beta.
    Beta,
    /// Model is in preview.
    Preview,
    /// Unknown status (forward compatibility).
    #[serde(other)]
    Unknown,
}

/// Model capabilities.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ModelCapabilities {
    /// Whether the model supports tool use.
    #[serde(default)]
    pub tool_use: bool,
    /// Whether the model supports vision/images.
    #[serde(default)]
    pub vision: bool,
    /// Whether the model supports extended thinking.
    #[serde(default)]
    pub thinking: bool,
    /// Interleaved reasoning support.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub interleaved: Option<InterleavedCapability>,
    /// Additional fields.
    #[serde(flatten)]
    pub extra: serde_json::Value,
}

/// Interleaved reasoning capability (can be bool or config object).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum InterleavedCapability {
    /// Simple boolean flag.
    Bool(bool),
    /// Detailed configuration.
    Config(InterleavedConfig),
    /// Unknown configuration (forward compatibility).
    Unknown(serde_json::Value),
}

/// Interleaved reasoning configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct InterleavedConfig {
    /// The field to use for interleaved content.
    pub field: InterleavedField,
    /// Additional fields.
    #[serde(flatten)]
    pub extra: serde_json::Value,
}

/// Field for interleaved reasoning content.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[non_exhaustive]
#[serde(rename_all = "snake_case")]
pub enum InterleavedField {
    /// Use `reasoning_content` field.
    ReasoningContent,
    /// Use `reasoning_details` field.
    ReasoningDetails,
    /// Unknown field type (forward compatibility).
    #[serde(other)]
    Unknown,
}

/// Provider authentication info.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ProviderAuth {
    /// Provider identifier.
    pub provider_id: String,
    /// Authentication method.
    pub method: AuthMethod,
    /// Whether auth is configured.
    #[serde(default)]
    pub configured: bool,
}

/// Authentication method for a provider.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
#[serde(tag = "type", rename_all = "kebab-case")]
pub enum AuthMethod {
    /// API key authentication.
    ApiKey {
        /// Environment variable name for the key.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        env_var: Option<String>,
    },
    /// OAuth authentication.
    Oauth {
        /// OAuth authorize URL.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        authorize_url: Option<String>,
    },
    /// No authentication required.
    None,
    /// Unknown auth method (forward compatibility).
    #[serde(other)]
    Unknown,
}

/// Request to set authentication for a provider.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SetAuthRequest {
    /// The API key or token.
    pub key: String,
}

/// OAuth authorize response.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OAuthAuthorizeResponse {
    /// The authorization URL to redirect to.
    pub url: String,
}

/// OAuth callback request.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OAuthCallbackRequest {
    /// The authorization code.
    pub code: String,
    /// Optional state parameter.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub state: Option<String>,
}

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

    #[test]
    fn test_model_minimal() {
        let json = r#"{"id": "claude-3"}"#;
        let model: Model = serde_json::from_str(json).unwrap();
        assert_eq!(model.id, "claude-3");
        assert!(model.name.is_none());
        assert!(model.capabilities.is_none());
    }

    #[test]
    fn test_model_full() {
        let json = r#"{
            "id": "claude-3",
            "name": "Claude 3",
            "api": {"endpoint": "https://api.example.com"},
            "capabilities": {"toolUse": true, "vision": true, "thinking": false},
            "cost": {"input": 3.0, "output": 15.0},
            "limit": {"context": 200000, "output": 4096},
            "status": "available",
            "releaseDate": "2024-01-01",
            "headers": {"X-Custom": "value"}
        }"#;
        let model: Model = serde_json::from_str(json).unwrap();
        assert_eq!(model.id, "claude-3");
        assert_eq!(model.name, Some("Claude 3".to_string()));
        assert!(model.api.is_some());
        assert!(model.capabilities.is_some());
        let caps = model.capabilities.unwrap();
        assert!(caps.tool_use);
        assert!(caps.vision);
        assert!(!caps.thinking);
        assert!(model.cost.is_some());
        let cost = model.cost.unwrap();
        assert_eq!(cost.input, Some(3.0));
        assert_eq!(cost.output, Some(15.0));
        assert!(model.limit.is_some());
        assert_eq!(model.limit.unwrap().context, Some(200_000));
        assert_eq!(model.status, Some(ModelStatus::Available));
        assert_eq!(model.release_date, Some("2024-01-01".to_string()));
        assert_eq!(model.headers.get("X-Custom"), Some(&"value".to_string()));
    }

    #[test]
    fn test_model_status_variants() {
        assert_eq!(
            serde_json::from_str::<ModelStatus>(r#""available""#).unwrap(),
            ModelStatus::Available
        );
        assert_eq!(
            serde_json::from_str::<ModelStatus>(r#""deprecated""#).unwrap(),
            ModelStatus::Deprecated
        );
        assert_eq!(
            serde_json::from_str::<ModelStatus>(r#""beta""#).unwrap(),
            ModelStatus::Beta
        );
        assert_eq!(
            serde_json::from_str::<ModelStatus>(r#""preview""#).unwrap(),
            ModelStatus::Preview
        );
        assert_eq!(
            serde_json::from_str::<ModelStatus>(r#""future-status""#).unwrap(),
            ModelStatus::Unknown
        );
    }

    #[test]
    fn test_interleaved_capability_bool() {
        let json = r"true";
        let cap: InterleavedCapability = serde_json::from_str(json).unwrap();
        assert!(matches!(cap, InterleavedCapability::Bool(true)));
    }

    #[test]
    fn test_interleaved_capability_config() {
        let json = r#"{"field": "reasoning_content"}"#;
        let cap: InterleavedCapability = serde_json::from_str(json).unwrap();
        if let InterleavedCapability::Config(config) = cap {
            assert_eq!(config.field, InterleavedField::ReasoningContent);
        } else {
            panic!("Expected InterleavedCapability::Config");
        }
    }

    #[test]
    fn test_interleaved_capability_unknown_config() {
        let json = r#"{"field": "future_field"}"#;
        let cap: InterleavedCapability = serde_json::from_str(json).unwrap();
        if let InterleavedCapability::Config(config) = cap {
            assert_eq!(config.field, InterleavedField::Unknown);
        } else {
            panic!("Expected InterleavedCapability::Config");
        }
    }

    #[test]
    fn test_model_capabilities_with_interleaved() {
        let json = r#"{
            "toolUse": true,
            "vision": false,
            "thinking": true,
            "interleaved": {"field": "reasoning_details"}
        }"#;
        let caps: ModelCapabilities = serde_json::from_str(json).unwrap();
        assert!(caps.tool_use);
        assert!(!caps.vision);
        assert!(caps.thinking);
        assert!(caps.interleaved.is_some());
        if let Some(InterleavedCapability::Config(config)) = caps.interleaved {
            assert_eq!(config.field, InterleavedField::ReasoningDetails);
        } else {
            panic!("Expected InterleavedCapability::Config");
        }
    }

    #[test]
    fn test_provider_source_variants() {
        assert_eq!(
            serde_json::from_str::<ProviderSource>(r#""env""#).unwrap(),
            ProviderSource::Env
        );
        assert_eq!(
            serde_json::from_str::<ProviderSource>(r#""config""#).unwrap(),
            ProviderSource::Config
        );
        assert_eq!(
            serde_json::from_str::<ProviderSource>(r#""future""#).unwrap(),
            ProviderSource::Unknown
        );
    }
}