A PHP SDK for interacting with the OpenCode API. Built with Saloon, this package provides a clean, type-safe interface for managing OpenCode sessions, sending messages, and interacting with the OpenCode API programmatically.
Warning
This package is currently under active development, and we have not yet released a major version. Once a 0.* version has been tagged, we strongly recommend locking your application to a specific working version because we might make breaking changes even in patch releases until we've tagged 1.0.
- Complete API Coverage: Auto-generated from OpenAPI spec with 52+ endpoints
- Type-Safe DTOs: 85+ data transfer objects for request/response handling
- Laravel Integration: Service provider with container binding and configuration
- Session Management: Create, update, delete, and manage OpenCode sessions
- Message Handling: Send prompts and retrieve AI assistant responses
- File Operations: List, read, and check file status
- Configuration Management: Get and update OpenCode configuration
- Event Subscriptions: Subscribe to OpenCode events
Install the package via Composer:
composer require artisan-build/opencode-sdkPublish the configuration file to customize settings:
php artisan vendor:publish --tag=opencode-sdkThis creates config/opencode-sdk.php in your application.
The package works out of the box with sensible defaults. Configuration can be customized via environment variables or by publishing the config file.
# OpenCode API Base URL (default: http://localhost:3333)
OPENCODE_BASE_URL=http://localhost:3333
# Request timeout in seconds (default: 30)
OPENCODE_TIMEOUT=30
# Optional authentication
OPENCODE_AUTH_TYPE=bearer
OPENCODE_AUTH_TOKEN=your-token-here
# Retry configuration
OPENCODE_RETRY_TIMES=3
OPENCODE_RETRY_SLEEP=100After publishing, you can customize config/opencode-sdk.php:
return [
'base_url' => env('OPENCODE_BASE_URL', 'http://localhost:3333'),
'timeout' => (int) env('OPENCODE_TIMEOUT', 30),
'auth' => [
'type' => env('OPENCODE_AUTH_TYPE'),
'token' => env('OPENCODE_AUTH_TOKEN'),
],
'retry' => [
'times' => (int) env('OPENCODE_RETRY_TIMES', 3),
'sleep' => (int) env('OPENCODE_RETRY_SLEEP', 100),
],
];use ArtisanBuild\OpencodeSdk\OpenCode\OpenCode;
// Create a new connector instance
$opencode = new OpenCode();use ArtisanBuild\OpencodeSdk\OpenCode\Requests\Misc\SessionList;
// Get all sessions
$response = $opencode->send(new SessionList());
$sessions = $response->json();use ArtisanBuild\OpencodeSdk\OpenCode\Requests\Misc\SessionCreate;
// Create a new session
$response = $opencode->send(new SessionCreate(
title: 'My New Session',
model: 'claude-3-5-sonnet-20241022'
));
$session = $response->json();
$sessionId = $session['id'];use ArtisanBuild\OpencodeSdk\OpenCode\Requests\Misc\SessionPrompt;
// Send a prompt to a session
$response = $opencode->send(new SessionPrompt(
id: $sessionId,
prompt: 'Write a hello world function in PHP'
));
$result = $response->json();use ArtisanBuild\OpencodeSdk\OpenCode\Requests\Misc\SessionMessages;
// Get all messages from a session
$response = $opencode->send(new SessionMessages(id: $sessionId));
$messages = $response->json();use ArtisanBuild\OpencodeSdk\OpenCode\Requests\Misc\SessionGet;
// Get a specific session
$response = $opencode->send(new SessionGet(id: $sessionId));
$session = $response->json();use ArtisanBuild\OpencodeSdk\OpenCode\Requests\Misc\SessionDelete;
// Delete a session
$response = $opencode->send(new SessionDelete(id: $sessionId));The SDK organizes requests into resources for cleaner syntax:
$opencode = new OpenCode();
// Access the misc resource
$misc = $opencode->misc();
// All requests are available through the resource
$sessions = $misc->sessionList();use ArtisanBuild\OpencodeSdk\OpenCode\OpenCode;
$opencode = new OpenCode();
$opencode->baseUrl('https://custom-opencode-server.com');$opencode = new OpenCode();
$opencode->config()->setTimeout(60); // 60 secondsIf your OpenCode API requires authentication:
use Saloon\Http\Auth\TokenAuthenticator;
$opencode = new OpenCode();
$opencode->authenticate(new TokenAuthenticator('your-api-token'));Saloon provides built-in retry capabilities. Configure retries:
use Saloon\Http\Faking\MockClient;
use Saloon\Http\Faking\MockResponse;
$opencode = new OpenCode();
// Retry on specific HTTP status codes
$opencode->config()->retry(
times: 3,
interval: 100, // milliseconds
useExponentialBackoff: true
);use ArtisanBuild\OpencodeSdk\OpenCode\Requests\Misc\FileList;
use ArtisanBuild\OpencodeSdk\OpenCode\Requests\Misc\FileRead;
// List files
$response = $opencode->send(new FileList(path: '/src'));
$files = $response->json();
// Read a file
$response = $opencode->send(new FileRead(path: '/src/index.php'));
$content = $response->json();use ArtisanBuild\OpencodeSdk\OpenCode\Requests\Misc\ConfigGet;
use ArtisanBuild\OpencodeSdk\OpenCode\Requests\Misc\ConfigUpdate;
// Get current config
$response = $opencode->send(new ConfigGet());
$config = $response->json();
// Update config
$response = $opencode->send(new ConfigUpdate(
// Pass config options as needed
));The SDK is fully testable using Saloon's testing utilities:
use Saloon\Http\Faking\MockClient;
use Saloon\Http\Faking\MockResponse;
use ArtisanBuild\OpencodeSdk\OpenCode\OpenCode;
use ArtisanBuild\OpencodeSdk\OpenCode\Requests\Misc\SessionList;
$mockClient = new MockClient([
SessionList::class => MockResponse::make([
['id' => 'ses_123', 'title' => 'Test Session'],
], 200),
]);
$opencode = new OpenCode();
$opencode->withMockClient($mockClient);
$response = $opencode->send(new SessionList());
// Will return the mocked responseThe SDK provides access to all OpenCode API endpoints:
SessionList- List all sessionsSessionCreate- Create a new sessionSessionGet- Get session detailsSessionUpdate- Update sessionSessionDelete- Delete sessionSessionFork- Fork a sessionSessionInit- Initialize sessionSessionAbort- Abort sessionSessionShare- Share sessionSessionUnshare- Unshare sessionSessionChildren- Get child sessionsSessionTodo- Get session todosSessionDiff- Get session diffSessionSummarize- Summarize sessionSessionRevert- Revert sessionSessionUnrevert- Unrevert session
SessionMessages- Get session messagesSessionPrompt- Send a promptSessionMessage- Get specific messageSessionCommand- Execute commandSessionShell- Execute shell command
FileList- List filesFileRead- Read file contentFileStatus- Get file status
ConfigGet- Get configurationConfigUpdate- Update configurationConfigProviders- Get providers
ProjectList- List projectsProjectCurrent- Get current project
ToolIds- Get tool IDsToolList- List tools
FindText- Search textFindFiles- Find filesFindSymbols- Find symbols
PathGet- Get path infoCommandList- List commandsAppLog- Get application logsAppAgents- Get agentsMcpStatus- Get MCP statusAuthSet- Set authenticationEventSubscribe- Subscribe to events
If you receive connection errors, ensure OpenCode is running:
# Check if OpenCode is running on the expected port
curl http://localhost:3333Update the base URL if using a different port:
OPENCODE_BASE_URL=http://localhost:8080Increase the timeout for long-running requests:
OPENCODE_TIMEOUT=120Or programmatically:
$opencode->config()->setTimeout(120);Ensure your authentication credentials are correct:
OPENCODE_AUTH_TYPE=bearer
OPENCODE_AUTH_TOKEN=your-valid-tokenIf you encounter "class not found" errors, ensure autoloader is updated:
composer dump-autoloadThis package is part of our internal toolkit and is optimized for our own purposes. We do not accept issues or PRs in this repository.
