hardimpact/opencode-sdk-laravel

Laravel SDK for the OpenCode AI coding agent API

Maintainers

Package info

github.com/hardimpactdev/opencode-sdk-laravel

pkg:composer/hardimpact/opencode-sdk-laravel

Statistics

Installs: 0

Dependents: 0

Suggesters: 0

Stars: 1

Open Issues: 0

0.0.4 2026-03-01 13:20 UTC

This package is auto-updated.

Last update: 2026-03-01 19:51:26 UTC


README

A Laravel SDK for the OpenCode AI coding agent HTTP API, built with Saloon.

Requirements

  • PHP 8.4+
  • Laravel 11 or 12

Installation

composer require hardimpact/opencode-sdk-laravel

The package auto-registers its service provider via Laravel's package discovery.

Configuration

Publish the config file:

php artisan vendor:publish --tag="opencode-config"
// config/opencode.php
return [
    'base_url' => env('OPENCODE_BASE_URL', 'http://localhost:4096'),
];

Usage

Using the Facade

use HardImpact\OpenCode\Facades\OpenCode;

$session = OpenCode::sessions()->create(directory: '/path/to/project');

Using Dependency Injection

use HardImpact\OpenCode\OpenCode;

public function __construct(private OpenCode $opencode) {}

Without Laravel

use HardImpact\OpenCode\OpenCode;

$opencode = new OpenCode('http://localhost:4096');

Sessions

// Create
$session = $opencode->sessions()->create(directory: '/path/to/project', title: 'My Session');

// List all
$sessions = $opencode->sessions()->list();

// Get by ID
$session = $opencode->sessions()->get(id: 'ses_xxx');

// Update
$session = $opencode->sessions()->update(id: 'ses_xxx', title: 'New Title');

// Delete
$opencode->sessions()->delete(id: 'ses_xxx');

// Abort active operation
$opencode->sessions()->abort(id: 'ses_xxx');

Sending Messages

// Sync (waits for completion)
$response = $opencode->sessions()->sendMessage(
    id: 'ses_xxx',
    providerID: 'anthropic',
    modelID: 'claude-sonnet-4-20250514',
    text: 'What files are in this project?',
);

// $response->info is an AssistantMessage
// $response->parts is an array of Part DTOs

// Async (returns immediately, monitor via events)
$opencode->sessions()->sendMessageAsync(
    id: 'ses_xxx',
    providerID: 'anthropic',
    modelID: 'claude-sonnet-4-20250514',
    text: 'Refactor the auth module',
);

// Send with raw parts (for file attachments, etc.)
$response = $opencode->sessions()->sendMessageWithParts(
    id: 'ses_xxx',
    providerID: 'anthropic',
    modelID: 'claude-sonnet-4-20250514',
    parts: [
        ['type' => 'text', 'text' => 'Review this file'],
        ['type' => 'file', 'mime' => 'text/plain', 'url' => 'file:///path/to/file.php'],
    ],
);

// Get message history
$messages = $opencode->sessions()->messages(id: 'ses_xxx');

Slash Commands

$response = $opencode->sessions()->command(
    id: 'ses_xxx',
    command: 'compact',
    arguments: '',
);

Session Operations

// Initialize
$opencode->sessions()->init(id: 'ses_xxx', messageID: '...', modelID: '...', providerID: '...');

// Summarize
$opencode->sessions()->summarize(id: 'ses_xxx', modelID: '...', providerID: '...');

// Revert to a previous message
$session = $opencode->sessions()->revert(id: 'ses_xxx', messageID: 'msg_xxx');

// Undo revert
$session = $opencode->sessions()->unrevert(id: 'ses_xxx');

// Share / unshare
$session = $opencode->sessions()->share(id: 'ses_xxx');
$session = $opencode->sessions()->unshare(id: 'ses_xxx');

Permissions (Questions)

When OpenCode needs approval for tool usage (file edits, bash commands, etc.), permissions appear as events. Respond programmatically:

// List pending permissions
$questions = $opencode->questions()->list();

// Approve once
$opencode->questions()->answer(
    sessionId: 'ses_xxx',
    permissionId: 'perm_xxx',
    response: 'once',
);

// Approve always (for this pattern)
$opencode->questions()->answer(
    sessionId: 'ses_xxx',
    permissionId: 'perm_xxx',
    response: 'always',
);

// Reject
$opencode->questions()->reject(sessionId: 'ses_xxx', permissionId: 'perm_xxx');

Event Streaming (SSE)

Monitor real-time state changes via Server-Sent Events:

foreach ($opencode->events()->stream() as $event) {
    match ($event->type) {
        EventType::SessionIdle => handleDone($event),
        EventType::SessionError => handleError($event),
        EventType::MessagePartUpdated => handlePartUpdate($event),
        EventType::PermissionUpdated => handlePermission($event),
        default => null,
    };
}

Projects

// List all projects
$projects = $opencode->projects()->list();

// Get current project
$project = $opencode->projects()->current();

// Update project properties (name, icon, startup script)
$project = $opencode->projects()->update(
    id: 'proj_xxx',
    name: 'My Project',
    icon: ['override' => 'rocket', 'color' => '#ff0000'],
    commands: ['start' => 'php artisan serve'],
);

Providers

$providers = $opencode->providers()->list();

Session Management

The SDK includes an Eloquent model (OpenCodeSession) and a SessionManager for tracking and managing session lifecycles in your application.

OpenCodeSession Model

use HardImpact\OpenCode\Models\OpenCodeSession;

// Create a session linked to any model via polymorphic relationship
$session = OpenCodeSession::query()->create([
    'sessionable_id' => $task->id,
    'sessionable_type' => Task::class,
    'session_id' => 'ses_xxx',
    'workspace' => '/path/to/project',
    'provider' => 'anthropic',
    'model' => 'claude-sonnet-4-20250514',
    'status' => 'created',
]);

// Status helpers
$session->isActive();    // true when status is Active
$session->isIdle();      // true when status is Idle
$session->isTerminal();  // true when status is Completed or Failed

SessionManager

The SessionManager provides session lifecycle management with assessment heuristics and Laravel event dispatching.

use HardImpact\OpenCode\SessionManager;

$manager = new SessionManager;

// Assess session state by querying the OpenCode API
$assessment = $manager->assess($session);
$assessment->state;            // SessionState enum (Active, Idle, Completed, Missing)
$assessment->shouldComplete(); // true when state is Completed or Idle
$assessment->isMissing();      // true when the API session was not found

// With completion pattern matching
$assessment = $manager->assess($session, ['/task completed/i', '/all done/i']);

// Lifecycle transitions (each dispatches a Laravel event)
$manager->activate($session);   // → SessionActivated
$manager->markIdle($session);   // → SessionBecameIdle
$manager->complete($session);   // → SessionCompleted
$manager->fail($session, $msg); // → SessionFailed
$manager->interrupt($session);  // → SessionInterrupted
$manager->recover($session);    // → SessionRecovered

All lifecycle methods are idempotent — calling them on a session already in the target state is a no-op.

Tolerant Deserialization

The SDK handles unknown enum values from the API gracefully. Unknown part types, message roles, and tool statuses are mapped to Unknown enum cases instead of throwing exceptions:

$part = Part::fromTolerant($data); // returns null if data is invalid, maps unknown enums to Unknown

Error Handling

DTO-returning methods (e.g. sessions()->get(), sessions()->messages()) throw on HTTP errors. Boolean-returning methods (e.g. sessions()->delete(), sessions()->abort()) return false on failure instead of throwing.

Feature Parity

Comparison with the official OpenCode SDKs (JS, Go).

Session

Endpoint Laravel JS Go
Create session Y Y Y
List sessions Y Y Y
Get session Y Y Y
Update session Y - Y
Delete session Y Y Y
Abort session Y Y Y
Send message (sync) Y Y Y
Send message (async) Y - -
Get messages Y Y Y
Get single message - - Y
Run slash command Y - Y
Run shell command - - Y
Init session Y Y Y
Summarize session Y Y Y
Revert session Y Y Y
Unrevert session Y Y Y
Share session Y Y Y
Unshare session Y Y Y
Get child sessions - - Y

Permissions

Endpoint Laravel JS Go
List pending Y - -
Respond (once/always/reject) Y - Y

Events

Endpoint Laravel JS Go
SSE event stream Y Y Y

Providers

Endpoint Laravel JS Go
List providers + models Y Y Y

App

Endpoint Laravel JS Go
Get app info - Y -
Init app - Y -
Log - Y Y
List modes - Y -

Config

Endpoint Laravel JS Go
Get config - Y Y

File

Endpoint Laravel JS Go
List files - - Y
Read file - Y Y
File status (git) - Y Y

Find

Endpoint Laravel JS Go
Find files - Y Y
Find symbols - Y Y
Find text - Y Y

Agent

Endpoint Laravel JS Go
List agents - - Y

Project

Endpoint Laravel JS Go
List projects Y - Y
Current project Y - Y
Update project Y - -

Session Management (Laravel-only)

Feature Laravel JS Go
OpenCodeSession Eloquent model Y - -
SessionManager (lifecycle + assess) Y - -
Laravel event dispatching Y - -
Tolerant enum deserialization Y - -

Command

Endpoint Laravel JS Go
List commands - - Y

Path

Endpoint Laravel JS Go
Get paths - - Y

TUI

Endpoint Laravel JS Go
Append/clear/submit prompt - Y Y
Open help/models/sessions/themes - Y Y
Execute command - - Y
Show toast - - Y

Testing

composer test

Static Analysis

composer analyse

Code Style

composer format

License

MIT