PHPackages                             hardimpact/opencode-sdk-laravel - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [API Development](/categories/api)
4. /
5. hardimpact/opencode-sdk-laravel

ActiveLibrary[API Development](/categories/api)

hardimpact/opencode-sdk-laravel
===============================

Laravel SDK for the OpenCode AI coding agent API

0.0.5(1mo ago)11021[1 issues](https://github.com/hardimpactdev/opencode-sdk-laravel/issues)MITPHPPHP ^8.4

Since Feb 7Pushed 1mo agoCompare

[ Source](https://github.com/hardimpactdev/opencode-sdk-laravel)[ Packagist](https://packagist.org/packages/hardimpact/opencode-sdk-laravel)[ Docs](https://github.com/hardimpactdev/opencode-sdk-laravel)[ RSS](/packages/hardimpact-opencode-sdk-laravel/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (3)Dependencies (32)Versions (6)Used By (0)

OpenCode SDK for Laravel
========================

[](#opencode-sdk-for-laravel)

A Laravel SDK for the [OpenCode](https://github.com/opencode-ai/opencode) AI coding agent HTTP API, built with [Saloon](https://docs.saloon.dev).

Requirements
------------

[](#requirements)

- PHP 8.4+
- Laravel 11 or 12

Installation
------------

[](#installation)

```
composer require hardimpact/opencode-sdk-laravel
```

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

Configuration
-------------

[](#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
-----

[](#usage)

### Using the Facade

[](#using-the-facade)

```
use HardImpact\OpenCode\Facades\OpenCode;

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

### Using Dependency Injection

[](#using-dependency-injection)

```
use HardImpact\OpenCode\OpenCode;

public function __construct(private OpenCode $opencode) {}
```

### Without Laravel

[](#without-laravel)

```
use HardImpact\OpenCode\OpenCode;

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

### Sessions

[](#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

[](#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

[](#slash-commands)

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

### Session Operations

[](#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)

[](#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)

[](#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

[](#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)

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

### Session Management

[](#session-management)

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

#### OpenCodeSession Model

[](#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

[](#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

[](#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

[](#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
--------------

[](#feature-parity)

Comparison with the official OpenCode SDKs ([JS](https://github.com/anomalyco/opencode-sdk-js), [Go](https://github.com/anomalyco/opencode-sdk-go)).

### Session

[](#session)

EndpointLaravelJSGoCreate sessionYYYList sessionsYYYGet sessionYYYUpdate sessionY-YDelete sessionYYYAbort sessionYYYSend message (sync)YYYSend message (async)Y--Get messagesYYYGet single message--YRun slash commandY-YRun shell command--YInit sessionYYYSummarize sessionYYYRevert sessionYYYUnrevert sessionYYYShare sessionYYYUnshare sessionYYYGet child sessions--Y### Permissions

[](#permissions)

EndpointLaravelJSGoList pendingY--Respond (once/always/reject)Y-Y### Events

[](#events)

EndpointLaravelJSGoSSE event streamYYY### Providers

[](#providers-1)

EndpointLaravelJSGoList providers + modelsYYY### App

[](#app)

EndpointLaravelJSGoGet app info-Y-Init app-Y-Log-YYList modes-Y-### Config

[](#config)

EndpointLaravelJSGoGet config-YY### File

[](#file)

EndpointLaravelJSGoList files--YRead file-YYFile status (git)-YY### Find

[](#find)

EndpointLaravelJSGoFind files-YYFind symbols-YYFind text-YY### Agent

[](#agent)

EndpointLaravelJSGoList agents--Y### Project

[](#project)

EndpointLaravelJSGoList projectsY-YCurrent projectY-YUpdate projectY--### Session Management (Laravel-only)

[](#session-management-laravel-only)

FeatureLaravelJSGoOpenCodeSession Eloquent modelY--SessionManager (lifecycle + assess)Y--Laravel event dispatchingY--Tolerant enum deserializationY--### Command

[](#command)

EndpointLaravelJSGoList commands--Y### Path

[](#path)

EndpointLaravelJSGoGet paths--Y### TUI

[](#tui)

EndpointLaravelJSGoAppend/clear/submit prompt-YYOpen help/models/sessions/themes-YYExecute command--YShow toast--YTesting
-------

[](#testing)

```
composer test
```

Static Analysis
---------------

[](#static-analysis)

```
composer analyse
```

Code Style
----------

[](#code-style)

```
composer format
```

License
-------

[](#license)

MIT

###  Health Score

37

—

LowBetter than 83% of packages

Maintenance71

Regular maintenance activity

Popularity17

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity45

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~12 days

Total

5

Last Release

42d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/9d5702c35fc18764615b1a80dffdcd4a980a04fd79bc2192bc7db79691ae0447?d=identicon)[nckrtl](/maintainers/nckrtl)

---

Top Contributors

[![nckrtl](https://avatars.githubusercontent.com/u/18613261?v=4)](https://github.com/nckrtl "nckrtl (3 commits)")

---

Tags

laravelsdkaiopencodeHardImpact

###  Code Quality

TestsPest

Static AnalysisPHPStan, Rector

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/hardimpact-opencode-sdk-laravel/health.svg)

```
[![Health](https://phpackages.com/badges/hardimpact-opencode-sdk-laravel/health.svg)](https://phpackages.com/packages/hardimpact-opencode-sdk-laravel)
```

###  Alternatives

[ryangjchandler/bearer

Minimalistic token-based authentication for Laravel API endpoints.

8129.8k](/packages/ryangjchandler-bearer)[helgesverre/mistral

Laravel Client for the Mistral.ai API

5213.5k1](/packages/helgesverre-mistral)[simplestats-io/laravel-client

Client for SimpleStats!

4515.5k](/packages/simplestats-io-laravel-client)[claude-php/claude-php-sdk-laravel

Laravel integration for the Claude PHP SDK - Anthropic Claude API

5010.8k](/packages/claude-php-claude-php-sdk-laravel)[codebar-ag/laravel-docuware

DocuWare integration with Laravel

1221.1k](/packages/codebar-ag-laravel-docuware)[codebar-ag/laravel-zammad

Zammad integration with Laravel

106.1k](/packages/codebar-ag-laravel-zammad)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
