# Events (/docs/run/events)



```ts
const page = await session.history();
for (const item of page.items) {
  console.log(item.type, item.payload);
}

for await (const event of session.observe({ cursor: page.cursor ?? undefined })) {
  console.log(event.type, event.payload);
}
```

Each record includes `eventId`, `sessionId`, `turnId`, `cursor`, `time`,
`type`, `payload`, `source`, and `evidence`. The `cursor` is an opaque
position. Pass it to `history({ cursor })` or `observe({ cursor })` to
continue. `history({ agent })` keeps events whose `payload.agent.delegationId`
or `payload.agent.path` matches. `observe({ follow: true })` merges linked flow
child sessions. `observe` skips SSE frames named `heartbeat` or `ready`.
A connection that sends nothing, keepalives included, for `idleTimeoutMs`
(45 seconds by default; `0` never) is dropped and reopened from the last
event's id, so a stalled stream does not stall the loop.
Clients ignore event types they do not know.

`session.inspect()` returns status and waits. It is a snapshot, not a live
stream.

## Families [#families]

| Family                                                    | When                                                                                                                                                                                                                                                             | Schema                            |
| --------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------- |
| `command.*`                                               | A message, approval, or response was accepted.                                                                                                                                                                                                                   | [Runtime API](/reference/runtime) |
| `message.queued`, `queue.taken`                           | A message arrived while a turn ran and waits in the session's queue (`queuedMessageId`, `position`), or a turn started with the queued messages (`turnId`, `queuedMessageIds`). See [Messages while a turn runs](/docs/run/sessions#messages-while-a-turn-runs). | [Runtime API](/reference/runtime) |
| `queue.failed`, `queue.cancelled`                         | Queued messages no turn will take (`queuedMessageIds`): their Agent refused their turn's start past `queuedStartMs` or for good (`error`), or a client removed them (A2A `CancelTask`). Host feature `queue-recovery`.                                           | [Runtime API](/reference/runtime) |
| `turn.*`                                                  | The turn completed, paused, failed, or was cancelled.                                                                                                                                                                                                            | [Runtime API](/reference/runtime) |
| `message.assistant`, `model.failed`, `context.compacted`  | A model call ended.                                                                                                                                                                                                                                              | [Runtime API](/reference/runtime) |
| `tool.*`                                                  | A tool call ended (`tool.completed`), one per call.                                                                                                                                                                                                              | [Runtime API](/reference/runtime) |
| `mcp.*`                                                   | A turn readied the agent's MCP servers (`mcp.discovered`): the session's first, and the first on a manifest version whose harness section differs.                                                                                                               | [Runtime API](/reference/runtime) |
| `effect.*`                                                | A model call's outcome was lost (`effect.uncertain`).                                                                                                                                                                                                            | [Runtime API](/reference/runtime) |
| `delegation.*`                                            | A subagent started or settled.                                                                                                                                                                                                                                   | [Runtime API](/reference/runtime) |
| `node.*`                                                  | A flow stage started (`node.started`), an HTTP stage ended (`node.completed`), or an agent stage opened its session (`node.agent`).                                                                                                                              | [Runtime API](/reference/runtime) |
| `loop.*`                                                  | A Loop iteration or a verifier's verdict (`loop.iteration`, `loop.verified`).                                                                                                                                                                                    | [Runtime API](/reference/runtime) |
| `wake.*`                                                  | The agent booked its session's next turn with `schedule_wake` (`wake.booked`), or cancelled the booking (`wake.cancelled`). See [Wakes](/docs/run/triggers#wakes).                                                                                               | [Runtime API](/reference/runtime) |
| `memory.updated`                                          | The agent's `memory` tool changed the Agent's memories. See [Agent memory](/docs/run/memory).                                                                                                                                                                    | [Runtime API](/reference/runtime) |
| `plan.updated`                                            | The agent's `update_plan` tool recorded its whole plan: up to 20 steps, each a `label`, a `state`, and an optional `note`. See [Loop settings](/docs/build/agent-manifests#loop-settings).                                                                       | [Runtime API](/reference/runtime) |
| `agent.attached`, `environment.state`, `environment.exec` | The session's [Agent](/docs/run/agents): the session opened on it, its sandbox's state, and each sandbox tool run.                                                                                                                                               | [Runtime API](/reference/runtime) |
| `artifact.*`                                              | File uploads, exports, and tool results the harness stored.                                                                                                                                                                                                      | [Runtime API](/reference/runtime) |

Assistant text arrives whole. There is no token streaming.

## The agent's record and the Runtime's [#the-agents-record-and-the-runtimes]

Each event type has a layer in the event catalog, so the envelope does not
carry it. **`agent`** events are what the agent saw and did: its inputs
(`command.*`), model calls, tool calls, the harness's own work (`context.compacted`,
`delegation.*`, `plan.updated`, `memory.updated`), turns, and a flow's stages.
**`runtime`** events are what the Runtime did to the session: the queue, wakes,
the model setting, the sandbox (`environment.*`), MCP discovery, artifacts, and
diagnostics. Every event on an Agent's own stream is the Runtime's.

```ts
import { eventLayer } from "@nylorun/agents";

const page = await session.history();
const agentOnly = page.items.filter((item) => eventLayer(item.type) === "agent");
```

`eventLayer` returns `undefined` for a type your package version does not know.
Studio's **Events › Log** opens on the **Agent** view, with **Runtime** and
**All** beside it.

## Who wrote an event [#who-wrote-an-event]

`source.kind` says who wrote an event, and `evidence` how far to trust it. The
most common writers:

| `source.kind` | Writer                                                                                                                                            | `evidence` |
| ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- |
| `client`      | A command over the Runtime API. `principal` names who sent it, from its credential.                                                               | `observed` |
| `harness`     | What the harness reported: assistant messages, tool results it ran, its turn's end. `source.id` is the harness id.                                | `claimed`  |
| `core`        | The Runtime's own logic, such as a held or refused call, a tool the Runtime serves (`schedule_wake`, `memory`), or a trigger's or wake's message. | `observed` |

Events written by an older Runtime say `api` or `loop`; accept both spellings
when you filter on `source.kind`.

## Turn payloads [#turn-payloads]

`turn.completed`, `turn.failed`, and `turn.cancelled` carry:

| Field        | Meaning                                                                                                                  |
| ------------ | ------------------------------------------------------------------------------------------------------------------------ |
| `durationMs` | From the turn's start to its end, time waiting for a person included.                                                    |
| `pausedMs`   | How much of that the turn waited paused.                                                                                 |
| `agentId`    | The session's [Agent](/docs/run/agents).                                                                                 |
| `manifest`   | `{ name, version }`: the agent manifest version the turn ran.                                                            |
| `totals`     | `{ steps, tokens, costUsd }`: the model calls the Model Gate metered, as `GET /v1/tenant/usage?scope=turn` reports them. |

`turn.paused` lists `interactions`: one `approval` per tool call the
[tool policy](/docs/run/tool-policy) holds, each with its `interaction.id`, the
tool name, `input`, and `reason`. See [Pauses and control](/docs/run/control).

`command.message` carries the message as sent and its `delivery`, plus:

| Field             | Meaning                                                                                                                                                                    |
| ----------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `removeTools`     | The tools the message's turn may not use. See [Leave tools out of a turn](/docs/run/sessions#leave-tools-out-of-a-turn).                                                   |
| `queuedMessageId` | The message waited in the session's queue; its id there.                                                                                                                   |
| `cause`           | `{ kind, triggerId, runId }` for a message no client sent: `trigger` for a [trigger's run](/docs/run/triggers#runs), `self` for a booked [wake](/docs/run/triggers#wakes). |

`turn.version_kept` says a turn's first segment kept the session on the version
it was accepted for, not its Agent's current one: `reason: "variant_invalid"`,
`from` and `to` (each `{ name, version }`), and `message`. The message carried a
whole turn manifest that is no variant of the new version, so the turn runs on
the old one and never gets more than its message allowed.

`session.model` is written when the session opens, when it chooses or clears its
own model, and at a turn's start when the model its turns call changed: the
session's [model record](/docs/run/models#a-sessions-model), with `previous`.

`engine.diagnostic` is something the engine met that the agent's declarations
decide, and says instead of choosing: `mcp_tools_inline` for an agent that
doesn't declare `engine.toolSearch` and whose MCP tools pass the deferral
threshold. See [Engine features](/docs/build/agent-manifests#engine-features).

## Model call payloads [#model-call-payloads]

Each model call ends in one row, `message.assistant` or `model.failed`, and
each compaction in one `context.compacted` with its last summary call's facts.
Each carries:

| Field          | Meaning                                                                                                                                                         |
| -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `effectId`     | The model call's effect id; the same as in [`session.modelCalls()`](/reference/runtime/sessions/page-a-sessions-model-calls).                                   |
| `durationMs`   | From the call's start to its outcome.                                                                                                                           |
| `gate`         | `{ startedAt, endedAt }`: the Model Gate's own times, when it metered the call.                                                                                 |
| `firstTokenMs` | From the gate's start to the provider's first stream event.                                                                                                     |
| `meteredUsage` | `inputTokens`, `outputTokens`, `totalTokens`, and `cachedTokens` and `costUsd` when not zero: what the Runtime counts, beside the `usage` the harness reported. |

A model step that said nothing (no text and no tool calls) writes
`message.assistant` with `text: ""`; it is in the log for its timing. A
structured answer's `message.assistant` carries the answer's JSON text.
`context.compacted` also carries `trigger` (`threshold` or `overflow`),
`tokensBefore`, and `tokensAfter`. The AG-UI and A2A histories skip empty steps; when you render
raw events, skip them with `isEmptyAssistantMessage`:

```ts
import { isEmptyAssistantMessage } from "@nylorun/core/contracts";

const shown = page.items.filter(
  (item) =>
    !(item.type === "message.assistant" && isEmptyAssistantMessage(item.payload as { text?: unknown })),
);
```

## Tool payloads [#tool-payloads]

Every tool call ends in one `tool.completed`, whether it ran, failed, was
refused, or was cancelled. It carries the call's `callId`, `toolName` (the name
the model called it by), and `output`, or an `error`, and:

| Field             | Meaning                                                                                                                                                                                                                                                                                                                           |
| ----------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `status`          | `completed`: the tool answered, with its output or its own error. `failed`: the Runtime ended the call (`tool.denied`, `tool.interrupted`, `tool.disabled`, `tool.unavailable`). `cancelled`: the turn was cancelled while the call ran or was held; it may have run.                                                             |
| `kind`            | `mcp`, `http`, `sandbox`, `harness` (a tool the turn's harness runs itself: our harness's `read_artifact`, `save_artifact`, `load_skill`, `read_skill_resource`, and `tool_search`; see [Bring your own harness](/docs/build/harness#tools-of-your-own)), or `runtime` (a tool the Runtime serves: `schedule_wake` and `memory`). |
| `server`          | The MCP server, or the host of the HTTP tool's URL.                                                                                                                                                                                                                                                                               |
| `tool`            | The tool's identity: an MCP tool's own name on `server`, or an HTTP tool's declared name. The [tool policy](/docs/run/tool-policy) and approvals key on it.                                                                                                                                                                       |
| `skill`           | The skill the call ran: the one `load_skill` or `read_skill_resource` names, or the one whose folder (`/skills/<name>@<hash>/`) a sandbox tool's input names. See [Skills](/docs/build/skills).                                                                                                                                   |
| `plugin`          | `{ name, version? }`: the Agent Plugin that brought the call's MCP server or skill. See [Plugins](/docs/build/plugins).                                                                                                                                                                                                           |
| `attempts`        | How many times the call was sent: `0` when it was never sent, above `1` when the Runtime sent it again with the same key.                                                                                                                                                                                                         |
| `durationMs`      | From the first send to the outcome; absent when the call never ran.                                                                                                                                                                                                                                                               |
| `effectId`        | The call's effect id, as in [`session.toolCalls()`](/reference/runtime/sessions/page-a-sessions-tool-calls).                                                                                                                                                                                                                      |
| `gate`            | `{ startedAt, endedAt }`: the Tool Gate's own times of the last send, for an MCP or HTTP call.                                                                                                                                                                                                                                    |
| `policy`          | `{ decision, reason, approvedBy? }` when the [tool policy](/docs/run/tool-policy) held (`ask`) or refused (`deny`) the call.                                                                                                                                                                                                      |
| `error.code`      | The code the model saw, such as `tool.denied`, `tool.interrupted`, `mcp.lost`, `credential_rejected`, or `http.status`.                                                                                                                                                                                                           |
| `error.message`   | What went wrong, without credential values.                                                                                                                                                                                                                                                                                       |
| `error.retryable` | Whether calling again may succeed, when known.                                                                                                                                                                                                                                                                                    |
| `error.server`    | With `credential_rejected`: the MCP server, or the HTTP tool's `credential`, whose server answered `401`, or whose gateway at `via` reported that the server behind it did.                                                                                                                                                       |
| `error.gateway`   | With `credential_rejected` of a [`workload` credential](/docs/run/credentials#the-workload-credential): the origin of the gateway that refused the Runtime's workload token, such as an expired one.                                                                                                                              |
| `redacted`        | How many credential values in the result or error were replaced with `[redacted]`.                                                                                                                                                                                                                                                |

| Code               | Meaning                                                                                                        |
| ------------------ | -------------------------------------------------------------------------------------------------------------- |
| `tool.denied`      | The tool policy refused the call, or a person denied it. It was never sent.                                    |
| `tool.interrupted` | A crash interrupted the call. It may have run. See [Pauses and control](/docs/run/control#tool-call-delivery). |
| `mcp.lost`         | An MCP call was sent and its answer lost. It may have run.                                                     |

A flow's HTTP stage and HTTP verifier end in `node.completed` instead, with the
stage's `path`, `kind`, `key`, `iterations`, `effectId`, `status`,
`durationMs`, and `gate`.

`mcp.discovered` has one entry in `servers` per declared MCP server, with its
`serverName`, `outcome` (`connected`, `failed`, or `refused`), `message`, and
`tools`, the number of its tools the server's `tools` settings leave enabled,
and:

| Field          | Meaning                                                                                |
| -------------- | -------------------------------------------------------------------------------------- |
| `agentId`      | The agent used as a tool that declares the server; absent for the session's own agent. |
| `plugin`       | `{ name, version? }`: the Agent Plugin that brought the server, when one did.          |
| `disabled`     | How many tools the server's `tools` settings disabled.                                 |
| `unknownTools` | Keys in the server's `tools` settings that match no tool the server lists.             |

A server that did not connect adds no tools until a turn runs a manifest
version whose harness section differs, which readies the servers again. See
[MCP](/docs/build/mcp).

Through a gateway whose credential sets a
[`toolPrefix`](/docs/run/credentials#gateway-tool-prefix), the server's tools
are counted and named without the prefix. A tool the gateway listed without
the prefix keeps its name, and the server's `message` names it.

A tool result our harness stores as an artifact raises `artifact.created` with
`source: "engine"` and the tool call's `callId`; see
[Files](/docs/run/files#large-tool-results).

## Agent payloads [#agent-payloads]

| Event               | Payload                                                                                                     |
| ------------------- | ----------------------------------------------------------------------------------------------------------- |
| `agent.attached`    | `agentId`: the session was opened on this Agent.                                                            |
| `environment.state` | `state` (`creating`, `running`, or `stopped`), `backend`, and, when known, `image`, `network`, and `error`. |
| `environment.exec`  | One sandbox tool call: `tool`, `command`, `outcome`, `code`, and `durationMs`.                              |
| `memory.updated`    | `effectId`, and `changes`: each `{ path, operation, version }` the `memory` call changed.                   |
| `wake.booked`       | `at`, `note`, `effectId`, and `replaced` when it replaced a booking.                                        |

### The Agent's stream [#the-agents-stream]

An Agent's own events are on its stream, not the session's. Read them with
`client.agents.events(id, { from, types, since, until })`
(`GET /v1/agents/{id}/events`); `AGENT_EVENT_TYPES` lists the types. These
carry the most:

| Event                                                                           | Payload                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| ------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `agent.created`                                                                 | `kind`, `labels`, `manifest` (`{ name, version, tracking }`), and `forkedFrom` (`{ agent, disk }`, the source and its disk version) when it is a fork.                                                                                                                                                                                                                                                                                                    |
| `agent.forked`                                                                  | On the source of a fork: `to`, the new Agent; `disk`, the disk version it started from (`null` for an empty disk); `manifest` (`{ name, version }`); and `secrets`, how many secrets were copied.                                                                                                                                                                                                                                                         |
| `agent.outdated`                                                                | It was asked to move from version `from` to `to`, which waits: `waitingFor` is `secrets` (a required secret the new version adds) or `start` (a pod's next start).                                                                                                                                                                                                                                                                                        |
| `agent.version_changed`                                                         | It moved from version `from` to `to`: turns that start from here run `to`.                                                                                                                                                                                                                                                                                                                                                                                |
| `agent.start_failed`                                                            | Its pod did not start on version `to`: `reason`, and `reverted` when it went back to `from` with its disk as it was.                                                                                                                                                                                                                                                                                                                                      |
| `agent.egress`                                                                  | One connection a pod Agent's sandbox opened: `agentId`, `host`, `port`, `outcome` (`allowed` or `refused`), `reason` and `status` for a refusal, `mode` (`tunnel`, or `credential` for a host a secret is bound to), `credentialBound`, `bytesUp`, `bytesDown`, `startedAt`, `durationMs`, and `runningTurns`, the turns (`{ sessionId, turnId }`, at most 16) running on the Agent when it opened. It never holds a header value, a URL path, or a body. |
| `agent.run`                                                                     | A [trigger](/docs/run/triggers#runs) fired or was run by hand: `runId`, `triggerId`, `dueAt`, `late`, `status`, `reason`, and `sessionId`.                                                                                                                                                                                                                                                                                                                |
| `agent.trigger_paused`, `agent.trigger_resumed`, `agent.trigger_secret_rotated` | `triggerId`, and for a pause its `reason`.                                                                                                                                                                                                                                                                                                                                                                                                                |
| `agent.memory_updated`                                                          | A turn changed its [memories](/docs/run/memory): `memory.updated`'s payload with `sessionId` and `turnId`.                                                                                                                                                                                                                                                                                                                                                |

Sessions on one Agent run turns at the same time, so a connection belongs to
the Agent, not to one turn. To see what a turn reached, read `agent.egress`
with `since` and `until` around the turn and match `runningTurns`. See
[Egress records](/docs/run/agents#egress-records).

## Next step [#next-step]

<Cards>
  <Card title="Traces" description="Read a turn as an OpenTelemetry trace." href="/docs/run/traces" />

  <Card title="Pauses and control" description="Cancel a turn and resolve pauses." href="/docs/run/control" />
</Cards>
