# JSON Event Stream Mode

```bash
selesai --mode json "Your prompt"
```

Outputs all session events as JSON lines to stdout. Useful for integrating pi into other tools or custom UIs.

## Event Types

Events are defined in [`AgentSessionEvent`](https://github.com/earendil-works/pi-mono/blob/main/packages/coding-agent/src/core/agent-session.ts#L102):

```typescript
type AgentSessionEvent =
  | Exclude<AgentEvent, { type: "agent_end" }>
  | { type: "agent_end"; messages: AgentMessage[]; willRetry: boolean }
  | { type: "agent_settled"; aborted: boolean }
  | { type: "queue_update"; steering: readonly string[]; followUp: readonly string[] }
  | { type: "compaction_start"; reason: "manual" | "threshold" | "overflow" }
  | { type: "compaction_end"; reason: "manual" | "threshold" | "overflow"; result: CompactionResult | undefined; aborted: boolean; willRetry: boolean; errorMessage?: string }
  | { type: "auto_retry_start"; attempt: number; maxAttempts: number; delayMs: number; errorMessage: string }
  | { type: "auto_retry_end"; success: boolean; attempt: number; finalError?: string };
```

`queue_update` emits the full pending steering and follow-up queues whenever they change. `compaction_start` and `compaction_end` cover both manual and automatic compaction. In session events `agent_end` also carries `willRetry`, which is `true` when the session will retry automatically after this `agent_end` because the last assistant message was a retryable error. `agent_settled` is described in [Run settlement](#run-settlement).

Base events from [`AgentEvent`](https://github.com/earendil-works/pi-mono/blob/main/packages/agent/src/types.ts#L179):

```typescript
type AgentEvent =
  // Agent lifecycle
  | { type: "agent_start" }
  | { type: "agent_end"; messages: AgentMessage[] }
  // Turn lifecycle
  | { type: "turn_start" }
  | { type: "turn_end"; message: AgentMessage; toolResults: ToolResultMessage[] }
  // Message lifecycle
  | { type: "message_start"; message: AgentMessage }
  | { type: "message_update"; message: AgentMessage; assistantMessageEvent: AssistantMessageEvent }
  | { type: "message_end"; message: AgentMessage }
  // Tool execution
  | { type: "tool_execution_start"; toolCallId: string; toolName: string; args: any }
  | { type: "tool_execution_update"; toolCallId: string; toolName: string; args: any; partialResult: any }
  | { type: "tool_execution_end"; toolCallId: string; toolName: string; result: any; isError: boolean; durationMs?: number };
```

## Message Types

Base messages from [`packages/ai/src/types.ts`](https://github.com/earendil-works/pi-mono/blob/main/packages/ai/src/types.ts#L134):
- `UserMessage` (line 134)
- `AssistantMessage` (line 140)
- `ToolResultMessage` (line 152)

Extended messages from [`packages/coding-agent/src/core/messages.ts`](https://github.com/earendil-works/pi-mono/blob/main/packages/coding-agent/src/core/messages.ts#L29):
- `BashExecutionMessage` (line 29)
- `CustomMessage` (line 46)
- `BranchSummaryMessage` (line 55)
- `CompactionSummaryMessage` (line 62)

## Wire streaming events

JSON and RPC mode emit `JsonAgentSessionEvent`, a delta-only projection of SDK events. `message_update` includes cumulative `usage` and `assistantMessageEvent`, but omits the cumulative `message` and nested `partial` snapshots. Reconstruct text/thinking from deltas and use `message_end.message` as the authoritative final message. `toolcall_start` includes `contentIndex`, `id`, and `toolName`. Read stdout continuously; backpressure can pause generation.

## Run settlement

`agent_end` ends one agent loop, not necessarily the whole run: automatic retry, compaction recovery, and queued steering or follow-up messages can start further loops. `agent_settled` is emitted once, after all of that, and follows the run's other lifecycle events:

```json
{"type":"agent_settled","aborted":false}
```

`aborted` is `true` only if an abort was requested while the run was active (Escape in the TUI, the RPC `abort` command, `session.abort()`, or `ctx.abort()` from an extension), including during an automatic-retry delay. The flag is reset for each run, and an abort while no run is active does not affect the next one.

`aborted: false` does not mean the run succeeded. A run that ends in a provider error that is not retried, or whose retries are exhausted, also settles with `aborted: false`. To distinguish completion from failure, read the run's last assistant `message_end`: `stopReason` is `"error"` with an `errorMessage` after a failure, and `"aborted"` when an abort cut the response off. For a cancellation, rely on `aborted`; an abort during a retry delay may leave no aborted assistant message.

A failed run:

```json
{"type":"message_end","message":{"role":"assistant","stopReason":"error","errorMessage":"...",...}}
{"type":"agent_settled","aborted":false}
```

A run aborted mid-response:

```json
{"type":"message_end","message":{"role":"assistant","stopReason":"aborted",...}}
{"type":"agent_settled","aborted":true}
```

Other events of the run can appear between the lines shown. Extension `agent_settled` handlers run before the event is written to stdout (see [`agent_settled`](extensions.md#agent_settled)). A prompt handled by an extension command or `input` handler without starting a run emits no `agent_settled`. In RPC mode, wait for `agent_settled` before treating a prompt as complete.

## Output Format

Each line is a JSON object. The first line is the session header:

```json
{"type":"session","version":3,"id":"uuid","timestamp":"...","cwd":"/path"}
```

Followed by events as they occur:

```json
{"type":"agent_start"}
{"type":"turn_start"}
{"type":"message_start","message":{"role":"assistant","content":[],...}}
{"type":"message_update","usage":{...},"assistantMessageEvent":{"type":"text_delta","delta":"Hello",...}}
{"type":"message_end","message":{...}}
{"type":"turn_end","message":{...},"toolResults":[]}
{"type":"agent_end","messages":[...],"willRetry":false}
{"type":"agent_settled","aborted":false}
```

## Example

```bash
selesai --mode json "List files" 2>/dev/null | jq -c 'select(.type == "message_end")'
```
