### Mock Server Setup for Listing Providers Source: https://docs.rs/opencode_rs/latest/src/opencode_rs/http/providers.rs.html Sets up a mock server to test the `list_providers` functionality. It defines a GET request to '/provider' and returns a predefined JSON response. ```rust Mock::given(method("GET")) .and(path("/provider")) .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ "all": [ { "id": "anthropic", "name": "Anthropic", "env": [], "options": {}, "models": {} }, { "id": "openai", "name": "OpenAI", "env": [], "options": {}, "models": {} } ], "default": {}, "connected": [] }))) .mount(&mock_server) .await; ``` -------------------------------- ### Mock Server Setup and API Call Source: https://docs.rs/opencode_rs/latest/src/opencode_rs/http/global.rs.html Sets up a mock server to simulate an API response for a GET request to /global/health. It then creates an HTTP client and calls the health API, asserting the result. ```rust let mock_server = MockServer::start().await; Mock::given(method("GET")) .and(path("/global/health")) .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ "healthy": true, "version": "1.0.0" }))) .mount(&mock_server) .await; let client = HttpClient::new(HttpConfig { base_url: mock_server.uri(), directory: None, timeout: Duration::from_secs(30), }) .unwrap(); let api = GlobalApi::new(client); let result = api.health().await.unwrap(); assert!(result); ``` -------------------------------- ### Mock Server Setup for Find Files Test Source: https://docs.rs/opencode_rs/latest/src/opencode_rs/http/find.rs.html Sets up a mock HTTP server to test the `files` method of the Find API. It mocks a GET request to '/find/file' with a 'query' parameter and returns a JSON response. ```rust let mock_server = MockServer::start().await; Mock::given(method("GET")) .and(path("/find/file")) .and(query_param("query", "main")) .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ "files": [ {"path": "src/main.rs", "score": 1.0} ] }))) .mount(&mock_server) .await; ``` -------------------------------- ### Mock Server Setup for Find Text Test Source: https://docs.rs/opencode_rs/latest/src/opencode_rs/http/find.rs.html Sets up a mock HTTP server to test the `text` method of the Find API. It mocks a GET request to '/find' with a 'pattern' query parameter and returns a JSON response. ```rust let mock_server = MockServer::start().await; Mock::given(method("GET")) .and(path("/find")) .and(query_param("pattern", "SEARCH_TERM")) .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ "matches": [ {"file": "src/main.rs", "line": 10, "content": "// SEARCH_TERM: fix this"} ] }))) .mount(&mock_server) .await; ``` -------------------------------- ### Mock Server Setup for Find Symbols Test Source: https://docs.rs/opencode_rs/latest/src/opencode_rs/http/find.rs.html Sets up a mock HTTP server to test the `symbols` method of the Find API. It mocks a GET request to '/find/symbol' with a 'query' parameter and returns an empty JSON array for symbols. ```rust let mock_server = MockServer::start().await; Mock::given(method("GET")) .and(path("/find/symbol")) .and(query_param("query", "main")) .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ "symbols": [] }))) .mount(&mock_server) .await; ``` -------------------------------- ### Mock MCP GET Request Source: https://docs.rs/opencode_rs/latest/src/opencode_rs/http/mcp.rs.html Sets up a mock server to respond to a GET request on the /mcp path for testing purposes. ```rust Mock::given(method("GET")) .and(path("/mcp")) ``` -------------------------------- ### GET /command Source: https://docs.rs/opencode_rs/latest/src/opencode_rs/http/tools.rs.html Lists available commands that can be executed. ```APIDOC ## GET /command ### Description Lists available commands that can be executed. ### Method GET ### Endpoint /command ### Parameters None ### Request Example None ### Response #### Success Response (200) - **commands** (array[object]) - A list of command objects. #### Response Example ```json [ { "id": "run_script", "description": "Execute a script" } ] ``` ``` -------------------------------- ### Struct ToolTimeStart Source: https://docs.rs/opencode_rs/latest/opencode_rs/types/message/struct.ToolTimeStart.html Represents the start time of a tool execution. ```APIDOC ## Struct ToolTimeStart ### Description Tool execution time (start only). ### Fields - **start** (i64) - Start timestamp (ms). ### Request Example ```json { "start": 1678886400000 } ``` ### Response Example ```json { "start": 1678886400000 } ``` ``` -------------------------------- ### GET Request with Directory Header Source: https://docs.rs/opencode_rs/latest/src/opencode_rs/http/mod.rs.html Demonstrates making a GET request with a custom 'x-opencode-directory' header. The HttpClient is configured with a specific directory path. ```rust Mock::given(method("GET")) .and(path("/test")) .and(header("x-opencode-directory", "/my/project")) .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({}))) .mount(&mock_server) .await; let client = HttpClient::new(HttpConfig { base_url: mock_server.uri(), directory: Some("/my/project".to_string()), timeout: Duration::from_secs(30), }) .unwrap(); let result: serde_json::Value = client.get("/test").await.unwrap(); assert_eq!(result, serde_json::json!({})); ``` -------------------------------- ### Mock GET /permission Endpoint Source: https://docs.rs/opencode_rs/latest/src/opencode_rs/http/permissions.rs.html Sets up a mock server to respond to a GET request for /permission with a list of permission requests. Used for testing the list function. ```rust Mock::given(method("GET")) .and(path("/permission")) .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!([ { "id": "perm1", "sessionID": "s1", "permission": "file.write", "patterns": ["/home/user/file.txt"] } ]))) .mount(&mock_server) .await; ``` -------------------------------- ### GET /config Source: https://docs.rs/opencode_rs/latest/src/opencode_rs/http/config.rs.html Retrieves the current configuration settings for OpenCode. ```APIDOC ## GET /config ### Description Retrieves the current configuration settings for OpenCode. ### Method GET ### Endpoint /config ### Parameters None ### Request Example None ### Response #### Success Response (200) - **provider** (string) - The currently active configuration provider. - **model** (string) - The model configured for the active provider. #### Response Example ```json { "provider": "anthropic", "model": "claude-sonnet-4-20250514" } ``` ``` -------------------------------- ### POST Request with JSON Body Source: https://docs.rs/opencode_rs/latest/src/opencode_rs/http/mod.rs.html Example of making a POST request with a JSON body and asserting the response ID. Ensure the mock server is started and configured correctly. ```rust let body = serde_json::json!({"name": "test"}); let result: serde_json::Value = client.post("/create", &body).await.unwrap(); assert_eq!(result["id"], "new123"); ``` -------------------------------- ### McpApi Client Initialization Source: https://docs.rs/opencode_rs/latest/opencode_rs/http/mcp/struct.McpApi.html Demonstrates how to create a new instance of the McpApi client. ```APIDOC ## POST /mcp/new ### Description Create a new MCP API client. ### Method POST ### Endpoint /mcp/new ### Parameters #### Request Body - **http** (HttpClient) - Required - The HTTP client instance to be used. ### Request Example ```json { "http": "" } ``` ### Response #### Success Response (200) - **McpApi** (McpApi) - The newly created McpApi client instance. #### Response Example ```json { "client": "" } ``` ``` -------------------------------- ### Start MCP Authentication Flow Source: https://docs.rs/opencode_rs/latest/opencode_rs/http/mcp/struct.McpApi.html Initiates the MCP authentication process for a given server. ```APIDOC ## POST /mcp/{name}/auth/start ### Description Start MCP auth flow. ### Method POST ### Endpoint /mcp/{name}/auth/start ### Parameters #### Path Parameters - **name** (str) - Required - The name of the MCP server. #### Request Body - **req** (McpAuthStartRequest) - Required - The request object for starting the authentication flow. ### Request Example ```json { "req": { "client_id": "your_client_id", "redirect_uri": "http://localhost:3000/callback" } } ``` ### Response #### Success Response (200) - **McpAuthStartResponse** (McpAuthStartResponse) - The response containing details to start the authentication flow. #### Response Example ```json { "authorization_url": "https://mcp.example.com/auth?client_id=..." } ``` ### Errors Returns an error if the request fails. ``` -------------------------------- ### Get Config API Source: https://docs.rs/opencode_rs/latest/opencode_rs/client/struct.Client.html Retrieves the API client for configuration settings. ```rust pub fn config(&self) -> ConfigApi ``` -------------------------------- ### SkillsApi Client Initialization Source: https://docs.rs/opencode_rs/latest/opencode_rs/http/skills/struct.SkillsApi.html Demonstrates how to create a new instance of the SkillsApi client. ```APIDOC ## POST /api/skills/new ### Description Create a new Skills API client. ### Method POST ### Endpoint /api/skills/new ### Parameters #### Request Body - **http** (HttpClient) - Required - The HTTP client instance to use for requests. ### Request Example ```json { "http": "" } ``` ### Response #### Success Response (200) - **SkillsApi** (SkillsApi) - A new instance of the SkillsApi client. #### Response Example ```json { "client": "" } ``` ``` -------------------------------- ### PartsApi Client Initialization Source: https://docs.rs/opencode_rs/latest/opencode_rs/http/parts/struct.PartsApi.html Demonstrates how to create a new instance of the PartsApi client. ```APIDOC ## PartsApi::new ### Description Create a new Parts API client. ### Method `new` ### Parameters - **http** (`HttpClient`) - Description not provided ``` -------------------------------- ### SnapshotsApi Client Initialization Source: https://docs.rs/opencode_rs/latest/opencode_rs/http/snapshots/struct.SnapshotsApi.html Demonstrates how to create a new instance of the SnapshotsApi client. ```APIDOC ## POST /api/snapshots/new ### Description Creates a new Snapshots API client. ### Method POST ### Endpoint /api/snapshots/new ### Parameters #### Request Body - **http** (HttpClient) - Required - An instance of HttpClient to be used for API requests. ### Response #### Success Response (200) - **SnapshotsApi** (SnapshotsApi) - A new instance of the SnapshotsApi client. ### Request Example ```json { "http": "" } ``` ### Response Example ```json { "client": "" } ``` ``` -------------------------------- ### GET /experimental/tool Source: https://docs.rs/opencode_rs/latest/src/opencode_rs/http/tools.rs.html Lists all experimental tools available in the system. Each tool includes its ID, description, and parameters. ```APIDOC ## GET /experimental/tool ### Description Lists all experimental tools available in the system. ### Method GET ### Endpoint /experimental/tool ### Parameters None ### Request Example None ### Response #### Success Response (200) - **tools** (array[object]) - A list of tool objects, each containing: - **id** (string) - The unique identifier for the tool. - **description** (string) - A brief description of the tool's functionality. - **parameters** (object) - The schema defining the parameters the tool accepts. #### Response Example ```json [ { "id": "read_file", "description": "Read contents of a file", "parameters": { "type": "object", "properties": { "path": { "type": "string" } } } } ] ``` ``` -------------------------------- ### HttpClient Initialization Source: https://docs.rs/opencode_rs/latest/src/opencode_rs/http/mod.rs.html Demonstrates how to create a new HttpClient instance with custom configuration, including base URL and timeout. ```APIDOC ## HttpClient::new ### Description Creates a new HTTP client with the given configuration. ### Method `pub fn new(cfg: HttpConfig) -> Result` ### Parameters - **cfg** (`HttpConfig`) - Required - The configuration for the HTTP client. ### Request Body (Not applicable for this method) ### Response #### Success Response (200) - **Self** (`HttpClient`) - A new instance of the HTTP client. ### Errors - Returns an error if the HTTP client cannot be built. ## HttpClient::from_parts ### Description Creates an HTTP client from a base URL, an optional directory, and an optional existing `reqwest::Client`. ### Method `pub fn from_parts(base_url: &url::Url, directory: Option, http: Option) -> Result` ### Parameters - **base_url** (`&url::Url`) - Required - The base URL for the OpenCode server. - **directory** (`Option`) - Optional - The directory context header. - **http** (`Option`) - Optional - An existing `reqwest::Client` to use. ### Response #### Success Response (200) - **Self** (`HttpClient`) - A new instance of the HTTP client. ### Errors - Returns an error if the HTTP client cannot be built. ``` -------------------------------- ### Initialize ClientBuilder with Default Settings Source: https://docs.rs/opencode_rs/latest/src/opencode_rs/client.rs.html Creates a new `ClientBuilder` with default configurations for base URL, directory, and timeout. Use this as a starting point for building a client. ```rust impl Default for ClientBuilder { fn default() -> Self { Self { base_url: "http://127.0.0.1:4096".to_string(), directory: 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() } // ... other methods } ``` -------------------------------- ### Test Getting a Specific Skill Source: https://docs.rs/opencode_rs/latest/src/opencode_rs/http/skills.rs.html Tests the `get` method of the SkillsApi by mocking a GET request to the /skill/get endpoint with a query parameter and asserting the response. ```rust use super::*; use crate::http::HttpConfig; use std::time::Duration; use wiremock::Mock; use wiremock::MockServer; use wiremock::ResponseTemplate; use wiremock::matchers::method; use wiremock::matchers::path; use wiremock::matchers::query_param; #[tokio::test] async fn test_get_skill() { let mock_server = MockServer::start().await; Mock::given(method("GET")) .and(path("/skill/get")) .and(query_param("name", "code-review")) .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ "name": "code-review", "description": "Review code for issues", "content": "Please review the following code...", "builtin": true }))) .mount(&mock_server) .await; let client = HttpClient::new(HttpConfig { base_url: mock_server.uri(), directory: None, timeout: Duration::from_secs(30), }) .unwrap(); let api = SkillsApi::new(client); let skill = api.get("code-review").await.unwrap(); assert_eq!(skill.name, "code-review"); assert!(skill.content.is_some()); } ``` -------------------------------- ### Get Resource API (Experimental) Source: https://docs.rs/opencode_rs/latest/opencode_rs/client/struct.Client.html Retrieves the experimental API client for resource management. ```rust pub fn resource(&self) -> ResourceApi ``` -------------------------------- ### GET /api Source: https://docs.rs/opencode_rs/latest/src/opencode_rs/http/mod.rs.html Sends a GET request to the specified path. This is a basic GET request without specific retry logic mentioned in this snippet, but it's part of the client's functionality. ```APIDOC ## GET /api ### Description Sends a GET request to the specified path. ### Method GET ### Endpoint /api ### Parameters #### Query Parameters - **path** (string) - Required - The API endpoint path. ### Response #### Success Response (200) - **T** (object) - The deserialized JSON response body. #### Response Example ```json { "id": "test123", "value": 42 } ``` ``` -------------------------------- ### Mock Server Setup for Files API Tests Source: https://docs.rs/opencode_rs/latest/src/opencode_rs/http/files.rs.html Sets up a mock server using `wiremock` to simulate HTTP responses for Files API endpoints during testing. ```rust use wiremock::Mock; use wiremock::MockServer; use wiremock::ResponseTemplate; use wiremock::matchers::method; use wiremock::matchers::path; use wiremock::matchers::query_param; #[tokio::test] async fn test_list_files_success() { let mock_server = MockServer::start().await; Mock::given(method("GET")) .and(path("/file")) .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!([ {"path": "src/main.rs", "type": "file"}, {"path": "src/lib.rs", "type": "file"} ]))) .mount(&mock_server) .await; let http = HttpClient::new(HttpConfig { base_url: mock_server.uri(), directory: None, timeout: Duration::from_secs(30), }) .unwrap(); let files = FilesApi::new(http); let result = files.list().await; assert!(result.is_ok()); let file_list = result.unwrap(); assert_eq!(file_list.len(), 2); } ``` ```rust #[tokio::test] async fn test_read_file_success() { let mock_server = MockServer::start().await; // Use a simple filename without slashes to avoid URL encoding issues Mock::given(method("GET")) .and(path("/file/content")) .and(query_param("path", "main.rs")) .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ "path": "main.rs", "content": "fn main() {}" }))) .mount(&mock_server) .await; let http = HttpClient::new(HttpConfig { base_url: mock_server.uri(), directory: None, timeout: Duration::from_secs(30), }) .unwrap(); let files = FilesApi::new(http); let result = files.read("main.rs").await; assert!(result.is_ok()); } ``` ```rust #[tokio::test] async fn test_status_files_success() { let mock_server = MockServer::start().await; Mock::given(method("GET")) .and(path("/file/status")) .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!([ {"path": "src/main.rs", "status": "modified"}, {"path": "new_file.rs", "status": "untracked"} ]))) .mount(&mock_server) .await; let http = HttpClient::new(HttpConfig { base_url: mock_server.uri(), directory: None, timeout: Duration::from_secs(30), }) .unwrap(); let files = FilesApi::new(http); let result = files.status().await; assert!(result.is_ok()); } ``` ```rust #[tokio::test] async fn test_read_file_not_found() { let mock_server = MockServer::start().await; // Use wiremock's any() matcher for the query param since path encoding may vary Mock::given(method("GET")) .and(path("/file/content")) .respond_with(ResponseTemplate::new(404).set_body_json(serde_json::json!({ "name": "NotFound", ``` -------------------------------- ### Create New Client Builder Source: https://docs.rs/opencode_rs/latest/opencode_rs/client/struct.Client.html Initializes a new client builder to configure and create a client instance. ```rust pub fn builder() -> ClientBuilder ``` -------------------------------- ### GET /global/health Source: https://docs.rs/opencode_rs/latest/src/opencode_rs/http/global.rs.html Performs a quick GET request to verify connectivity of the global endpoint. ```APIDOC ## GET /global/health ### Description Checks if the global endpoint is available by performing a quick GET request to verify connectivity. Returns `true` if the server is reachable and healthy, otherwise an error is returned. ### Method GET ### Endpoint /global/health ### Parameters None ### Request Body None ### Response #### Success Response (200) - **healthy** (boolean) - Indicates if the global endpoint is healthy. #### Response Example ```json { "healthy": true } ``` ``` -------------------------------- ### Create a new ClientBuilder Source: https://docs.rs/opencode_rs/latest/opencode_rs/client/struct.ClientBuilder.html Initializes a new ClientBuilder with default settings for base URL and timeout. Use this as a starting point for configuring a client. ```rust pub fn new() -> Self ``` -------------------------------- ### HttpClient GET Request Source: https://docs.rs/opencode_rs/latest/src/opencode_rs/http/mod.rs.html Shows how to perform a GET request to a specified path and deserialize the JSON response. ```APIDOC ## HttpClient::get ### Description Performs a GET request to the specified path and returns the deserialized JSON response. ### Method `pub async fn get(&self, path: &str) -> Result` ### Parameters - **path** (`&str`) - Required - The path to the resource. ### Request Body (Not applicable for GET requests) ### Response #### Success Response (200) - **T** (`DeserializeOwned`) - The deserialized JSON response. ### Errors - Returns an error if the request fails or the response cannot be deserialized. ``` -------------------------------- ### ProjectApi::git_init Source: https://docs.rs/opencode_rs/latest/opencode_rs/http/project/struct.ProjectApi.html Initializes a git repository in the project directory. ```APIDOC ## `ProjectApi::git_init` ### Description Initialize a git repository in the project directory. ### Method `git_init` ### Parameters - **req** (`&GitInitRequest`) - Required - The git initialization request body. ### Returns - `Result` - A Result containing the GitInitResponse on success, or an error if git initialization fails. ``` -------------------------------- ### Get Specific Skill Source: https://docs.rs/opencode_rs/latest/src/opencode_rs/http/skills.rs.html Retrieves details for a specific skill by its name. Use this to get the full information about a particular skill template. ```APIDOC ## GET /skill/get ### Description Gets a specific skill by name. ### Method GET ### Endpoint /skill/get ### Parameters #### Query Parameters - **name** (string) - Required - The name of the skill to retrieve. ### Request Example None ### Response #### Success Response (200) - **name** (string) - The name of the skill. - **description** (string) - A brief description of the skill. - **content** (string) - The content or prompt of the skill. - **builtin** (boolean) - Indicates if the skill is built-in. #### Response Example ```json { "name": "code-review", "description": "Review code for issues", "content": "Please review the following code...", "builtin": true } ``` ``` -------------------------------- ### Initialize Question API Client Source: https://docs.rs/opencode_rs/latest/src/opencode_rs/http/question.rs.html Creates a new instance of the Question API client. Requires an initialized HttpClient. ```rust pub struct QuestionApi { http: HttpClient, } impl QuestionApi { /// Create a new Question API client. pub fn new(http: HttpClient) -> Self { Self { http } } } ``` -------------------------------- ### Test GET Resource in Rust Source: https://docs.rs/opencode_rs/latest/src/opencode_rs/http/resource.rs.html Tests the `get` method of the `ResourceApi` by mocking an HTTP server response. Verifies that resource information is correctly retrieved and parsed. ```rust use super::*; use crate::http::HttpConfig; use std::time::Duration; use wiremock::Mock; use wiremock::MockServer; use wiremock::ResponseTemplate; use wiremock::matchers::method; use wiremock::matchers::path; use wiremock::matchers::query_param; #[tokio::test] async fn test_get_resource() { let mock_server = MockServer::start().await; Mock::given(method("GET")) .and(path("/experimental/resource")) .and(query_param("uri", "file:///path/to/file.txt")) .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ "uri": "file:///path/to/file.txt", "name": "file.txt", "content": "Hello, world!", "mimeType": "text/plain" }))) .mount(&mock_server) .await; let client = HttpClient::new(HttpConfig { base_url: mock_server.uri(), directory: None, timeout: Duration::from_secs(30), }) .unwrap(); let api = ResourceApi::new(client); let resource = api.get("file:///path/to/file.txt").await.unwrap(); assert_eq!(resource.uri, Some("file:///path/to/file.txt".to_string())); assert_eq!(resource.name, Some("file.txt".to_string())); assert_eq!(resource.content, Some("Hello, world!".to_string())); assert_eq!(resource.mime_type, Some("text/plain".to_string())); } ``` -------------------------------- ### Mock Server Setup for Snapshot Track Test Source: https://docs.rs/opencode_rs/latest/src/opencode_rs/http/snapshots.rs.html Sets up a mock server to simulate the `/snapshot/track` API endpoint for testing purposes. It defines the expected request method and path, and provides a JSON response. ```rust Mock::given(method("POST")) .and(path("/snapshot/track")) .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ "tracked": 3 }))) .mount(&mock_server) .await; ``` -------------------------------- ### Configure and Use HTTP Client with Find API Source: https://docs.rs/opencode_rs/latest/src/opencode_rs/http/find.rs.html Instantiates an HTTP client with a mock server URI and a timeout, then uses it to create a Find API client. Demonstrates making a text search and asserting a successful result. ```rust let http = HttpClient::new(HttpConfig { base_url: mock_server.uri(), directory: None, timeout: Duration::from_secs(30), }) .unwrap(); let find = FindApi::new(http); let result = find.text("nonexistent").await; assert!(result.is_ok()); ``` -------------------------------- ### Perform GET Request and Deserialize JSON Source: https://docs.rs/opencode_rs/latest/src/opencode_rs/http/mod.rs.html Performs a GET request to the specified path and deserializes the JSON response. Returns an error if the request fails or the response cannot be deserialized. ```rust pub async fn get(&self, path: &str) -> Result { let resp = self .build_request(Method::GET, path) .send() .await .map_err(|e| OpencodeError::Network(e.to_string()))?; Self::map_json_response(resp).await } ``` -------------------------------- ### Revert Snapshot Source: https://docs.rs/opencode_rs/latest/src/opencode_rs/http/snapshots.rs.html Revert changes in a snapshot. This example sets up a mock server for the revert operation. ```rust let mock_server = MockServer::start().await; Mock::given(method("POST")) .and(path("/snapshot/revert")) .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ ``` -------------------------------- ### Create New HttpClient Source: https://docs.rs/opencode_rs/latest/opencode_rs/http/struct.HttpClient.html Initializes a new HTTP client with provided configuration. Errors may occur if the client cannot be built. ```rust pub fn new(cfg: HttpConfig) -> Result ``` -------------------------------- ### Mock GET Request Test Source: https://docs.rs/opencode_rs/latest/src/opencode_rs/http/mod.rs.html Tests a successful GET request using wiremock to mock the server response. Asserts that the deserialized JSON response matches the expected values. ```rust #[tokio::test] async fn test_get_success() { let mock_server = MockServer::start().await; Mock::given(method("GET")) .and(path("/test")) .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ "id": "test123", "value": 42 }))) .mount(&mock_server) .await; let client = HttpClient::new(HttpConfig { base_url: mock_server.uri(), directory: None, timeout: Duration::from_secs(30), }) .unwrap(); let result: serde_json::Value = client.get("/test").await.unwrap(); assert_eq!(result["id"], "test123"); assert_eq!(result["value"], 42); } ``` -------------------------------- ### Test Getting Current Project Source: https://docs.rs/opencode_rs/latest/src/opencode_rs/http/project.rs.html Tests the successful retrieval of the current project using the Project API client. It mocks the HTTP GET request to '/project/current' and asserts the response. ```rust #[tokio::test] async fn test_current_project_success() { let mock_server = MockServer::start().await; Mock::given(method("GET")) .and(path("/project/current")) .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ "id": "current-proj", "name": "Current Project" }))) .mount(&mock_server) .await; let http = HttpClient::new(HttpConfig { base_url: mock_server.uri(), directory: None, timeout: Duration::from_secs(30), }) .unwrap(); let project = ProjectApi::new(http); let result = project.current().await; assert!(result.is_ok()); } ``` -------------------------------- ### Create Client Builder Instance Source: https://docs.rs/opencode_rs/latest/src/opencode_rs/client.rs.html Provides a convenient way to obtain a `ClientBuilder` instance, starting with default configuration values. ```rust impl Client { /// Create a new client builder. pub fn builder() -> ClientBuilder { ClientBuilder::new() } // ... other methods } ``` -------------------------------- ### POST /session/{id}/init Source: https://docs.rs/opencode_rs/latest/src/opencode_rs/http/sessions.rs.html Initializes a session, typically setting it up for the first time or preparing it for use. ```APIDOC ## POST /session/{id}/init ### Description Initialize a session. ### Method POST ### Endpoint /session/{id}/init ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the session to initialize. ### Request Example ```json { "initial_state": "starting point" } ``` ### Response #### Success Response (200) - **session** (Session) - The initialized Session object. #### Response Example ```json { "id": "session_id_1", "status": "initialized", "created_at": "2023-10-27T12:00:00Z" } ``` ``` -------------------------------- ### Perform GET Request Source: https://docs.rs/opencode_rs/latest/opencode_rs/http/struct.HttpClient.html Executes a GET request to the specified path and deserializes the JSON response into the provided type T. Errors occur if the request fails or deserialization fails. ```rust pub async fn get(&self, path: &str) -> Result ``` -------------------------------- ### Mock Empty GET /permission Endpoint Source: https://docs.rs/opencode_rs/latest/src/opencode_rs/http/permissions.rs.html Configures a mock server to return an empty JSON array for GET requests to /permission. Useful for testing scenarios where no permission requests are pending. ```rust Mock::given(method("GET")) .and(path("/permission")) .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!([]))) .mount(&mock_server) .await; ``` -------------------------------- ### Create FilesApi Client Source: https://docs.rs/opencode_rs/latest/opencode_rs/http/files/struct.FilesApi.html Instantiates a new FilesApi client. Requires an initialized HttpClient. ```rust pub fn new(http: HttpClient) -> Self ``` -------------------------------- ### Initialize Git Repository Source: https://docs.rs/opencode_rs/latest/opencode_rs/http/project/struct.ProjectApi.html Initializes a new Git repository within a project directory. Requires a GitInitRequest and returns a GitInitResponse on success or an error if initialization fails. ```rust pub async fn git_init(&self, req: &GitInitRequest) -> Result ``` -------------------------------- ### VecDeque to Vec Conversion Source: https://docs.rs/opencode_rs/latest/opencode_rs/types/permission/type.Ruleset.html Demonstrates converting a `VecDeque` to a `Vec`. The first example shows an O(1) conversion where the pointer remains the same. The second example shows a case requiring data rearrangement. ```rust use std::collections::VecDeque; // This one is *O*(1). let deque: VecDeque<_> = (1..5).collect(); let ptr = deque.as_slices().0.as_ptr(); let vec = Vec::from(deque); assert_eq!(vec, [1, 2, 3, 4]); assert_eq!(vec.as_ptr(), ptr); // This one needs data rearranging. let mut deque: VecDeque<_> = (1..5).collect(); deque.push_front(9); deque.push_front(8); let ptr = deque.as_slices().1.as_ptr(); let vec = Vec::from(deque); assert_eq!(vec, [8, 9, 1, 2, 3, 4]); assert_eq!(vec.as_ptr(), ptr); ``` -------------------------------- ### Create Session using Rust Source: https://docs.rs/opencode_rs/latest/src/opencode_rs/http/sessions.rs.html Demonstrates creating a new session using the SessionsApi. Requires an initialized HttpClient. ```rust #[tokio::test] async fn test_create_session() { let mock_server = MockServer::start().await; Mock::given(method("POST")) .and(path("/session")) .and(body_json(serde_json::json!({}))) .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ "id": "session123", "slug": "session123", "projectId": "proj1", "directory": "/path", "title": "New Session", "version": "1.0", "time": {"created": 1_234_567_890, "updated": 1_234_567_890} }))) .mount(&mock_server) .await; let http = HttpClient::new(HttpConfig { base_url: mock_server.uri(), directory: None, timeout: Duration::from_secs(30), }) .unwrap(); let sessions = SessionsApi::new(http); let session = sessions .create(&CreateSessionRequest::default()) .await .unwrap(); assert_eq!(session.id, "session123"); } ``` -------------------------------- ### Get OpenAPI Spec Source: https://docs.rs/opencode_rs/latest/opencode_rs/http/misc/struct.MiscApi.html Retrieves the OpenAPI specification. ```APIDOC ## GET /api/misc/doc ### Description Get `OpenAPI` spec. ### Method GET ### Endpoint /api/misc/doc ### Response #### Success Response (200) - **OpenApiDoc** (object) - The OpenAPI specification document. #### Errors - Returns an error if the request fails. ### Response Example ```json { "openapi": "3.0.0", "info": { "title": "Misc API", "version": "1.0.0" }, "paths": {} } ``` ``` -------------------------------- ### Create HTTP Client from Parts Source: https://docs.rs/opencode_rs/latest/src/opencode_rs/http/mod.rs.html Creates an HTTP client from a base URL, directory, and an optional existing client. Returns an error if the HTTP client cannot be built. ```rust pub fn from_parts( base_url: &url::Url, directory: Option, http: Option, ) -> Result { let timeout = Duration::from_secs(1800); let inner = match http { Some(client) => client, None => ReqClient::builder() .timeout(timeout) .build() .map_err(|e| OpencodeError::Network(e.to_string()))?, }; Ok(Self { inner, cfg: HttpConfig { base_url: base_url.to_string().trim_end_matches('/').to_string(), directory: directory.map(|p| p.to_string_lossy().to_string()), timeout, }, }) } ``` -------------------------------- ### Get Message Role Source: https://docs.rs/opencode_rs/latest/opencode_rs/types/message/struct.Message.html Retrieves the role assigned to the message. ```rust pub fn role(&self) -> &str ``` -------------------------------- ### List Sessions using Rust Source: https://docs.rs/opencode_rs/latest/src/opencode_rs/http/sessions.rs.html Demonstrates listing all available sessions. This function does not require any parameters. ```rust #[tokio::test] async fn test_list_sessions() { let mock_server = MockServer::start().await; Mock::given(method("GET")) .and(path("/session")) .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!([ {"id": "s1", "slug": "s1", "projectId": "p1", "directory": "/path", "title": "S1", "version": "1.0", "time": {"created": 1_234_567_890, "updated": 1_234_567_890}}, {"id": "s2", "slug": "s2", "projectId": "p1", "directory": "/path", "title": "S2", "version": "1.0", "time": {"created": 1_234_567_890, "updated": 1_234_567_890}} ]))) .mount(&mock_server) .await; let http = HttpClient::new(HttpConfig { base_url: mock_server.uri(), directory: None, timeout: Duration::from_secs(30), }) .unwrap(); let sessions = SessionsApi::new(http); let list = sessions.list().await.unwrap(); assert_eq!(list.len(), 2); } ``` -------------------------------- ### Get Message ID Source: https://docs.rs/opencode_rs/latest/opencode_rs/types/message/struct.Message.html Retrieves the unique identifier for the message. ```rust pub fn id(&self) -> &str ``` -------------------------------- ### MiscApi Constructor Source: https://docs.rs/opencode_rs/latest/opencode_rs/http/misc/struct.MiscApi.html Initializes a new instance of the MiscApi client. ```APIDOC ## POST /api/misc/new ### Description Create a new Misc API client. ### Method POST ### Endpoint /api/misc/new ### Parameters #### Request Body - **http** (HttpClient) - Required - The HTTP client instance to use. ### Response #### Success Response (200) - **MiscApi** (object) - The newly created MiscApi client instance. ### Request Example ```json { "http": "HttpClientInstance" } ``` ### Response Example ```json { "client_id": "generated_client_id" } ``` ``` -------------------------------- ### Get Skill Directories Source: https://docs.rs/opencode_rs/latest/opencode_rs/http/skills/struct.SkillsApi.html Retrieves information about skill directories. ```APIDOC ## GET /api/skills/dirs ### Description Get skill directories. ### Method GET ### Endpoint /api/skills/dirs ### Response #### Success Response (200) - **directories** (SkillDirs) - Information about skill directories. #### Response Example ```json { "directories": [ "/path/to/skill/dir1", "/path/to/skill/dir2" ] } ``` ### Errors Returns an error if the request fails. ``` -------------------------------- ### Initialize HTTP Client Source: https://docs.rs/opencode_rs/latest/src/opencode_rs/http/permissions.rs.html Creates a new HTTP client instance configured with the base URL of the mock server and a timeout. Ensure the base URL is correctly set to the mock server's URI. ```rust let http = HttpClient::new(HttpConfig { base_url: mock_server.uri(), directory: None, timeout: Duration::from_secs(30), }) .unwrap(); ``` -------------------------------- ### Get Global Health Source: https://docs.rs/opencode_rs/latest/opencode_rs/http/misc/struct.MiscApi.html Retrieves the global health status. ```APIDOC ## GET /api/misc/health ### Description Get global health. ### Method GET ### Endpoint /api/misc/health ### Response #### Success Response (200) - **HealthInfo** (object) - An object containing global health information. #### Errors - Returns an error if the request fails. ### Response Example ```json { "status": "ok", "checks": { "database": "healthy", "network": "healthy" } } ``` ``` -------------------------------- ### Get Formatter Status Source: https://docs.rs/opencode_rs/latest/opencode_rs/http/misc/struct.MiscApi.html Retrieves the status of all configured formatters. ```APIDOC ## GET /api/misc/formatter ### Description Get formatter status for all configured formatters. ### Method GET ### Endpoint /api/misc/formatter ### Response #### Success Response (200) - **formatters** (array) - A list of FormatterInfo objects. #### Errors - Returns an error if the request fails. ### Response Example ```json [ { "name": "rustfmt", "status": "enabled", "version": "1.0.0" } ] ``` ``` -------------------------------- ### Get Path Info Source: https://docs.rs/opencode_rs/latest/opencode_rs/http/misc/struct.MiscApi.html Retrieves information about the current path. ```APIDOC ## GET /api/misc/path ### Description Get current path info. ### Method GET ### Endpoint /api/misc/path ### Response #### Success Response (200) - **PathInfo** (object) - An object containing path information. #### Errors - Returns an error if the request fails. ### Response Example ```json { "current_path": "/usr/local/bin", "base_path": "/usr/local" } ``` ``` -------------------------------- ### ProjectApi::new Source: https://docs.rs/opencode_rs/latest/opencode_rs/http/project/struct.ProjectApi.html Creates a new Project API client. ```APIDOC ## `ProjectApi::new` ### Description Create a new Project API client. ### Method `new` ### Parameters - **http** (`HttpClient`) - Description: An instance of HttpClient. ### Returns - `Self` - A new instance of ProjectApi. ``` -------------------------------- ### Struct McpAuthStartRequest Source: https://docs.rs/opencode_rs/latest/opencode_rs/types/mcp/struct.McpAuthStartRequest.html Represents an MCP authentication start request. ```APIDOC ## Struct McpAuthStartRequest ### Description MCP auth start request. ### Fields - **callback_url** (Option) - Optional - Callback URL for OAuth flow. ### Request Example ```json { "callback_url": "https://example.com/callback" } ``` ### Response Example ```json { "callback_url": "https://example.com/callback" } ``` ``` -------------------------------- ### Create HttpClient From Parts Source: https://docs.rs/opencode_rs/latest/opencode_rs/http/struct.HttpClient.html Constructs an HTTP client using a base URL, an optional directory, and an existing HTTP client. Returns an error if construction fails. ```rust pub fn from_parts( base_url: &Url, directory: Option, http: Option, ) -> Result ``` -------------------------------- ### Initialize Files API Client Source: https://docs.rs/opencode_rs/latest/src/opencode_rs/http/files.rs.html Creates a new instance of the Files API client. Requires an initialized `HttpClient`. ```rust pub struct FilesApi { http: HttpClient, } impl FilesApi { /// Create a new Files API client. pub fn new(http: HttpClient) -> Self { Self { http } } // ... other methods ``` -------------------------------- ### Get Length of Vec Source: https://docs.rs/opencode_rs/latest/opencode_rs/types/permission/type.Ruleset.html Returns the number of elements currently in the vector. ```rust let a = vec![1, 2, 3]; assert_eq!(a.len(), 3); ``` -------------------------------- ### List Files in Project Source: https://docs.rs/opencode_rs/latest/src/opencode_rs/http/files.rs.html Fetches a list of all files within the project. Returns a `Vec` on success. ```rust /// List files in the project. /// /// # Errors /// /// Returns an error if the request fails. pub async fn list(&self) -> Result> { self.http.request_json(Method::GET, "/file", None).await } ``` -------------------------------- ### GET /session/{id} Source: https://docs.rs/opencode_rs/latest/src/opencode_rs/http/sessions.rs.html Retrieves details for a specific session by its ID. ```APIDOC ## GET /session/{id} ### Description Retrieves the details of a specific session. ### Method GET ### Endpoint /session/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the session. ### Response #### Success Response (200) - **Session** (object) - An object containing the session details. #### Response Example { "id": "abc123", "slug": "abc123", "projectId": "p1", "directory": "/path", "title": "Test Session", "version": "1.0", "time": { "created": 1234567890, "updated": 1234567890 } } ``` -------------------------------- ### Get Session Status API Source: https://docs.rs/opencode_rs/latest/src/opencode_rs/types/session.rs.html Retrieves the current status of sessions. ```APIDOC ## GET /session/status ### Description Retrieves the status of the current session and whether any session is busy. ### Method GET ### Endpoint /session/status ### Response #### Success Response (200) - **active_session_id** (Option) - The ID of the currently active session, if any. - **busy** (bool) - Indicates whether any session is currently busy processing work. #### Response Example ```json { "active_session_id": "session_123", "busy": false } ``` ``` -------------------------------- ### API Client Initialization and Request Source: https://docs.rs/opencode_rs/latest/src/opencode_rs/http/providers.rs.html Initializes a ProvidersApi client using the configured HTTP client and makes an oauth_authorize request. Asserts that the result is an error and specifically a 'not found' error. ```rust let providers = ProvidersApi::new(http); let result = providers.oauth_authorize("unknown").await; assert!(result.is_err()); assert!(result.unwrap_err().is_not_found()); ``` -------------------------------- ### GET /experimental/worktree Source: https://docs.rs/opencode_rs/latest/src/opencode_rs/http/worktree.rs.html Lists all existing Git worktrees. This is an experimental endpoint. ```APIDOC ## GET /experimental/worktree ### Description Lists all existing Git worktrees. This is an experimental endpoint. ### Method GET ### Endpoint /experimental/worktree ### Response #### Success Response (200 OK) - **Array of Worktree objects** - Each object contains: - **path** (string) - The path of the worktree. - **branch** (string) - The branch associated with the worktree. - **is_main** (boolean) - Indicates if this is the main worktree. #### Response Example ```json [ { "path": "/path/to/main/worktree", "branch": "main", "is_main": true }, { "path": "/path/to/feature/worktree", "branch": "feature-branch", "is_main": false } ] ``` ``` -------------------------------- ### Run Simple Text Prompt Source: https://docs.rs/opencode_rs/latest/opencode_rs/client/struct.Client.html Creates a session and sends a text prompt. The AI response is received asynchronously via SSE events. Use `subscribe_session` to get the response. Returns an error if session creation or prompt fails. ```rust pub async fn run_simple_text(&self, text: impl Into) -> Result ```