createOpencode()
Create a complete OpenCode instance with both server and client.
import { createOpencode } from '@opencode-ai/sdk'
const { client , server } = await createOpencode ( options )
Parameters
Server configuration options Show ServerOptions properties
hostname
string
default: "127.0.0.1"
Server hostname to bind to
Abort signal for cancellation
Timeout in milliseconds for server startup
Returns
Type-safe client instance for API calls
Server instance with control methods Full URL of the running server (e.g., http://127.0.0.1:4096)
Method to shutdown the server: server.close()
Example
import { createOpencode } from '@opencode-ai/sdk'
const { client , server } = await createOpencode ({
hostname: '127.0.0.1' ,
port: 4096 ,
timeout: 10000 ,
config: {
model: 'anthropic/claude-3-5-sonnet-20241022' ,
logLevel: 'INFO' ,
},
})
console . log ( `Server running at ${ server . url } ` )
// Use the client
const health = await client . global . health ()
console . log ( `Version: ${ health . data . version } ` )
// Shutdown when done
server . close ()
With Abort Signal
const controller = new AbortController ()
const { client , server } = await createOpencode ({
signal: controller . signal ,
config: { model: 'anthropic/claude-3-5-sonnet-20241022' },
})
// Abort after 30 seconds
setTimeout (() => controller . abort (), 30000 )
createOpencodeClient()
Create a client to connect to an existing OpenCode server.
import { createOpencodeClient } from '@opencode-ai/sdk'
const client = createOpencodeClient ( options )
Parameters
Client configuration options Show OpencodeClientConfig properties
baseUrl
string
default: "http://localhost:4096"
URL of the OpenCode server
Override the working directory for this client. Sets the x-opencode-directory header.
Custom fetch implementation. Defaults to global fetch.
Custom headers to include with every request
Response parsing method: auto, json, text, blob, arrayBuffer, stream
Return style: data (returns only data) or fields (returns object with data, error, etc.)
Throw errors instead of returning them in response object
Returns
Type-safe client instance for making API calls to the server
Example: Basic Client
import { createOpencodeClient } from '@opencode-ai/sdk'
const client = createOpencodeClient ({
baseUrl: 'http://localhost:4096' ,
})
const sessions = await client . session . list ()
console . log ( `Active sessions: ${ sessions . data . length } ` )
const client = createOpencodeClient ({
baseUrl: 'http://localhost:4096' ,
headers: {
'X-Custom-Header' : 'value' ,
},
})
Example: Override Directory
const client = createOpencodeClient ({
baseUrl: 'http://localhost:4096' ,
directory: '/path/to/project' ,
})
// All operations will use this directory
const project = await client . project . current ()
Example: Error Handling
// Return errors in response object
const client = createOpencodeClient ({
baseUrl: 'http://localhost:4096' ,
throwOnError: false ,
})
const result = await client . session . get ({ path: { id: 'invalid' } })
if ( result . error ) {
console . error ( 'Error:' , result . error )
}
// Or throw errors
const throwingClient = createOpencodeClient ({
baseUrl: 'http://localhost:4096' ,
throwOnError: true ,
})
try {
await throwingClient . session . get ({ path: { id: 'invalid' } })
} catch ( error ) {
console . error ( 'Error:' , error )
}
createOpencodeTui()
Launch the OpenCode Terminal UI programmatically.
import { createOpencodeTui } from '@opencode-ai/sdk'
const tui = createOpencodeTui ( options )
Parameters
TUI configuration options Show TuiOptions properties
Project directory to open
Model to use (format: provider/model)
Agent to use (e.g., build, plan, general)
Abort signal for cancellation
Returns
TUI instance with control methods Method to close the TUI: tui.close()
Example
import { createOpencodeTui } from '@opencode-ai/sdk'
const tui = createOpencodeTui ({
project: '/path/to/project' ,
model: 'anthropic/claude-3-5-sonnet-20241022' ,
agent: 'build' ,
})
// TUI runs in the current terminal
// Use tui.close() to exit programmatically
Client Namespaces
The client is organized into logical namespaces:
Global
client . global . health () // Server health check
client . global . event () // Global event stream
Session
client . session . list () // List sessions
client . session . create () // Create session
client . session . get () // Get session
client . session . update () // Update session
client . session . delete () // Delete session
client . session . prompt () // Send prompt
client . session . command () // Execute command
client . session . messages () // Get messages
client . session . share () // Share session
// ... and more
Project
client . project . list () // List projects
client . project . current () // Get current project
Config
client . config . get () // Get configuration
client . config . update () // Update configuration
client . config . providers () // List providers
File Operations
client . find . text () // Search text in files
client . find . files () // Find files by name
client . find . symbols () // Find workspace symbols
client . file . read () // Read file contents
client . file . status () // Get file status
App
client . app . log () // Write log entry
client . app . agents () // List available agents
TUI Control
client . tui . appendPrompt () // Append text to prompt
client . tui . submitPrompt () // Submit prompt
client . tui . clearPrompt () // Clear prompt
client . tui . showToast () // Show notification
client . tui . openSessions () // Open session selector
client . tui . openModels () // Open model selector
Auth
client . auth . set () // Set authentication credentials
Events
client . event . subscribe () // Subscribe to server-sent events
By default, API calls return an object with the following structure:
interface Response < T > {
data : T // Response data
error ?: Error // Error if request failed
response : Response // Raw fetch Response object
}
Accessing Data
const result = await client . session . list ()
// Access response data
console . log ( result . data ) // Session[]
// Check for errors
if ( result . error ) {
console . error ( 'Failed:' , result . error )
}
// Access raw response
console . log ( result . response . status ) // 200
TypeScript Support
The client is fully typed with TypeScript:
import type { Session , Message , Config } from '@opencode-ai/sdk'
// Types are inferred automatically
const sessions = await client . session . list ()
// sessions.data is typed as Session[]
const session = await client . session . get ({ path: { id: 'abc' } })
// session.data is typed as Session
const config = await client . config . get ()
// config.data is typed as Config
See the Types reference for all available types.