Extensibility: JavaScript/TypeScript SDK
Relevant source files
The following files were used as context for generating this wiki page:The OpenCode JavaScript/TypeScript SDK provides a client library for interacting with the OpenCode server's backend API. It is designed for developers who want to build integrations, plugins, or custom frontends that leverage the core functionality of OpenCode, such as session management, agent interaction, and file system operations. The SDK is automatically generated from an OpenAPI specification, ensuring that it is always in sync with the server's API endpoints.
This SDK is a critical component for extending OpenCode, enabling programmatic control over its features. It supports both TypeScript and JavaScript, offering type safety and modern asynchronous programming patterns (async/await). The library handles API requests, authentication, and error handling, allowing developers to focus on their application logic.
Sources: packages/sdk/js/README.md, CONTRIBUTING.md:22-22, packages/opencode/AGENTS.md:21-22
Architecture and Generation
The JavaScript/TypeScript SDK is not manually written but is instead generated using the Stainless tool, based on an OpenAPI 3.1.1 specification. This generation process ensures that the SDK accurately reflects the server's API, including all endpoints, request parameters, and response schemas. When the server API in packages/opencode/src/server/server.ts is modified, the SDK must be regenerated to incorporate the changes.
Sources: CONTRIBUTING.md:21-22, packages/sdk/stainless/openapi.json
The diagram below illustrates the SDK generation workflow.
API Client Initialization
The main entry point for the SDK is the OpenCode class. To use the SDK, you must first instantiate this class.
Sources: packages/sdk/js/src/client.ts:18-26, packages/sdk/js/example/example.ts:3-3
Configuration
The OpenCode client can be configured during instantiation. The available options are:
| Option | Type | Description | Default |
|---|---|---|---|
baseURL | string | Overrides the base URL for all API requests. | process.env["OPENCODE_BASE_URL"] |
directory | string | The project directory. | process.env["OPENCODE_DIRECTORY"] |
authToken | string | The authentication token for API requests. | process.env["OPENCODE_AUTH_TOKEN"] |
timeout | number | Request timeout in milliseconds. | 600,000ms (10 minutes) |
fetch | Fetch | Custom fetch implementation. | Global fetch |
Sources: packages/sdk/js/src/client.ts:28-60
Usage Example
// packages/sdk/js/example/example.ts
import OpenCode from "@opencode/sdk";
const client = new OpenCode({
// You can provide the directory, otherwise it will be inferred
// from the environment
directory: process.cwd(),
});
async function main() {
const current = await client.project.current();
console.log("Current project:", current);
const sessions = await client.session.list();
console.log("Sessions:", sessions);
}
main();
Sources: packages/sdk/js/example/example.ts:1-18
API Resources
The SDK is organized into resources, each corresponding to a logical group of API endpoints. These resources are available as properties on the OpenCode client instance.
The following diagram shows the main OpenCode client and its relationship with the API resource namespaces.
Session Management
The session resource is central to interacting with the OpenCode agent. It allows for creating, managing, and interacting with conversational sessions.
Key methods include:
create(body): Creates a new session.get(id): Retrieves a specific session.list(): Lists all sessions for the project.prompt(id, body): Sends a message to a session and gets a response.fork(id, body): Creates a new session by forking an existing one at a specific message.delete(id): Deletes a session.messages(id): Lists all messages for a session.
Sources: packages/sdk/stainless/openapi.json
The sequence diagram below shows a typical interaction flow for creating a session and sending a prompt.
Sources: packages/sdk/stainless/openapi.json
Event Streaming
The event resource provides a way to subscribe to real-time events from the OpenCode server using Server-Sent Events (SSE).
subscribe(): Subscribes to the event stream. Returns aStreamobject that can be iterated over to receive events.
Sources: packages/sdk/stainless/openapi.json
Available event types include:
installation.updatedmessage.updatedmessage.part.updatedsession.createdsession.updatedsession.deletedpermission.updatedfile.edited
Sources: packages/sdk/stainless/openapi.json
File and Project Operations
The SDK provides resources for interacting with the project's file system and configuration.
project:list()andcurrent()methods to manage OpenCode projects.file:list(path),read(path), andstatus()methods for file system inspection.find:text(pattern),files(query), andsymbols(query)for searching within the workspace.config:get()andupdate(config)to manage project-specific configuration.
Sources: packages/sdk/stainless/openapi.json
Data Models
The SDK uses typed interfaces for all API request and response bodies, derived from the OpenAPI specification.
Session Model
The Session object represents a single conversation with the agent.
| Field | Type | Description |
|---|---|---|
id | string | Unique identifier for the session (e.g., ses...). |
projectID | string | The ID of the project this session belongs to. |
directory | string | The working directory of the session. |
parentID | string | null | The ID of the parent session if it's a fork. |
title | string | The title of the session. |
time | object | Timestamps for creation and updates. |
share | object | null | Contains the share URL if the session is shared. |
Sources: packages/sdk/stainless/openapi.json
Message and Part Models
A Session contains a series of messages. Each message is composed of one or more Part objects.
The diagram below shows the relationship between these core entities.
Sources: packages/sdk/stainless/openapi.json
- Message: Can be from a
userorassistant. Contains metadata likeid,sessionID, and timestamps. - Part: The content of a message. A
Partcan be of several types:text: Plain text content.reasoning: The agent's thought process.tool: Represents a tool call and its state (pending, running, completed, error).file: A file attachment.patch: A code patch.
Sources: packages/sdk/stainless/openapi.json
Conclusion
The JavaScript/TypeScript SDK is the primary tool for programmatically extending and integrating with OpenCode. Its auto-generated nature from the openapi.json specification guarantees that it remains a reliable and up-to-date interface to the server's API. By providing typed, asynchronous methods for all core features—from session and agent management to file system interaction and real-time event streaming—the SDK empowers developers to build powerful, custom tools and applications on top of the OpenCode platform.
Sources: packages/sdk/js/README.md, CONTRIBUTING.md:21-22, packages/sdk/stainless/openapi.json