### Client Instantiation and Basic Usage Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/_autodocs/api-reference/client.md Demonstrates how to instantiate the Opencode client with various configuration options and provides examples of common operations such as listing sessions, retrieving app information, performing file searches, and making custom GET requests. ```APIDOC ## Client Instantiation and Basic Usage ### Description Instantiate the Opencode client with optional configuration and perform common operations. ### Usage Example ```typescript import Opencode from '@opencode-ai/sdk'; const client = new Opencode({ baseURL: 'https://api.opencode.ai', timeout: 30000, maxRetries: 2, }); // Access session operations const sessions = await client.session.list(); // Access app information const app = await client.app.get(); // Access search functionality const files = await client.find.files({ query: '*.ts' }); // Make custom requests const response = await client.get('/some/path'); const result = await response.json(); ``` ### Configuration Options - **baseURL** (string): The base URL for API requests. Defaults to environment variable `OPENCODE_BASE_URL` or a built-in default. - **timeout** (number): The timeout in milliseconds for API requests. Defaults to 30000. - **maxRetries** (number): The maximum number of retries for failed requests. Defaults to a built-in default. ### Environment Variables - `OPENCODE_BASE_URL`: Default base URL for API requests. - `OPENCODE_LOG`: Default log level ('debug', 'info', 'warn', 'error', 'off'). ### Configuration Precedence 1. Explicit constructor options. 2. Environment variables. 3. Built-in defaults. ``` -------------------------------- ### Add and Run an Example Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/CONTRIBUTING.md Create a new TypeScript file in the examples directory and make it executable to run against your API. ```ts // add an example to examples/.ts #!/usr/bin/env -S npm run tsn -T … ``` ```sh $ chmod +x examples/.ts # run the example against your api $ yarn tsn -T examples/.ts ``` -------------------------------- ### Install Opencode SDK Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/README.md Install the Opencode SDK using npm. This is the first step to using the library in your project. ```sh npm install @opencode-ai/sdk ``` -------------------------------- ### Install Dependencies and Build Project Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/CONTRIBUTING.md Run these commands to install all necessary dependencies and build the project's output files. ```sh $ yarn $ yarn build ``` -------------------------------- ### Initialize App Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/_autodocs/api-reference/app.md Initializes the application, performing any necessary setup procedures. ```APIDOC ## POST /app/init ### Description Initializes the application, performing any necessary setup procedures. ### Method POST ### Endpoint /app/init ### Response #### Success Response (200) - **boolean** - Returns true if initialization was successful, false otherwise. ``` -------------------------------- ### Install SDK via Git Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/CONTRIBUTING.md Use this command to install the Opencode SDK JS directly from its GitHub repository using SSH. ```sh $ npm install git+ssh://git@github.com:sst/opencode-sdk-js.git ``` -------------------------------- ### Handle InternalServerError Example Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/_autodocs/errors.md Example of how to catch and handle an InternalServerError. Logs a message suggesting to try again later. ```typescript try { const result = await client.session.list(); } catch (error) { if (error instanceof Opencode.InternalServerError) { console.log('Server error - try again later'); } } ``` -------------------------------- ### Initialize the App Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/_autodocs/api-reference/app.md Initiate the application's setup process. Check the returned boolean value to confirm successful initialization. ```typescript const success = await client.app.init(); if (success) { console.log('App initialized successfully'); } ``` -------------------------------- ### get Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/_autodocs/api-reference/client.md Makes a GET request to the specified path, returning a promise-like object for the response. ```APIDOC ## get(path: string, opts?: RequestOptions): APIPromise ### Description Make a GET request to the specified path. ### Method Instance Method ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **path** (string) - Required - The request path. - **opts** (RequestOptions) - Optional - Optional request-specific options. ### Returns - **APIPromise** - Promise-like object for the response. ``` -------------------------------- ### Initialize Opencode Client and List Sessions Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/README.md Initialize the Opencode client and make a call to list sessions. This is a basic example of how to interact with the API. ```js import Opencode from '@opencode-ai/sdk'; const client = new Opencode(); const sessions = await client.session.list(); ``` -------------------------------- ### get Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/_autodocs/api-reference/app.md Retrieves the current application information, including hostname, working directory, root path, and Git status. ```APIDOC ## get ### Description Get app information. ### Method GET ### Endpoint /app ### Parameters #### Query Parameters - **options** (RequestOptions) - Optional - Request options. ### Response #### Success Response (200) - **App** - Application information object. ### Response Example ```json { "git": true, "hostname": "example.com", "path": { "cwd": "/app", "root": "/app", "state": "/app/state" } } ``` ``` -------------------------------- ### Example: Accessing Specific Config Properties Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/_autodocs/api-reference/config.md Demonstrates how to access and log specific properties from the retrieved application configuration, such as the current model and theme. ```typescript const config = await client.config.get(); console.log('Current model:', config.model); console.log('Theme:', config.theme); console.log('Username:', config.username); ``` -------------------------------- ### Make a GET Request Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/_autodocs/api-reference/client.md Execute a GET request to a specified API path. The `opts` parameter allows for request-specific configurations. ```typescript client.get('/some/path', opts?: RequestOptions) ``` -------------------------------- ### Full Session Usage Example Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/_autodocs/api-reference/session.md Demonstrates the complete lifecycle of a session: creation, sending a chat message with tools, listing messages, sharing, and deletion. ```typescript import Opencode from '@opencode-ai/sdk'; const client = new Opencode(); // Create a new session const session = await client.session.create(); console.log('Session created:', session.id); // Send a message to the session const response = await client.session.chat(session.id, { modelID: 'gpt-4', providerID: 'openai', parts: [ { type: 'text', text: 'Analyze this codebase and create documentation', } ], system: 'You are a technical documentation expert', tools: { search: true, read: true }, }); console.log('Assistant response:', response.tokens); // List messages in the session const messages = await client.session.messages(session.id); console.log('Total messages:', messages.length); // Share the session const shared = await client.session.share(session.id); console.log('Shared at:', shared.share?.url); // Clean up await client.session.delete(session.id); ``` -------------------------------- ### Handle NotFoundError Example Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/_autodocs/errors.md Example of how to catch and handle a NotFoundError when attempting to delete a session. Logs a message if the session is not found. ```typescript try { const result = await client.session.delete('nonexistent-id'); } catch (error) { if (error instanceof Opencode.NotFoundError) { console.log('Session not found'); } } ``` -------------------------------- ### Handle RateLimitError Example Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/_autodocs/errors.md Example of how to catch and handle a RateLimitError. Logs a message indicating that the client is rate-limited and should wait before retrying. ```typescript try { const result = await client.session.list(); } catch (error) { if (error instanceof Opencode.RateLimitError) { console.log('Rate limited - wait before retrying'); } } ``` -------------------------------- ### Create Session Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/_autodocs/api-reference/session.md Creates a new chat session. This is the entry point for starting a conversation. ```APIDOC ## POST /session ### Description Creates a new chat session. ### Method POST ### Endpoint /session ### Response #### Success Response (200) - **id** (string) - The unique identifier for the newly created session. ``` -------------------------------- ### Development Environment Configuration Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/_autodocs/configuration.md Example configuration for a development environment, enabling debug logging and setting a local base URL. ```typescript const client = new Opencode({ baseURL: 'http://localhost:54321', timeout: 30000, logLevel: 'debug', maxRetries: 2, }); ``` -------------------------------- ### client.session.create Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/api.md Creates a new session. This is the entry point for starting a new conversation or task within the SDK. ```APIDOC ## POST /session ### Description Creates a new session. ### Method POST ### Endpoint /session ### Response #### Success Response (200) - **session** (Session) - The created session object. ``` -------------------------------- ### client.app.get Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/api.md Retrieves application details. This method corresponds to a GET request to the /app endpoint. ```APIDOC ## GET /app ### Description Retrieves application details. ### Method GET ### Endpoint /app ### Response #### Success Response (200) - **data** (App) - The response containing application details. ``` -------------------------------- ### client.config.get Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/api.md Retrieves the configuration. This method corresponds to a GET request to the /config endpoint. ```APIDOC ## GET /config ### Description Retrieves the configuration. ### Method GET ### Endpoint /config ### Response #### Success Response (200) - **data** (Config) - The response containing the configuration. ``` -------------------------------- ### create Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/_autodocs/api-reference/session.md Creates a new conversation session. This is the entry point for starting a new chat or interaction. ```APIDOC ## create ### Description Create a new session. ### Method POST ### Endpoint /v1/sessions ### Parameters #### Query Parameters - **options** (RequestOptions) - Optional - Request options. ### Returns - **Session** - The newly created session object. ### Example ```typescript const session = await client.session.create(); ``` ``` -------------------------------- ### Production Environment Configuration Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/_autodocs/configuration.md Example configuration for a production environment, using environment variables for base URL and log level, and including a custom logger. ```typescript const client = new Opencode({ baseURL: process.env.OPENCODE_BASE_URL, timeout: 60000, logLevel: process.env.DEBUG ? 'debug' : 'warn', maxRetries: 3, logger: logger, // custom logger }); ``` -------------------------------- ### Configure Deno HTTP Client with Proxy for Fetch Options Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/_autodocs/configuration.md Set up a custom HTTP client with proxy support for Deno environments when configuring fetch options. This example configures a proxy URL. ```typescript const httpClient = Deno.createHttpClient({ proxy: { url: 'http://localhost:8888' } }); const client = new Opencode({ fetchOptions: { client: httpClient }, }); ``` -------------------------------- ### Get OpenCode Configuration Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/_autodocs/api-reference/config.md Retrieves the current OpenCode configuration. This is a foundational step for inspecting other settings. ```typescript import Opencode from '@opencode-ai/sdk'; const client = new Opencode(); const config = await client.config.get(); console.log('=== OpenCode Configuration ==='); console.log(`Model: ${config.model}`); console.log(`Small model: ${config.small_model}`); console.log(`Theme: ${config.theme}`); console.log(`Username: ${config.username}`); console.log(`Auto-update enabled: ${config.autoupdate}`); console.log(`Share setting: ${config.share}`); ``` -------------------------------- ### Opencode SDK Client Initialization and Usage Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/_autodocs/api-reference/client.md Initialize the Opencode client with custom options like baseURL, timeout, and maxRetries. Demonstrates accessing session, app, and find operations, as well as making custom GET requests. ```typescript import Opencode from '@opencode-ai/sdk'; const client = new Opencode({ baseURL: 'https://api.opencode.ai', timeout: 30000, maxRetries: 2, }); // Access session operations const sessions = await client.session.list(); // Access app information const app = await client.app.get(); // Access search functionality const files = await client.find.files({ query: '*.ts' }); // Make custom requests const response = await client.get('/some/path'); const result = await response.json(); ``` -------------------------------- ### EventIdeInstalled Interface Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/_autodocs/api-reference/event.md Defines the structure for an 'ide.installed' event, indicating that an IDE has been installed and specifying the IDE name. ```typescript interface EventIdeInstalled { type: 'ide.installed'; properties: { ide: string; }; } ``` -------------------------------- ### Get Provider Configuration Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/_autodocs/api-reference/app.md Fetches the configuration details for all available API providers and their associated models. ```APIDOC ## GET /app/providers ### Description Fetches the configuration details for all available API providers and their associated models. ### Method GET ### Endpoint /app/providers ### Response #### Success Response (200) - **AppProvidersResponse** (object) - An object containing default provider configurations and a list of available providers. - **default** (object) - Map of provider type to default provider ID. - **providers** (Array of Provider objects) - List of available providers, each with details like ID, name, environment variables, API URL, npm package name, and a map of models. ``` -------------------------------- ### Initialize Opencode Client and Access Event Resource Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/_autodocs/api-reference/event.md Instantiate the Opencode client and get a reference to the event resource. This is the first step to interacting with event streams. ```typescript const client = new Opencode(); const eventResource = client.event; ``` -------------------------------- ### Configure Bun Proxy for Fetch Options Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/_autodocs/configuration.md Specify a proxy server for Bun environments when configuring fetch options. This example sets a proxy for HTTP requests. ```typescript const client = new Opencode({ fetchOptions: { proxy: 'http://localhost:8888' } }); ``` -------------------------------- ### Get Application Configuration Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/_autodocs/api-reference/config.md Retrieves the complete application configuration object. This includes settings for models, themes, user preferences, and more. ```APIDOC ## GET /config ### Description Retrieves the complete application configuration object. This includes settings for models, themes, user preferences, and more. ### Method GET ### Endpoint /config ### Parameters #### Query Parameters - **options** (RequestOptions) - Optional - Options for the request. ### Response #### Success Response (200) - **Config** (Config) - The application configuration object. ### Response Example ```json { "model": "anthropic/claude-2", "theme": "dark", "username": "user123" } ``` ``` -------------------------------- ### EventInstallationUpdated Interface Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/_autodocs/api-reference/event.md Defines the structure for an 'installation.updated' event, indicating a change in the OpenCode installation version. ```typescript interface EventInstallationUpdated { type: 'installation.updated'; properties: { version: string; }; } ``` -------------------------------- ### Get App Information Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/_autodocs/api-reference/app.md Retrieve detailed information about the application, such as its hostname and file paths. Useful for understanding the current environment. ```typescript const app = await client.app.get(); console.log('Hostname:', app.hostname); console.log('Working directory:', app.path.cwd); console.log('Root path:', app.path.root); console.log('Git enabled:', app.git); ``` -------------------------------- ### Configure Fetch Options for Opencode Client Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/_autodocs/configuration.md Pass additional options to the underlying fetch API, such as credentials, mode, cache, or proxy configurations. This example shows browser-specific options. ```typescript const client = new Opencode({ fetchOptions: { // HTTP method, body, headers are handled by SDK // These are passed through: // Browser-only credentials: 'include', mode: 'cors', cache: 'no-cache', // Node.js-only dispatcher: proxyAgent, // Bun-specific proxy: 'http://localhost:8888', }, }); ``` -------------------------------- ### Get Complete Application Configuration Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/_autodocs/api-reference/config.md Retrieve the entire application configuration object. This is useful for inspecting current settings like the active model or theme. ```typescript const config = await client.config.get(); ``` -------------------------------- ### Initialize Client with Options Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/_autodocs/README.md Demonstrates how to instantiate the Opencode client with custom configuration options like baseURL, timeout, and logLevel. ```typescript const client = new Opencode({ baseURL: 'https://api.example.com', timeout: 30000, maxRetries: 3, logLevel: 'debug', }); ``` -------------------------------- ### Get App Information Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/_autodocs/api-reference/app.md Retrieves general information about the running application, including its hostname, working directory, data directory, configuration directory, and Git repository status. ```APIDOC ## GET /app ### Description Retrieves general information about the running application, including its hostname, working directory, data directory, configuration directory, and Git repository status. ### Method GET ### Endpoint /app ### Response #### Success Response (200) - **hostname** (string) - The hostname of the application. - **path** (object) - Object containing directory paths. - **cwd** (string) - The current working directory. - **data** (string) - The data directory path. - **config** (string) - The configuration directory path. - **git** (boolean) - Indicates if a Git repository is available. ``` -------------------------------- ### Get App Information Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/_autodocs/api-reference/app.md Fetches general information about the running application, such as its hostname, working directory, data directory, configuration directory, and Git repository status. Useful for understanding the application's environment. ```typescript import Opencode from '@opencode-ai/sdk'; const client = new Opencode(); const app = await client.app.get(); console.log(`App is running on ${app.hostname}`); console.log(`Working directory: ${app.path.cwd}`); console.log(`Data directory: ${app.path.data}`); console.log(`Config directory: ${app.path.config}`); console.log(`Git repo available: ${app.git}`); ``` -------------------------------- ### Set Shorter Request Timeout for Opencode Client Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/_autodocs/configuration.md Configure a shorter request timeout in milliseconds for the Opencode client. This example sets a 5-second timeout. ```typescript const client = new Opencode({ timeout: 5000 }); ``` -------------------------------- ### Set up Mock Server for Testing Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/CONTRIBUTING.md Before running tests, set up a mock server using Prism against your OpenAPI specification. ```sh $ npx prism mock path/to/your/openapi.yml ``` -------------------------------- ### Usage: Automated Workflow with TUI Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/_autodocs/api-reference/tui.md An example of an automated workflow that appends a prompt, waits, and optionally opens help, including error handling for API errors. ```typescript async function runAutomatedWorkflow() { const client = new Opencode(); try { // Append an initial prompt const appendSuccess = await client.tui.appendPrompt({ text: 'Analyze the codebase for potential improvements' }); if (!appendSuccess) { console.log('Could not append prompt'); return; } // Give user time to review the prompt await new Promise(resolve => setTimeout(resolve, 1000)); // Optionally open help if user needs it await client.tui.openHelp(); } catch (error) { if (error instanceof Opencode.APIError) { console.error('TUI error:', error.message); } } } ``` -------------------------------- ### init Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/_autodocs/api-reference/app.md Initializes the application. This method is used to set up the application's state and prepare it for operation. ```APIDOC ## init ### Description Initialize the app. ### Method POST ### Endpoint /app/init ### Parameters #### Query Parameters - **options** (RequestOptions) - Optional - Request options. ### Response #### Success Response (200) - **boolean** - Success indicator. ### Response Example ```json true ``` ``` -------------------------------- ### Initialize and Configure App Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/_autodocs/api-reference/app.md Initializes the application and retrieves its configuration details, including state and config directory locations. Also lists available modes and their configurations, such as temperature and tool support. ```typescript // Initialize the app const initialized = await client.app.init(); if (!initialized) { console.error('Failed to initialize app'); } // Get configuration details const app = await client.app.get(); console.log('Config location:', app.path.config); console.log('State location:', app.path.state); // List available modes for user configuration const modes = await client.app.modes(); modes.forEach(mode => { console.log(` ${mode.name}:`); console.log(` Temperature: ${mode.temperature}`); if (mode.model) { console.log(` Default model: ${mode.model.modelID}`); } console.log(` Enabled tools: ${Object.entries(mode.tools) .filter(([_, enabled]) => enabled) .map(([name]) => name) .join(', ')}`); }); ``` -------------------------------- ### Demonstrate Configuration Precedence Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/_autodocs/configuration.md Illustrates the order of precedence for configuration options: constructor option, environment variable, and built-in default. ```typescript process.env.OPENCODE_BASE_URL = 'https://env.example.com'; // Uses constructor option (highest) const client1 = new Opencode({ baseURL: 'https://constructor.example.com' }); // baseURL = https://constructor.example.com // Uses environment variable const client2 = new Opencode(); // baseURL = https://env.example.com // Uses default process.env.OPENCODE_BASE_URL = ''; const client3 = new Opencode(); // baseURL = http://localhost:54321 ``` -------------------------------- ### Basic OpenCode SDK Usage Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/_autodocs/README.md Demonstrates basic usage of the OpenCode SDK, including client initialization, session creation, and sending a chat message. ```typescript import Opencode from '@opencode-ai/sdk'; const client = new Opencode(); // Create a session const session = await client.session.create(); console.log('Session:', session.id); // Send a message const response = await client.session.chat(session.id, { modelID: 'gpt-4', providerID: 'openai', parts: [ { type: 'text', text: 'Explain this codebase', } ], }); console.log('Response:', response.tokens); ``` -------------------------------- ### client.file.status Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/api.md Retrieves the status of a file. This method corresponds to a GET request to the /file/status endpoint. ```APIDOC ## GET /file/status ### Description Retrieves the status of a file. ### Method GET ### Endpoint /file/status ### Response #### Success Response (200) - **data** (FileStatusResponse) - The response containing the file status. ``` -------------------------------- ### client.app.init Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/api.md Initializes the application. This method corresponds to a POST request to the /app/init endpoint. ```APIDOC ## POST /app/init ### Description Initializes the application. ### Method POST ### Endpoint /app/init ### Response #### Success Response (200) - **data** (AppInitResponse) - The response after application initialization. ``` -------------------------------- ### client.app.providers Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/api.md Retrieves the application providers. This method corresponds to a GET request to the /config/providers endpoint. ```APIDOC ## GET /config/providers ### Description Retrieves the application providers. ### Method GET ### Endpoint /config/providers ### Response #### Success Response (200) - **data** (AppProvidersResponse) - The response containing the application providers. ``` -------------------------------- ### client.event.list Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/api.md Retrieves a list of events. This method corresponds to a GET request to the /event endpoint. ```APIDOC ## GET /event ### Description Retrieves a list of events. ### Method GET ### Endpoint /event ### Response #### Success Response (200) - **data** (EventListResponse) - The response containing the list of events. ``` -------------------------------- ### Initialize Opencode Client and Access Config Resource Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/_autodocs/api-reference/config.md This snippet shows how to instantiate the Opencode client and access the config resource. ```typescript const client = new Opencode(); const configResource = client.config; ``` -------------------------------- ### init Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/_autodocs/api-reference/session.md Initializes a session, potentially for analyzing an application and creating an AGENTS.md file. ```APIDOC ## init ### Description Analyze the app and create an AGENTS.md file. ### Method POST ### Endpoint /v1/sessions/{id}/init ### Parameters #### Path Parameters - **id** (string) - Required - Session identifier #### Query Parameters - **options** (RequestOptions) - Optional - Request options. #### Request Body - **messageID** (string) - Required - Message identifier - **modelID** (string) - Required - Model identifier - **providerID** (string) - Required - Provider identifier ### Returns - **boolean** - Success indicator ### Example ```typescript const initialized = await client.session.init('session-id', { messageID: 'msg-123', modelID: 'gpt-4', providerID: 'openai', }); ``` ``` -------------------------------- ### client.file.read Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/api.md Reads a file. This method corresponds to a GET request to the /file endpoint and accepts parameters. ```APIDOC ## GET /file ### Description Reads a file. ### Method GET ### Endpoint /file ### Parameters #### Query Parameters - **params** ({...}) - Required - Parameters for reading the file. ``` -------------------------------- ### withOptions Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/_autodocs/api-reference/client.md Creates a new client instance with merged options, allowing for dynamic configuration adjustments. ```APIDOC ## withOptions(options: Partial): Opencode ### Description Create a new client instance with merged options. ### Method Instance Method ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **options** (Partial) - Required - Partial client options to merge with the existing instance. ### Example ```typescript const newClient = client.withOptions({ timeout: 20000, logLevel: 'debug', }); ``` ### Returns - **Opencode** - A new Opencode client instance with updated options. ``` -------------------------------- ### client.app.modes Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/api.md Retrieves the available application modes. This method corresponds to a GET request to the /mode endpoint. ```APIDOC ## GET /mode ### Description Retrieves the available application modes. ### Method GET ### Endpoint /mode ### Response #### Success Response (200) - **data** (AppModesResponse) - The response containing the list of application modes. ``` -------------------------------- ### Handle APIUserAbortError Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/_autodocs/errors.md Example of catching an APIUserAbortError. This is useful for providing user feedback when a request is cancelled. ```typescript try { const result = await client.session.list(); } catch (error) { if (error instanceof Opencode.APIUserAbortError) { console.log('Request was aborted by user'); } } ``` -------------------------------- ### Configure HTTP Client with Proxy in Deno Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/README.md Set up a proxy for Deno environments by creating a custom HTTP client with Deno.createHttpClient and passing it to the Opencode client. ```typescript import Opencode from 'npm:@opencode-ai/sdk'; const httpClient = Deno.createHttpClient({ proxy: { url: 'http://localhost:8888' } }); const client = new Opencode({ fetchOptions: { client: httpClient, }, }); ``` -------------------------------- ### client.find.text Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/api.md Finds text based on provided parameters. This method corresponds to a GET request to the /find endpoint. ```APIDOC ## GET /find ### Description Finds text based on provided parameters. ### Method GET ### Endpoint /find ### Parameters #### Query Parameters - **params** ({...}) - Required - Parameters for finding text. ``` -------------------------------- ### Initialize Opencode Client Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/_autodocs/api-reference/find.md Instantiate the Opencode client to access its resources. ```typescript const client = new Opencode(); const findResource = client.find; ``` -------------------------------- ### client.find.symbols Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/api.md Finds symbols based on provided parameters. This method corresponds to a GET request to the /find/symbol endpoint. ```APIDOC ## GET /find/symbol ### Description Finds symbols based on provided parameters. ### Method GET ### Endpoint /find/symbol ### Parameters #### Query Parameters - **params** ({...}) - Required - Parameters for finding symbols. ``` -------------------------------- ### Initialize Opencode Client and File Resource Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/_autodocs/api-reference/file.md Instantiate the Opencode client and access the file resource for subsequent operations. ```typescript const client = new Opencode(); const fileResource = client.file; ``` -------------------------------- ### client.find.files Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/api.md Finds files based on provided parameters. This method corresponds to a GET request to the /find/file endpoint. ```APIDOC ## GET /find/file ### Description Finds files based on provided parameters. ### Method GET ### Endpoint /find/file ### Parameters #### Query Parameters - **params** ({...}) - Required - Parameters for finding files. ``` -------------------------------- ### client.session.init Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/api.md Initializes a session with specific parameters. This can be used to set up the initial state or context for a session. ```APIDOC ## POST /session/{id}/init ### Description Initializes a session with specific parameters. ### Method POST ### Endpoint /session/{id}/init ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the session to initialize. #### Request Body - **params** (object) - Required - An object containing initialization parameters for the session. ### Response #### Success Response (200) - **initResponse** (SessionInitResponse) - The response indicating the session has been initialized. ``` -------------------------------- ### Initialize Opencode Client and Access App Resource Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/_autodocs/api-reference/app.md Instantiate the Opencode client and obtain a reference to the app resource for subsequent operations. ```typescript const client = new Opencode(); const appResource = client.app; ``` -------------------------------- ### ToolStateRunning Interface Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/_autodocs/api-reference/session.md Represents the running state of a tool, including start time, input, metadata, and title. ```typescript interface ToolStateRunning { status: 'running'; time: { start: number }; input?: unknown; metadata?: { [key: string]: unknown }; title?: string; } ``` -------------------------------- ### Basic Event Listening Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/_autodocs/api-reference/event.md Demonstrates how to listen to all events from the event stream and handle different event types. ```APIDOC ## Basic Event Listening This example shows how to subscribe to the event stream and process different event types like `message.updated`, `file.edited`, and `session.error`. ### Method ```typescript client.event.list() ``` ### Usage ```typescript import Opencode from '@opencode-ai/sdk'; const client = new Opencode(); async function monitorEvents() { const stream = await client.event.list(); for await (const event of stream) { if (event.type === 'message.updated') { console.log('Message updated:', event.properties.info.id); } else if (event.type === 'file.edited') { console.log('File edited:', event.properties.file); } else if (event.type === 'session.error') { console.error('Session error:', event.properties.error); } } } monitorEvents(); ``` ``` -------------------------------- ### Initialize Opencode Client Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/_autodocs/api-reference/client.md Create a new Opencode API client instance. You can use default settings or provide custom options for baseURL, timeout, retries, and logging. ```typescript import Opencode from '@opencode-ai/sdk'; // Basic initialization const client = new Opencode(); // With custom options const client = new Opencode({ baseURL: 'https://api.example.com', timeout: 30000, maxRetries: 3, logLevel: 'debug', }); ``` -------------------------------- ### Get Raw Response Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/_autodocs/README.md Shows how to retrieve the raw HTTP response object without parsing the JSON body. ```typescript const response = await client.session.list().asResponse(); ``` -------------------------------- ### Configuration with Custom Pino Logger Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/_autodocs/configuration.md Set up a custom Pino logger with 'pino-pretty' for development and integrate it with the Opencode client. ```typescript import pino from 'pino'; const logger = pino({ level: process.env.LOG_LEVEL || 'info', transport: { target: 'pino-pretty', options: { colorize: true, }, }, }); const client = new Opencode({ logger: logger.child({ module: 'opencode' }), logLevel: 'debug', }); ``` -------------------------------- ### Get Parsed Data and Raw Response Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/_autodocs/README.md Illustrates how to obtain both the parsed data and the raw HTTP response from an API call. ```typescript const { data, response } = await client.session.list().withResponse(); ``` -------------------------------- ### Find All Classes Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/_autodocs/api-reference/find.md Retrieve all symbols in the codebase and filter them to find all classes. This is useful for getting a high-level overview of object-oriented structures. ```typescript // Find all classes const allSymbols = await client.find.symbols({ query: '' }); const classes = allSymbols.filter(s => s.kind === 5); console.log('Found classes:', classes.map(c => c.name)); ``` -------------------------------- ### Link Local SDK Copy with PNPM Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/CONTRIBUTING.md Clone the repository and use pnpm to link a local copy of the SDK into your project for development. ```sh # With pnpm $ pnpm link --global $ cd ../my-package $ pnpm link -—global @opencode-ai/sdk ``` -------------------------------- ### List Available Providers and Models Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/_autodocs/api-reference/app.md Retrieve configuration details for all available providers and the models they support. This helps in understanding integration capabilities and requirements. ```typescript const config = await client.app.providers(); console.log('Default providers:', config.default); config.providers.forEach(provider => { console.log(`Provider: ${provider.name}`); console.log('Models:', Object.keys(provider.models)); console.log('Environment vars needed:', provider.env); }); ``` -------------------------------- ### Get File Status Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/_autodocs/api-reference/file.md Retrieves the status of all files in the workspace, indicating whether they have been added, modified, or deleted. This is useful for tracking changes. ```typescript const status = await client.file.status(); ``` -------------------------------- ### ClientOptions Interface Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/_autodocs/types.md Defines the configuration options for initializing the OpenCode client. Includes settings for base URL, timeouts, and fetch behavior. ```typescript interface ClientOptions { baseURL?: string; timeout?: number; fetchOptions?: MergedRequestInit; fetch?: Fetch; maxRetries?: number; defaultHeaders?: HeadersLike; defaultQuery?: Record; logLevel?: LogLevel; logger?: Logger; } ``` -------------------------------- ### Handle APIConnectionTimeoutError Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/_autodocs/errors.md Example of catching an APIConnectionTimeoutError. This snippet shows how to detect when a request has timed out, potentially after setting a custom timeout value. ```typescript try { const result = await client.session.list({ timeout: 5000, // 5 second timeout }); } catch (error) { if (error instanceof Opencode.APIConnectionTimeoutError) { console.log('Request timed out after 5 seconds'); } } ``` -------------------------------- ### Search and Read Files Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/_autodocs/README.md Demonstrates how to find files matching a query (e.g., '*.ts') and then read the content of each found file. ```typescript // Find TypeScript files const files = await client.find.files({ query: '*.ts' }); // Read each file for (const file of files) { const response = await client.file.read({ path: file }); console.log(`${file}: ${response.content.length} chars`); } ``` -------------------------------- ### Usage: Opening Help Dialog Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/_autodocs/api-reference/tui.md Shows how to open the help dialog and check the success status. ```typescript // Open the help dialog const success = await client.tui.openHelp(); if (success) { console.log('Help dialog is now open'); } else { console.log('Failed to open help dialog'); } ``` -------------------------------- ### Handle APIConnectionError with Cause Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/_autodocs/errors.md Example of catching an APIConnectionError and inspecting its underlying cause. This helps in diagnosing specific network or transport-level failures. ```typescript try { const result = await client.session.list(); } catch (error) { if (error instanceof Opencode.APIConnectionError) { console.log('Connection failed:', error.message); if (error.cause) { console.log('Underlying cause:', error.cause.message); } } } ``` -------------------------------- ### Set API Base URL and Logging Level Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/_autodocs/README.md Configures the SDK by setting environment variables for the API base URL and logging level. ```bash # Base URL for API requests export OPENCODE_BASE_URL=https://api.opencode.ai # Logging level export OPENCODE_LOG=debug ``` -------------------------------- ### Monitor Specific Event Types Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/_autodocs/README.md An example of monitoring a stream of events and reacting to specific event types like 'message.updated' or 'session.error'. ```typescript const stream = await client.event.list(); for await (const event of stream) { if (event.type === 'message.updated') { console.log('New message:', event.properties.info.id); } else if (event.type === 'session.error') { console.error('Session error:', event.properties.error); } } ``` -------------------------------- ### Create Client Variant with Merged Options Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/_autodocs/configuration.md Use the withOptions method to create a new client instance with merged options, inheriting settings from the original client. ```typescript const client = new Opencode({ baseURL: 'https://api.opencode.ai', timeout: 30000, }); // Create variant with different timeout const quickClient = client.withOptions({ timeout: 5000 }); // quickClient inherits baseURL, only timeout differs ``` -------------------------------- ### Set Request Timeout for Opencode Client Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/_autodocs/configuration.md Configure a custom request timeout in milliseconds for the Opencode client. This example sets a 30-second timeout. ```typescript const client = new Opencode({ timeout: 30000 }); ``` -------------------------------- ### Client Class Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/_autodocs/README.md The main entry point for interacting with the OpenCode SDK. It allows for configuration and provides access to various resource modules. HTTP method helpers are also available for direct requests. ```APIDOC ## Opencode Class ### Description The `Opencode` class is the primary interface for using the SDK. It handles authentication, configuration, and provides access to all SDK resources. ### Methods - **`constructor(options?: OpencodeOptions)`**: Initializes a new instance of the `Opencode` client. - **`get(path: string, options?: RequestOptions)`**: Makes an HTTP GET request. - **`post(path: string, options?: RequestOptions)`**: Makes an HTTP POST request. - **`patch(path: string, options?: RequestOptions)`**: Makes an HTTP PATCH request. - **`put(path: string, options?: RequestOptions)`**: Makes an HTTP PUT request. - **`delete(path: string, options?: RequestOptions)`**: Makes an HTTP DELETE request. - **`withOptions(options: OpencodeOptions)`**: Creates a new client instance with specific options applied. ### Parameters #### Constructor Options (`OpencodeOptions`) - **`baseURL`** (string) - Optional - The base URL for API requests. - **`apiKey`** (string) - Optional - The API key for authentication. - **`timeout`** (number) - Optional - The request timeout in milliseconds. - **`headers`** (Record) - Optional - Custom headers to include in requests. #### Request Options (`RequestOptions`) - **`params`** (Record) - Optional - Query parameters for the request. - **`data`** (any) - Optional - The request body. - **`headers`** (Record) - Optional - Custom headers for this specific request. ### Resource Access The client instance provides access to the following resources: - **`client.session`**: For conversation session management. - **`client.event`**: For real-time event streaming. - **`client.app`**: For application information and configuration. - **`client.find`**: For workspace search operations. - **`client.file`**: For file operations. - **`client.config`**: For configuration access. - **`client.tui`**: For terminal UI interaction. ``` -------------------------------- ### List Available App Modes Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/_autodocs/api-reference/app.md Fetch a list of all configured modes for the application. This is useful for understanding available operational states and their associated tools. ```typescript const modes = await client.app.modes(); modes.forEach(mode => { console.log('Mode:', mode.name); console.log('Tools:', Object.keys(mode.tools)); if (mode.model) { console.log('Model:', mode.model.modelID); } }); ``` -------------------------------- ### Create New Client with Merged Options Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/_autodocs/api-reference/client.md Generate a new client instance by merging provided options with the existing client's configuration. This is useful for creating temporary configurations without affecting the original client. ```typescript const newClient = client.withOptions({ timeout: 20000, logLevel: 'debug', }); ``` -------------------------------- ### Handle AuthenticationError Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/_autodocs/errors.md Example of catching an AuthenticationError. This is useful for prompting users to re-authenticate or check their API keys when access is denied due to invalid credentials. ```typescript try { const result = await client.session.list(); } catch (error) { if (error instanceof Opencode.AuthenticationError) { console.log('Authentication failed - check API key'); } } ``` -------------------------------- ### Configure Proxy in Bun Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/README.md Configure proxy settings for Bun environments by specifying the proxy URL directly in the fetch options. ```typescript import Opencode from '@opencode-ai/sdk'; const client = new Opencode({ fetchOptions: { proxy: 'http://localhost:8888', }, }); ``` -------------------------------- ### Initialize Session Parameters Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/_autodocs/api-reference/session.md Configure and initialize a session with specific parameters, including message, model, and provider identifiers. This is used for analyzing an app and creating an AGENTS.md file. ```typescript const initialized = await client.session.init('session-id', { messageID: 'msg-123', modelID: 'gpt-4', providerID: 'openai', }); ``` -------------------------------- ### Read and Parse package.json Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/_autodocs/api-reference/file.md Demonstrates reading a 'package.json' file and parsing its content to access project details like name and version. ```typescript import Opencode from '@opencode-ai/sdk'; const client = new Opencode(); // Read a full file const response = await client.file.read({ path: 'package.json' }); console.log('Package JSON:', response.content); // Parse the content if (response.type === 'raw') { const pkg = JSON.parse(response.content); console.log('Project name:', pkg.name); console.log('Version:', pkg.version); } ``` -------------------------------- ### Catch Specific Opencode Errors Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/_autodocs/README.md Provides an example of how to catch and handle specific error types thrown by the Opencode SDK, such as NotFoundError, AuthenticationError, and RateLimitError. ```typescript try { await client.session.list(); } catch (error) { if (error instanceof Opencode.NotFoundError) { // 404 } else if (error instanceof Opencode.AuthenticationError) { // 401 } else if (error instanceof Opencode.RateLimitError) { // 429 } else if (error instanceof Opencode.APIConnectionError) { // Network issue } else if (error instanceof Opencode.APIError) { console.log(error.status, error.message); } } ``` -------------------------------- ### Run Project Tests Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/CONTRIBUTING.md Execute the test suite for the Opencode SDK JS project. ```sh $ yarn run test ``` -------------------------------- ### Add Undocumented Request Parameter Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/README.md Use `// @ts-expect-error` to add undocumented parameters to requests. For GET requests, these go into the query; otherwise, they go into the body. ```typescript client.session.list({ // ... // @ts-expect-error baz is not yet public baz: 'undocumented option', }); ``` -------------------------------- ### Opencode Constructor Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/_autodocs/api-reference/client.md Initializes a new Opencode API client instance. It can be configured with various options to customize API communication, such as base URL, timeouts, and retry mechanisms. ```APIDOC ## new Opencode(options?: ClientOptions) ### Description Creates a new Opencode API client instance. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **options** (ClientOptions) - Optional - Configuration options for the client. - **baseURL** (string) - Optional - Override the default base URL for the API. Defaults to `process.env.OPENCODE_BASE_URL` or `http://localhost:54321`. - **timeout** (number) - Optional - Maximum time in milliseconds to wait for a response before timing out. Defaults to 60000. - **fetchOptions** (MergedRequestInit) - Optional - Additional RequestInit options to pass to fetch calls. - **fetch** (Fetch) - Optional - Custom fetch function implementation. Defaults to global fetch. - **maxRetries** (number) - Optional - Maximum number of times to retry failed requests. Defaults to 2. - **defaultHeaders** (HeadersLike) - Optional - Default headers to include with every request. - **defaultQuery** (Record) - Optional - Default query parameters for every request. - **logLevel** (LogLevel) - Optional - Log level: 'debug', 'info', 'warn', 'error', or 'off'. Defaults to 'warn'. - **logger** (Logger) - Optional - Custom logger instance for output. Defaults to globalThis.console. ### Example ```typescript import Opencode from '@opencode-ai/sdk'; // Basic initialization const client = new Opencode(); // With custom options const client = new Opencode({ baseURL: 'https://api.example.com', timeout: 30000, maxRetries: 3, logLevel: 'debug', }); ``` ``` -------------------------------- ### Access Raw Response and Parsed Data Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/README.md Use the `.withResponse()` method to get both the raw Response object and the parsed data. This method consumes the response body. ```ts const { data: sessions, response: raw } = await client.session.list().withResponse(); console.log(raw.headers.get('X-My-Header')); console.log(sessions); ``` -------------------------------- ### Configure SDK with Proxy Agent Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/_autodocs/configuration.md Use this snippet to configure the SDK to route requests through a proxy server. Ensure the proxy URL is correct. ```typescript import * as undici from 'undici'; const proxyAgent = new undici.ProxyAgent('http://proxy.company.com:8080'); const client = new Opencode({ fetchOptions: { dispatcher: proxyAgent, }, }); ``` -------------------------------- ### Find Workspace Symbols Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/_autodocs/api-reference/find.md Locate symbols such as functions, classes, and types within the workspace using the `symbols` method. This example searches for symbols named 'createSession'. ```typescript const symbols = await client.find.symbols({ query: 'createSession' }); symbols.forEach(symbol => { console.log(`${symbol.name} (kind: ${symbol.kind})`); console.log(`Location: ${symbol.location.uri}`); console.log(`Range: ${JSON.stringify(symbol.location.range)}`); }); ``` -------------------------------- ### client.tui.openHelp Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/api.md Opens the help interface within the TUI. This displays help information to the user in the terminal. ```APIDOC ## POST /tui/open-help ### Description Opens the help interface within the TUI. ### Method POST ### Endpoint /tui/open-help ### Response #### Success Response (200) - **helpResponse** (TuiOpenHelpResponse) - The response from opening the help interface. ``` -------------------------------- ### Find Configuration Files Source: https://github.com/anomalyco/opencode-sdk-js/blob/main/_autodocs/api-reference/find.md Use this snippet to find files containing specific keywords, such as configuration files. ```typescript // Find configuration files const configFiles = await client.find.files({ query: 'tsconfig' }); console.log('Config files:', configFiles); ```