---
title: Message execution
description: >-
  Execute messages with SSE streaming, the StreamEvent reference, interrupts,
  sub-agents, and human-in-the-loop
tags:
  - sessions
  - streaming
  - sse
  - tools
---
> This endpoint is deprecated and answers `410 Gone`.

This endpoint runs a single turn in a session and streams everything that happens back to you as it happens — the model's text as it's generated, each tool call, job progress, sub-agent activity, and pauses for approval. Reach for it once you've created a session in [Manage sessions](/docs/api/sessions-manage) and want to send a message and watch the response unfold live. Every turn ends with a sync event so your client knows the stream is complete.

  advanced
  20 min
  [Sessions overview](/docs/api/sessions-overview), [Manage sessions](/docs/api/sessions-manage)

## Message Execution

## Request

- `content` (string) —
The user message to execute

- `stream` (boolean) —
Set to `false` for non-streaming mode (returns final state as JSON)

- `clientId` (string) —
Client identifier for version vector tracking. Auto-generated as `api_{Date.now()}` if not provided.

### Example Request

**cURL (SSE)**

```bash
curl -N -X POST "https://yourapp.com/api/v1/sessions/$SESSION_ID/execute" \
  -H "Authorization: Bearer ivy_your_key" \
  -H "Content-Type: application/json" \
  -d '{"content": "Run ADMET prediction on aspirin"}'
```

**TypeScript (fetch)**

```ts
const response = await fetch(
  `/api/v1/sessions/${sessionId}/execute`,
  {
    method: "POST",
    headers: {
      "Authorization": `Bearer ${apiKey}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ content: "Run ADMET prediction on aspirin" }),
  }
)

const reader = response.body!.getReader()
const decoder = new TextDecoder()

while (true) {
  const { done, value } = await reader.read()
  if (done) break

  const chunk = decoder.decode(value)
  for (const line of chunk.split("\n")) {
    if (line.startsWith("data: ")) {
      const event = JSON.parse(line.slice(6))
      console.log(event.type, event)
    }
  }
}
```

## SSE Response Format

The response has `Content-Type: text/event-stream`. Each event is one `data:` line holding a flat JSON object; its `type` field names the event and the other fields sit beside it, not under a `data` key:

```
data: {"type":"turn.started","turnId":"..."}

data: {"type":"message.delta","delta":"I'll run an ADMET prediction..."}

data: {"type":"tool.started","toolCall":{"id":"tc_001","name":"admet_ai","arguments":{"smiles":"CC(=O)Oc1ccccc1C(=O)O"}}}

data: {"type":"sync.completed","sessionId":"..."}
```

After the runtime finishes, the route writes a final `sync.completed` event and closes the stream. If the runtime throws mid-stream, the route writes an `error` event with `code: "EXECUTION_ERROR"` instead and closes.

---

## StreamEvent Types

The event union is `StreamEvent` in `@pleach/core`; that type is the authority, and new event types are additive. Handle the ones you need and ignore the rest. Every event may also carry `namespace` (a sub-agent path; empty for the root agent).

### Message Events

| Event | Fields | Meaning |
|-------|--------|---------|
| `message.added` | `message` | A message was appended to the session |
| `message.delta` | `delta`, `callClass?` | A chunk of answer text |
| `reasoning.delta` | `delta` | A chunk of model reasoning, never answer text |
| `message.complete` | `message`, `usage?`, `finishReason?` | Ivy's message is final |
| `message.citations` | `citations`, `section` | Citations extracted for the message |
| `message.entities` | `toolCallId`, `toolName`, `entities` | Linkable entities (genes, compounds, …) found in a tool result |
| `thinking.delta` / `thinking.complete` | `delta` / `thinking` | Extended-thinking text |
| `content.reset` | `reason`, `failedModel?` | Discard the text streamed so far; a retry follows |
| `content.correction` | `correctedContent`, `reason` | Replace the streamed answer with this text |
| `content.preview` / `content.suppressed` | `reason`, … | Interim text the runtime withheld or marked provisional |

### Tool Events

| Event | Fields | Meaning |
|-------|--------|---------|
| `tool.started` | `toolCall` | The model called a tool |
| `tool.delta` | `toolCallId`, `delta` | Streaming tool output |
| `tool.completed` | `toolCall`, `result` | The tool returned |
| `tool.failed` | `toolCall`, `error` | The tool failed |
| `result.offloaded` | `toolName`, `filename`, `sandboxPath`, `sizeBytes`, `rowCount?` | A tool result was written to the sandbox instead of the prompt |

### Job Events

| Event | Fields | Meaning |
|-------|--------|---------|
| `job.dispatched` | `job` | A compute job was submitted |
| `job.progress` | `jobId`, `progress`, `phase?`, `statusMessage?`, `estimatedRemainingMs?` | Progress from the backend |
| `job.completed` | `job` | The job finished |
| `job.failed` | `jobId`, `error` | The job failed |
| `jobs.pending` | `jobs` | Jobs still running when the turn ended |

### Artifact, Checkpoint and Sandbox Events

| Event | Fields | Meaning |
|-------|--------|---------|
| `artifact.created` | `artifact` | A new artifact reference |
| `checkpoint.created` | `checkpoint` | A checkpoint was saved (see [Checkpoints](/docs/api/sessions-checkpoints)) |
| `sandbox.created` | `sandboxId`, `tunnelUrl` | The chat's sandbox started |
| `sandbox.terminated` | `sandboxId`, `exportedFiles` | The sandbox stopped |

### Interrupt Events

| Event | Fields | Meaning |
|-------|--------|---------|
| `interrupt.requested` | `interrupt` | A tool call is waiting for approval |
| `interrupt.resolved` | `interruptId`, `decision` | The approval was answered |

### Sub-Agent Events

| Event | Fields | Meaning |
|-------|--------|---------|
| `subagent.spawned` | `subagentId`, `task`, `specName?` | A sub-agent started |
| `subagent.progress` | `subagentId`, `progress`, `message?`, `activeToolName?` | Sub-agent progress |
| `subagent.completed` | `subagentId`, `content`, `toolsUsed` | The sub-agent returned |
| `subagent.failed` | `subagentId`, `error`, `terminalStatus?` | The sub-agent failed, timed out or was cancelled |

### Session and Sync Events

| Event | Fields | Meaning |
|-------|--------|---------|
| `session.created` / `session.resumed` / `session.updated` | `session` | The full `SessionState` |
| `sync.started` / `sync.completed` | `sessionId` | Sync boundaries; the route's last event is `sync.completed` |
| `sync.conflict` | `sessionId`, `resolution` | A conflict was resolved as `local`, `remote` or `merged` |
| `context.summarized` | `originalMessageCount`, `compressedTokens` | Older history was condensed |

### Turn and Error Events

| Event | Fields | Meaning |
|-------|--------|---------|
| `turn.started` | `turnId?` | The turn began |
| `turn.completed` | `outcome`, `durationMs`, `abortedByUser?` | The turn ended as `ok`, `error` or `interrupted` |
| `turn.metrics` | `context`, `tools` | Context-window use and tool counts for the turn |
| `error` | `error`, `code?`, `httpStatus?` | A runtime error |
| `stream.truncated` | `reason`, `partialLength` | Output was cut off by a repetition guard |
| `stream.reconnecting` / `stream.disconnected` | `attempt`, `maxRetries` | Provider stream retries |

### Diagnostic Events

The runtime also emits diagnostic events. Clients that render a conversation can ignore any event type they do not handle.

---

## Non-Streaming Mode

Set `stream: false` to receive the final state as a single JSON response instead of SSE:

```bash
curl -X POST "https://yourapp.com/api/v1/sessions/$SESSION_ID/execute" \
  -H "Authorization: Bearer ivy_your_key" \
  -H "Content-Type: application/json" \
  -d '{"content": "What tools are available?", "stream": false}'
```

Returns `{"success": true, "events": [...], "state": {...}}`: every event the turn produced, and the last `SessionState` seen in a `session.updated` or `session.resumed` event (or `null` if none was emitted).

---

## Interrupt Flow (Human-in-the-Loop)

The runtime's `InterruptConfig` names the tools that pause for approval (`interruptBefore`, `interruptAfter`). The REST create route does not take it: `POST /api/v1/sessions` reads only `config.provider`, `config.model` and `config.tools`, so which tools pause is set by the host application.

When a turn reaches a gated tool:

1. The stream emits `interrupt.requested` with the pending interrupt.
2. Your client answers with `POST /api/v1/sessions/:sessionId/interrupt/:interruptId/resolve` and a body of `{"approved": true}` or `{"approved": false, "note": "..."}`.
3. The stream emits `interrupt.resolved` and the turn continues.

> The SSE connection stays open while the interrupt waits. Set client-side timeouts that allow for a person to answer.

---

## Read next

- [Manage sessions](/docs/api/sessions-manage) — create and manage sessions
- [SSE Streaming](/docs/api/realtime-sse) — SSE protocol details
- [Sync protocol](/docs/api/sessions-sync) — version vector sync
- [Checkpoints](/docs/api/sessions-checkpoints) — roll a session back
