> ## Documentation Index
> Fetch the complete documentation index at: https://kawax.biz/llms.txt
> Use this file to discover all available pages before exploring further.

# Sessions, host, and environment

> Use ServerRpc in Laravel Copilot SDK to manage sessions, the host, the runtime environment, cloud tasks, and trajectory classification.

## Sessions, host, and environment

Scope: ServerRpc (server-wide operations tied to the Client)

For an overview of RPC and the list of all RPC pages, see [RPC](https://kawax.biz/en/packages/laravel-copilot-sdk/rpc.md).

```php theme={null}
use Revolution\Copilot\Enums\EventsReadDirection;
use Revolution\Copilot\Types\Rpc\HooksDiscoverRequest;
use Revolution\Copilot\Types\Rpc\SessionsListRequest;
use Revolution\Copilot\Types\Rpc\SessionsPruneOldRequest;
use Revolution\Copilot\Types\Rpc\SessionsReadPersistedEventsRequest;
use Revolution\Copilot\Types\Rpc\SessionsOpenCreateRequest;
use Revolution\Copilot\Enums\SessionsOpenStatus;
use Revolution\Copilot\Types\SessionConfig;
use Revolution\Copilot\Types\SessionListFilter;

// List of built-in slash commands available in new sessions (experimental)
Copilot::client()->rpc()->commands()->list();

// Hook discovery before a session starts (experimental)
Copilot::client()->rpc()->hooks()->discover(new HooksDiscoverRequest(
    projectPaths: ['/path/to/project'],
));

// Host sandbox support (experimental)
$hostSupport = Copilot::client()->rpc()->sandbox()->getHostSupport();
// $hostSupport->supported, $hostSupport->reason, $hostSupport->capabilities

// sessions (experimental: query and manage persisted sessions)

// sessions.open selects create, resume, resumeLast, attach, remote/cloud connection, or handoff with `kind`.
$opened = $sessions->open(new SessionsOpenCreateRequest(
    options: new SessionConfig(sessionId: 'new-session', model: 'gpt-5'),
));
if ($opened->status === SessionsOpenStatus::Created) {
    echo $opened->sessionId;
}
// You can also pass an array. When resuming, set sessionId at the top level of the variant.
$resumed = $sessions->open(['kind' => 'resume', 'sessionId' => 'existing-session']);
// Returns SessionsOpenResult. When the status is not_found, there is no sessionId.
// sessionApi, onTaskCreated, onProgress, and onConfirm are in-process only and aren't included in the wire payload.

$listed = $sessions->list(new SessionsListRequest(
    source: 'local',
    metadataLimit: 50,
    filter: new SessionListFilter(cwd: '/path/to/project'),
));
// Use isRemote on each SessionMetadata to tell local and remote sessions apart
foreach ($listed->sessions as $session) {
    echo $session->sessionId;
}

$sessions->findByTaskId(['taskId' => 'task-id']);
$sessions->findByPrefix(['prefix' => 'session-id-prefix']);
$sessions->getLastForContext(['context' => ['cwd' => '/path/to/project']]);
// Check for a local event log without opening the session (an empty log also counts)
$hasEvents = Copilot::client()->rpc()->sessions()->hasEvents(['sessionId' => 'session-id']);
// $hasEvents->exists is false when the session has metadata but no log
$sizes = $sessions->getSizes(); // $sizes->sizes maps session ID => byte count
$inUse = $sessions->checkInUse(['sessionIds' => ['session-id']]);
$deleted = $sessions->bulkDelete(['sessionIds' => ['session-id']]);

// Close an active session (history isn't deleted)
$sessions->close(['sessionId' => 'session-id']);

// Save pending events to disk
$sessions->save(['sessionId' => 'session-id']);

// Explicitly release the in-use lock on a session held by this process
$sessions->releaseLock(['sessionId' => 'session-id']);

// reloadPluginHooks reloads user/plugin hooks.
// Repo hooks are deferred until folder trust is confirmed, then loaded after trust is confirmed.
$sessions->reloadPluginHooks([
    'sessionId' => 'session-id',
    'deferRepoHooks' => true,
]);
$loadedHooks = $sessions->loadDeferredRepoHooks(['sessionId' => 'session-id']);
// $loadedHooks->startupPrompts and $loadedHooks->hookCount

// Replace manager-wide additional plugin settings (clear with an empty array)
$sessions->setAdditionalPlugins(['plugins' => []]);

// Fill in summary / context for local session metadata
$enriched = $sessions->enrichMetadata([
    'sessions' => [[
        'sessionId' => 'session-id',
        'startTime' => '2026-10-17T09:00:00Z',
        'modifiedTime' => '2026-10-17T09:00:00Z',
        'isRemote' => false,
    ]],
]);

// close() shuts down, saves events, and releases the lock, then disposes of the active session,
// but doesn't delete persisted history. $session->disconnect() uses session.detach to release
// the connection to this SDK and the in-memory resources on the PHP side. Use bulkDelete() to delete persisted data.

// Page through persisted events with a cursor without opening the session
$cursor = null;
do {
    $page = $sessions->readPersistedEvents(new SessionsReadPersistedEventsRequest(
        sessionId: 'session-id',
        cursor: $cursor,
        max: 100,
        direction: EventsReadDirection::FORWARD,
    ));

    foreach ($page->events as $event) {
        // Process the event
    }

    $cursor = $page->cursor;
} while ($page->hasMore);

// dryRun returns candidates and estimates without deleting. To actually delete, specify dryRun: false
$preview = $sessions->pruneOld(new SessionsPruneOldRequest(
    olderThanDays: 30,
    dryRun: true,
));

// sessions.fork
$sessions->fork(new SessionsForkRequest(
    sessionId: 'source-session-id',
    toEventId: 'evt-boundary', // Optional: include only events before this ID
));

// environments (experimental: search, get, and delete GitHub Mission Control environments)
$result = Copilot::client()->rpc()->environments()->list(['kind' => 'user-local']);
// $result->environments is an array of GitHubEnvironment
$env = Copilot::client()->rpc()->environments()->get(['environmentId' => 'env-id']);
Copilot::client()->rpc()->environments()->delete(['environmentId' => 'env-id']);
```

## Runtime and host lifecycle (experimental)

`host.unpublishSession()` withdraws an application publication from a running host you own. Unpublishing doesn't delete or stop the original session history, worktree, or running work. If the session is already unpublished, `unpublished` is `false`, and publications other than application raise an error.

```php theme={null}
$result = Copilot::client()->rpc()->host()->unpublishSession([
    'hostId' => 'host-1',
    'sessionId' => 'session-1',
]);
// $result->unpublished
```

`host.dispose()` disposes of a host listener by `hostId`.

```php theme={null}
Copilot::client()->rpc()->host()->dispose(['hostId' => 'host-1']);
```

`host.setSessionCreationPolicy()` toggles whether a running host accepts new remote sessions. The change doesn't disconnect existing clients and applies only to later admissions.

```php theme={null}
use Revolution\Copilot\Types\Rpc\HostSetSessionCreationPolicyRequest;

Copilot::client()->rpc()->host()->setSessionCreationPolicy(
    new HostSetSessionCreationPolicyRequest(
        hostId: 'host-1',
        allowCreatingNewSessions: false,
    ),
);
```

For a stdio runtime started by the SDK, `Client::stop()` calls `runtime.shutdown` after disconnecting sessions and before closing the JSON-RPC connection and the process. Session detaches (`session.detach`) share a single 10-second deadline across all sessions; a detach that misses the deadline is included in the return value as an error, and shutdown continues. It also waits up to 10 seconds for runtime cleanup to finish; on failure, it includes the error in the return value and continues with the rest of the shutdown. For connections to an external runtime such as `cli_url`, this RPC isn't called so the shared runtime isn't terminated.

If the CLI can't identify the matching request and returns a JSON-RPC error with `id: null`, every in-flight request fails with a `JsonRpcException`. The exception includes a diagnostic message with quoted values removed and its length capped. The connection stays open. Because the CLI may already have processed the request, don't retry automatically without confirming that it's safe. The SDK rejects outgoing requests nested deeper than 127 levels, which the CLI can't read, before sending them. It replaces handler responses that are nested too deeply with a JSON-RPC error.

## cloudTasks (experimental: cloud agent tasks)

`cloudTasks()` creates, deletes, and gets cloud coding agent tasks, retrieves session logs and replays, changes sharing state, and resolves the session to open from a task ID. Each method accepts the matching Params type or an array and returns a typed DTO. When `ok` on a create result is `false`, check `reason` and `message` for why the service declined the request, and `statusCode`, `errorMessage`, and `errorPayloadJson` for a failed HTTP request.

```php theme={null}
use Revolution\Copilot\Facades\Copilot;
use Revolution\Copilot\Types\Rpc\CloudTasksCreateParams;

$result = Copilot::client()->rpc()->cloudTasks()->create(
    new CloudTasksCreateParams(
        authInfo: $authInfo,
        integrationId: 'my-app',
        repositoryOwner: 'octo',
        repositoryName: 'example',
    ),
);

if (! $result->ok) {
    // $result->reason and $result->message describe a declined request.
    // $result->statusCode and $result->errorMessage describe an attempted HTTP request.
}
```

## taskAnalytics (experimental: classify recorded trajectories)

`taskAnalytics()->classifyTrajectory()` classifies recorded Copilot events or ATIF data without creating a session. Archived tools aren't executed, and nothing is added to conversation history or classification telemetry. Pass `events` in their original order. You can also set `classifiers`, `maxConcurrentRequests`, `judge`, and `previousResult`. With `validateOnly: true`, the runtime skips inference and returns only the local validation result.

A normal classification sends the event content to model processing that uses your GitHub CAPI credentials. There is no automatic redaction or prompt injection protection. Approve the upload, verify where the archive came from, and remove sensitive data first. Classification results aren't trusted facts, so don't use them for authorization or security decisions.

```php theme={null}
$result = Copilot::client()->rpc()->taskAnalytics()->classifyTrajectory([
    'events' => $events,
    'validateOnly' => true,
]);
```

To open an authentication URL in the browser, use `runtime()->openBrowser()`.

```php theme={null}
use Revolution\Copilot\Types\Rpc\RuntimeOpenBrowserRequest;

Copilot::client()->rpc()->runtime()->openBrowser(new RuntimeOpenBrowserRequest(
    url: 'https://example.com/authorize',
));
```

To get the sandbox path grant warning, use `sandbox()->getPathGrantWarning()`.

```php theme={null}
use Revolution\Copilot\Types\Rpc\SandboxPathGrantWarningParams;

$warning = Copilot::client()->rpc()->sandbox()->getPathGrantWarning(new SandboxPathGrantWarningParams(
    resolvedPath: '/workspace/project',
    readOnly: false,
));
```

## sessions connect and Remote Control (TCP mode)

To connect the CLI server to an existing remote session, use `sessions()->connect()`. Pass the remote `sessionId`, and the result contains the SDK-side `sessionId` and the remote session's metadata.

```php theme={null}
use Revolution\Copilot\Facades\Copilot;
use Revolution\Copilot\Types\Rpc\ConnectRemoteSessionParams;

$client = Copilot::useTcp(url: 'tcp://127.0.0.1:12345')->client();

$connected = $client->rpc()->sessions()->connect(
    new ConnectRemoteSessionParams(sessionId: 'remote-session-id'),
);

echo $connected->sessionId;
// $connected->metadata - ConnectedRemoteSessionMetadata object
```

In TCP mode, you can also use `sessions()` to manage a single Remote Control for the whole runtime. Unlike the per-session `remote()->enable()`, these methods let you start, stop, and transfer Remote Control between sessions, and read its current status.

```php theme={null}
use Revolution\Copilot\Types\Rpc\RemoteControlConfig;
use Revolution\Copilot\Types\Rpc\SessionsStartRemoteControlRequest;

$result = $client->rpc()->sessions()->startRemoteControl(
    new SessionsStartRemoteControlRequest(
        sessionId: $sessionId,
        config: new RemoteControlConfig(
            remote: true,
            steerable: true,
            explicit: true,
            silent: false,
        ),
    ),
);

if ($result->status->frontendUrl !== null) {
    echo 'Remote URL: '.$result->status->frontendUrl.PHP_EOL;
}

$status = $client->rpc()->sessions()->getRemoteControlStatus();
// The state is one of off / connecting / active / error. When active, frontendUrl and isSteerable are also available

$client->rpc()->sessions()->setRemoteControlSteering(['enabled' => true]);
$client->rpc()->sessions()->transferRemoteControl([
    'toSessionId' => $nextSessionId,
    'expectedFromSessionId' => $sessionId,
]);
$client->rpc()->sessions()->stopRemoteControl([
    'expectedSessionId' => $nextSessionId,
]);
```

For details, see [Remote Sessions](https://kawax.biz/en/packages/laravel-copilot-sdk/remote-sessions.md).


## Related topics

- [ServerRpc overview](https://kawax.biz/en/packages/laravel-copilot-sdk/rpc/server-overview.md)
- [RPC (Remote Procedure Call)](https://kawax.biz/en/packages/laravel-copilot-sdk/rpc.md)
- [SessionConfig](https://kawax.biz/en/packages/laravel-copilot-sdk/session-config.md)
- [AHP Host](https://kawax.biz/en/packages/laravel-copilot-sdk/ahp.md)
- [Session](https://kawax.biz/en/session.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.