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

# SessionEvent

> Work with the Laravel Copilot SDK's SessionEvent using Laravel-native helpers, type checks, and broadcasting.

## SessionEvent

Every message from Copilot is a `Revolution\Copilot\Types\SessionEvent` class.
Because this is the class you use most often, Laravel-native conveniences are added on top.

## `content()`

Get the most important response message from the AI.

```php theme={null}
$response = Copilot::run('1 + 1');
echo $response->content(); // '2'
// content() can be null
```

Implicit conversion via `__toString()` also returns the message content.

```php theme={null}
echo (string) $response; // '2'
// This one is never null
```

## Checking the event type

`isAssistantMessage()`, `isUserMessage()`, `isIdle()`, and `isAssistantMessageDelta()` are available.
Additional helpers may be added for commonly used event types.

Use `is()` to check for any `EventType`.

```php theme={null}
use Revolution\Copilot\Enums\SessionEventType;

if ($response->is(SessionEventType::HOOK_START)) {
    // Handle the hook-start event
}
```

`type()` returns the string value of the `SessionEventType` enum.

```php theme={null}
echo $response->type(); // 'assistant.message'
```

## `session.autopilot_stopped`

`SessionEventType::SESSION_AUTOPILOT_STOPPED` (`session.autopilot_stopped`) fires when Autopilot stops continuing a specific request.
Use `$event->data['requestId']` to get the target message ID and `$event->data['reason']` to get the stop reason.
This event does not mean the whole session has become idle.

## `failed()` / `successful()`

When the event type is `SESSION_ERROR`, `failed()` returns true.
`successful()` is the opposite.

Renamed from `isError()` to match Laravel's naming.

## `throw()`

Just like Laravel's HTTP or Process API, errors are retained and can be raised via `throw()`.
If there's no error it does nothing, so you can write:

```php theme={null}
$content = $response->throw()->content();
```

If the event type is `SESSION_ERROR`, `Revolution\Copilot\Exceptions\SessionErrorException` is thrown.
On timeout, `Revolution\Copilot\Exceptions\SessionTimeoutException` is thrown.

For JSON-RPC errors, `Revolution\Copilot\Exceptions\JsonRpcException` is thrown.

See [Exceptions and error handling](https://kawax.biz/en/packages/laravel-copilot-sdk/exceptions.md) for the full list of exceptions and how to catch them.

## Conditionable

`when()` and `unless()` are available.

```php theme={null}
$response->when($response->isAssistantMessage(), function (SessionEvent $event) {
    // Handle assistant messages
});
```

## Dumpable

`dump()` and `dd()` are available.

```php theme={null}
$response->dump();
```

## Tappable

`tap()` is available.

```php theme={null}
return $response->tap(function (SessionEvent $event) {
    // Do something
    info($event->content());
});
```

## InteractsWithData

This feature applies only to SessionEvent's `$data` property.

Familiar helpers such as `all()`, `has()`, `only()`, and `collect()` are available.
See [InteractsWithData](https://kawax.biz/en/advanced/interacts-with-data.md) for details.

Because SessionEvent's `$data` shape differs per `EventType`, this is handy for accessing event-specific values.

`content()` also uses InteractsWithData under the hood.

```php theme={null}
return $this->data('content', $default);

// Pass a default to keep content() from being null
echo $response->content('');
```

## `toArray()` / `toJson()`

You can convert the entire SessionEvent to an array or JSON.

```php theme={null}
$array = $response->toArray();
$json = $response->toJson();
```

There is no top-level `collect()` method for the event as a whole, since InteractsWithData already provides `collect()` for `$data`.
To perform collection operations on the whole event, use Laravel's `collect()` helper.

```php theme={null}
$collect = collect($response->toArray());
```

## `broadcast()` / `broadcastNow()`

You can broadcast with the same interface as the Laravel AI SDK's `StreamEvent`.
The AI SDK uses it during streaming, but for SessionEvent you can use it with any `EventType`.

```php theme={null}
use Illuminate\Broadcasting\Channel;

$event->broadcast(new Channel('channel-name'));
```

`broadcastNow()` broadcasts immediately without going through a queue.

```php theme={null}
$event->broadcastNow(new Channel('channel-name'));
```

Streaming example:

```php theme={null}
use Illuminate\Broadcasting\Channel;
use Revolution\Copilot\Contracts\CopilotSession;
use Revolution\Copilot\Facades\Copilot;
use Revolution\Copilot\Types\SessionConfig;
use Revolution\Copilot\Types\SessionEvent;

Copilot::start(function (CopilotSession $session) {
    $session->on(function (SessionEvent $event): void {
        if ($event->isAssistantMessageDelta()) {
            $event->broadcastNow(new Channel('copilot'));
        }
    });

    $session->sendAndWait(prompt: 'Tell me something about Laravel.');
}, config: new SessionConfig(streaming: true));
```

## Event metadata

Starting with Copilot CLI 1.0.99, some events include additional metadata.
The SDK keeps these values as-is in `$data`, so you can access them through `$event->data` or the InteractsWithData helpers.

### Compaction events

`data.compactionAttemptId` on `session.compaction_start` and `session.compaction_complete` is an ID that links the start event to the complete event.
When the compaction involves a model switch, `switchTargetModel` is also included.
When the target model has a different prompt token budget, `targetPromptTokenLimit` is also included.

The complete event may include `initialModel`, `model`, `outcome`, `outcomeReason`, `failureReason`, `tokenAccountingBasis`, and more.
`outcome` and the reason fields are strings that may gain new values in the future.
Don't treat them as a fixed enum, and preserve unknown values as-is.
A missing field means the value wasn't provided. Don't infer a default value.

`session.compaction_summarized` means background compaction finished summarizing but hasn't applied the summary to the conversation yet (`data.applyPending` is always `true`).
The following `session.compaction_complete` is the authoritative result of applying or discarding it.

```php theme={null}
if ($event->is(SessionEventType::SESSION_COMPACTION_COMPLETE)) {
    $attemptId = $event->data('compactionAttemptId');
    $outcome = $event->data('outcome');
}
```

### Tool execution usage

`data.toolUsage` on `tool.execution_complete` is the provider-reported usage for runtime-owned tool operations.
It is separate from the conversation model's `assistant.usage`.
It may include reported usage even when the tool execution failed.
`toolUsage.model` is the model requested by the tool operation, not the conversation model.

Token counts and billing information may be only partially provided.
A missing field means the value is unavailable, not zero tokens.

```php theme={null}
$usage = $event->data['toolUsage'] ?? null;
$inputTokens = $usage['inputTokens'] ?? null;
$imageTokens = $usage['inputTokensDetails']['imageTokens'] ?? null;
```

The per-modality token counts in `inputTokensDetails` and `outputTokensDetails` are breakdowns included in their respective totals. Don't add them to the totals.
`toolUsage.requestId` is an ID the runtime uses to deduplicate redelivery and replay. It is not an upstream billing identifier.

`data.toolUsageRequestIds` on `session.usage_checkpoint` and `session.shutdown` is also runtime-internal deduplication metadata that identifies the tool operations included in the accounting snapshot.
Don't treat it as an upstream billing ID.

### Fusion resolved events

`data.selectedRuleId` on `session.fusion_resolved` identifies the server rule when server-side routing selects a different workflow than the local rule.
It is omitted when there is no override.

### MCP server tools loaded events

`SessionEventType::SESSION_MCP_SERVER_TOOLS_LOADED` (`session.mcp_server_tools_loaded`) fires when an MCP server's tool list becomes available.
It is an ephemeral event that fires once per connection and is not persisted.
It includes `data.serverName` and `data.toolCount`.

An MCP server reaching `connected` does not mean its tools have finished loading.
After the server leaves the connected state, treat it as loading until you receive this event again.
When cached tools are used, this event may arrive before `connected`.

```php theme={null}
if ($event->is(SessionEventType::SESSION_MCP_SERVER_TOOLS_LOADED)) {
    info("{$event->data('serverName')}: {$event->data('toolCount')} tools loaded");
}
```

### Instruction update events

`SessionEventType::INSTRUCTION_UPDATE` (`instruction.update`) fires when the runtime updates authoritative developer instructions. It was added in Copilot CLI 1.0.103.

| Field | Description |
| - | - |
| `data.content` | The instruction text |
| `data.authority` | The source of the update: `runtime`, `host`, or `managedPolicy` |
| `data.boundary` | The boundary the instruction applies to |
| `data.fallback` | The behavior when the provider doesn't support the instruction |
| `data.lifetime` | How long the instruction stays in effect |
| `data.name` | Optional name for diagnostics |

```php theme={null}
if ($event->is(SessionEventType::INSTRUCTION_UPDATE)) {
    $instruction = $event->data['content'];
}
```

`persistent` updates are kept in event order and restored after replay, resume, rewind, fork, and compaction.
`turn` updates are temporary, and `ephemeral` is `true` for them.
Values are kept as generic arrays, so unknown enum values are passed through as-is.

> [!NOTE]
>
> For the latest updates, see the [GitHub repository](https://github.com/invokable/laravel-copilot-sdk).


## Related topics

- [Streaming events](https://kawax.biz/en/packages/laravel-copilot-sdk/streaming-events.md)
- [Exceptions and error handling](https://kawax.biz/en/packages/laravel-copilot-sdk/exceptions.md)
- [Custom agents](https://kawax.biz/en/packages/laravel-copilot-sdk/custom-agents.md)
- [Getting started - GitHub Copilot SDK for Laravel](https://kawax.biz/en/packages/laravel-copilot-sdk/getting-started.md)
- [GitHub Copilot SDK for Laravel](https://kawax.biz/en/packages/laravel-copilot-sdk/index.md)


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