opencode_rs 0.11.1

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
//! Tool and agent types for `opencode_rs`.

use crate::types::permission::Ruleset;
use crate::types::project::ModelRef;
use serde::Deserialize;
use serde::Serialize;
use std::collections::HashMap;

/// A tool definition returned by `GET /experimental/tool`.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ToolListItem {
    /// Tool identifier.
    pub id: String,
    /// Tool description.
    pub description: String,
    /// Input parameters JSON schema.
    pub parameters: serde_json::Value,
}

/// Agent mode (how the agent operates).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[non_exhaustive]
#[serde(rename_all = "lowercase")]
pub enum AgentMode {
    /// Subagent mode (child agent).
    Subagent,
    /// Primary agent mode.
    Primary,
    /// Available in all contexts.
    All,
    /// Unknown mode (forward compatibility).
    #[serde(other)]
    Unknown,
}

/// An agent definition.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Agent {
    /// Agent name.
    pub name: String,

    /// Agent description.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,

    /// System prompt.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub system: Option<String>,

    /// Allowed tools.
    #[serde(default)]
    pub tools: Vec<String>,

    /// Whether this is a built-in agent.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub builtin: Option<bool>,

    // ==================== Upstream parity fields ====================
    /// Agent mode (subagent, primary, all).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub mode: Option<AgentMode>,

    /// Whether this is a native agent.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub native: Option<bool>,

    /// Whether this agent is hidden from UI.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub hidden: Option<bool>,

    /// Top-p sampling parameter.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub top_p: Option<f64>,

    /// Temperature sampling parameter.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub temperature: Option<f64>,

    /// Agent color for UI display.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub color: Option<String>,

    /// Permission ruleset for this agent.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub permission: Option<Ruleset>,

    /// Model reference for this agent.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub model: Option<ModelRef>,

    /// Model variant name.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub variant: Option<String>,

    /// Prompt template for this agent.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub prompt: Option<String>,

    /// Additional options.
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub options: HashMap<String, serde_json::Value>,

    /// Maximum steps for this agent.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub steps: Option<u32>,

    /// Additional fields from server.
    #[serde(flatten)]
    pub extra: serde_json::Value,
}

/// A command definition.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Command {
    /// Command name.
    pub name: String,
    /// Command description.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// Command shortcut key.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub shortcut: Option<String>,
}

/// List of tool IDs.
///
/// Deserializes directly from a JSON array (e.g., `["tool-a", "tool-b"]`).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(transparent)]
pub struct ToolIds(pub Vec<String>);

/// Tool list response.
pub type ToolList = Vec<ToolListItem>;

impl ToolIds {
    /// Returns the inner vector of tool IDs.
    pub fn into_inner(self) -> Vec<String> {
        self.0
    }

    /// Returns a reference to the inner vector.
    pub fn as_slice(&self) -> &[String] {
        &self.0
    }

    /// Returns true if empty.
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// Returns the number of tool IDs.
    pub fn len(&self) -> usize {
        self.0.len()
    }
}

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

    #[test]
    fn test_agent_mode_serialize() {
        assert_eq!(
            serde_json::to_string(&AgentMode::Subagent).unwrap(),
            r#""subagent""#
        );
        assert_eq!(
            serde_json::to_string(&AgentMode::Primary).unwrap(),
            r#""primary""#
        );
        assert_eq!(serde_json::to_string(&AgentMode::All).unwrap(), r#""all""#);
    }

    #[test]
    fn test_agent_mode_deserialize() {
        assert_eq!(
            serde_json::from_str::<AgentMode>(r#""subagent""#).unwrap(),
            AgentMode::Subagent
        );
        assert_eq!(
            serde_json::from_str::<AgentMode>(r#""primary""#).unwrap(),
            AgentMode::Primary
        );
        assert_eq!(
            serde_json::from_str::<AgentMode>(r#""all""#).unwrap(),
            AgentMode::All
        );
    }

    #[test]
    fn test_agent_mode_unknown() {
        // Unknown mode should deserialize as Unknown
        assert_eq!(
            serde_json::from_str::<AgentMode>(r#""future_mode""#).unwrap(),
            AgentMode::Unknown
        );
    }

    #[test]
    fn test_agent_minimal() {
        let json = r#"{"name": "coder"}"#;
        let agent: Agent = serde_json::from_str(json).unwrap();
        assert_eq!(agent.name, "coder");
        assert!(agent.tools.is_empty());
        assert_eq!(agent.builtin, None);
        assert_eq!(agent.native, None);
        assert_eq!(agent.hidden, None);
        assert!(agent.mode.is_none());
    }

    #[test]
    fn test_agent_with_new_fields() {
        let json = r##"{
            "name": "custom-agent",
            "description": "A custom agent",
            "builtin": false,
            "mode": "subagent",
            "native": true,
            "hidden": false,
            "topP": 0.9,
            "temperature": 0.7,
            "color": "#ff0000",
            "variant": "fast",
            "prompt": "You are helpful",
            "steps": 10,
            "tools": ["read", "write"]
        }"##;
        let agent: Agent = serde_json::from_str(json).unwrap();
        assert_eq!(agent.name, "custom-agent");
        assert_eq!(agent.description, Some("A custom agent".to_string()));
        assert_eq!(agent.builtin, Some(false));
        assert_eq!(agent.mode, Some(AgentMode::Subagent));
        assert_eq!(agent.native, Some(true));
        assert_eq!(agent.hidden, Some(false));
        assert_eq!(agent.top_p, Some(0.9));
        assert_eq!(agent.temperature, Some(0.7));
        assert_eq!(agent.color, Some("#ff0000".to_string()));
        assert_eq!(agent.variant, Some("fast".to_string()));
        assert_eq!(agent.prompt, Some("You are helpful".to_string()));
        assert_eq!(agent.steps, Some(10));
        assert_eq!(agent.tools, vec!["read", "write"]);
    }

    #[test]
    fn test_agent_with_model_ref() {
        // 1.3.17 uses uppercase ID casing
        let json = r#"{
            "name": "model-agent",
            "model": {
                "providerID": "anthropic",
                "modelID": "claude-3-opus"
            }
        }"#;
        let agent: Agent = serde_json::from_str(json).unwrap();
        assert_eq!(agent.name, "model-agent");
        let model = agent.model.unwrap();
        assert_eq!(model.provider_id, Some("anthropic".to_string()));
        assert_eq!(model.model_id, Some("claude-3-opus".to_string()));
    }

    #[test]
    fn test_agent_with_permission() {
        let json = r#"{
            "name": "restricted-agent",
            "permission": [
                {"permission": "file.read", "pattern": "**/*.rs", "action": "allow"}
            ]
        }"#;
        let agent: Agent = serde_json::from_str(json).unwrap();
        assert_eq!(agent.name, "restricted-agent");
        let permission = agent.permission.unwrap();
        assert_eq!(permission.len(), 1);
        assert_eq!(permission[0].permission, "file.read");
    }

    #[test]
    fn test_agent_with_options() {
        let json = r#"{
            "name": "options-agent",
            "options": {
                "maxTokens": 1000,
                "verbose": true
            }
        }"#;
        let agent: Agent = serde_json::from_str(json).unwrap();
        assert_eq!(agent.name, "options-agent");
        assert_eq!(agent.options.len(), 2);
        assert_eq!(agent.options["maxTokens"], serde_json::json!(1000));
        assert_eq!(agent.options["verbose"], serde_json::json!(true));
    }

    #[test]
    fn test_agent_extra_fields_preserved() {
        let json = r#"{
            "name": "future-agent",
            "futureField": "unknown value",
            "anotherFuture": 42
        }"#;
        let agent: Agent = serde_json::from_str(json).unwrap();
        assert_eq!(agent.name, "future-agent");
        assert_eq!(agent.extra["futureField"], "unknown value");
        assert_eq!(agent.extra["anotherFuture"], 42);
    }

    #[test]
    fn test_agent_null_boolean_fields_deserialize_as_none() {
        let json = r#"{
            "name": "opencode-1-15-7-agent",
            "builtin": null,
            "native": null,
            "hidden": null
        }"#;
        let agent: Agent = serde_json::from_str(json).unwrap();
        assert_eq!(agent.name, "opencode-1-15-7-agent");
        assert_eq!(agent.builtin, None);
        assert_eq!(agent.native, None);
        assert_eq!(agent.hidden, None);
    }

    #[test]
    fn test_agent_round_trip() {
        let agent = Agent {
            name: "test-agent".to_string(),
            description: Some("Test agent".to_string()),
            system: Some("You are a test agent".to_string()),
            tools: vec!["read".to_string(), "write".to_string()],
            builtin: Some(true),
            mode: Some(AgentMode::Primary),
            native: Some(false),
            hidden: Some(false),
            top_p: Some(0.95),
            temperature: Some(0.5),
            color: Some("#00ff00".to_string()),
            permission: None,
            model: Some(ModelRef {
                provider_id: Some("openai".to_string()),
                model_id: Some("gpt-4".to_string()),
                variant: None,
                extra: serde_json::Value::Null,
            }),
            variant: Some("turbo".to_string()),
            prompt: None,
            options: HashMap::new(),
            steps: Some(5),
            extra: serde_json::Value::Null,
        };
        let json = serde_json::to_string(&agent).unwrap();
        let parsed: Agent = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.name, agent.name);
        assert_eq!(parsed.builtin, agent.builtin);
        assert_eq!(parsed.mode, agent.mode);
        assert_eq!(parsed.native, agent.native);
        assert_eq!(parsed.hidden, agent.hidden);
        assert_eq!(parsed.top_p, agent.top_p);
    }

    // ==================== ToolIds Tests ====================

    #[test]
    fn test_tool_ids_deserialize_flat_array() {
        let json = r#"["read_file", "write_file", "bash"]"#;
        let ids: ToolIds = serde_json::from_str(json).unwrap();
        assert_eq!(ids.len(), 3);
        assert_eq!(ids.0[0], "read_file");
        assert_eq!(ids.0[1], "write_file");
        assert_eq!(ids.0[2], "bash");
    }

    #[test]
    fn test_tool_ids_deserialize_empty() {
        let json = r"[]";
        let ids: ToolIds = serde_json::from_str(json).unwrap();
        assert!(ids.is_empty());
        assert_eq!(ids.len(), 0);
    }

    #[test]
    fn test_tool_ids_into_inner() {
        let ids = ToolIds(vec!["a".to_string(), "b".to_string()]);
        let inner = ids.into_inner();
        assert_eq!(inner, vec!["a", "b"]);
    }

    #[test]
    fn test_tool_ids_as_slice() {
        let ids = ToolIds(vec!["x".to_string(), "y".to_string()]);
        assert_eq!(ids.as_slice(), &["x", "y"]);
    }

    // ==================== Tool List Tests ====================

    #[test]
    fn test_tool_deserialize() {
        let json = r#"{
            "id": "read_file",
            "description": "Read a file from the filesystem",
            "parameters": {"type": "object", "properties": {"path": {"type": "string"}}}
        }"#;
        let tool: ToolListItem = serde_json::from_str(json).unwrap();
        assert_eq!(tool.id, "read_file");
        assert_eq!(tool.description, "Read a file from the filesystem");
        assert_eq!(tool.parameters["type"], "object");
    }

    #[test]
    fn test_tool_round_trip() {
        let tool = ToolListItem {
            id: "bash".to_string(),
            description: "Execute a bash command".to_string(),
            parameters: serde_json::json!({"type": "object"}),
        };
        let json = serde_json::to_string(&tool).unwrap();
        let parsed: ToolListItem = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.id, "bash");
        assert_eq!(parsed.description, "Execute a bash command");
    }
}