# Sessions (/docs/run/sessions)



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

const client = await createClient();
const session = await client.createSession({
  agent: "assistant",
  ownerUserId: authenticatedUser.id,
});

await session.input("Look up order demo-123", {
  idempotencyKey: requestId,
});
```

`createClient()` resolves a connection in this order:

1. Explicit `{ url, key }`
2. `NYLORUN_RUNTIME_URL` and `NYLORUN_SERVER_KEY` (both must be set)
3. The project link that `nylorun start` wrote

There is no `tenant` option. Failure is `ConnectionError` (`connection_missing`).

A deployed backend can pass the destination explicitly:

```ts
const client = createClient({
  url: process.env.NYLORUN_RUNTIME_URL!,
  key: process.env.NYLORUN_SERVER_KEY!,
});
```

| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| `url` | `string \| undefined` | No | Runtime URL. |
| `key` | `string \| undefined` | No | Application key. |
| `fetch` | `((input: RequestInfo \| URL, init?: RequestInit) => Promise<Response>) \| undefined` | No | Custom fetch implementation. |
| `token` | `TokenSource \| undefined` | No | A trusted issuer's tokens, instead of `key`. |

`ownerUserId` comes from your own sign-in. Retry the same command with the same
`idempotencyKey`; changed content under the same key answers `409`.

## Input [#input]

Strings become text. Other JSON becomes structured input. File parts are
`{ type: "file", artifactId }`; see [Files](/docs/run/files). Any file may be
sent, within the Tenant's artifact limits: the session's harness decides how
its model sees each one. See
[What the model reads](/docs/run/files#what-the-model-reads).

```ts
await session.input({ repository: "acme/app", pullRequest: 117 }, {
  idempotencyKey: requestId,
});
```

### Leave tools out of a turn [#leave-tools-out-of-a-turn]

`removeTools` names the tools a message's turn may not use (Host feature
`remove-tools`):

```ts
await session.input("Summarise the open issues", {
  idempotencyKey: requestId,
  removeTools: ["deploy", "github__delete_repo", "billing"],
});
```

| Name                          | Removes                                                                                                                                                                                                          |
| ----------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `deploy`                      | The declared tool, or agent used as a tool, of that name, in the agent and in the agents it uses as tools.                                                                                                       |
| `github__delete_repo`         | One MCP server's tool: the server's name and the tool's own name on it.                                                                                                                                          |
| `billing`                     | Every tool of the MCP server `billing`.                                                                                                                                                                          |
| `nylorun__memory` or `memory` | A [Runtime plugin's](/docs/build/agent-manifests#the-runtimes-plugins) tool, by the name the model reads or by its own name, the one events show. Runtime 0.47 and later; an older Runtime ignores the own name. |

The Runtime applies it after the turn moves the session to its Agent's current
version, so a session that sends it with every message still moves to new
versions. A name that version doesn't have is ignored. It only narrows, so any
caller may send it, a token caller included. The `command.message` event
records it. The SDK checks the Host feature first and throws
`IncompatibleRuntimeError` without sending when the Runtime lacks it.

Over A2A, a new message carries the same list as `metadata.removeTools`
(Runtime 0.40 or later); [`createA2aClient`](/docs/a2a/client)'s `send()`
takes `removeTools`.

## Session options [#session-options]

`createSession` takes `agent` and `ownerUserId`, and also accepts `id`, `info`,
and `requestId`. `agent` names the [Agent](/docs/run/agents) the session runs
on: its manifest version, its sandbox, and its secrets. It is fixed once the
session exists.

| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| `agent` | `string` | Yes | The Agent the session runs on: its manifest version, its sandbox, and its secrets. Fixed once the session exists. |
| `ownerUserId` | `string` | Yes | The person who owns the session. Set by your server. |
| `id` | `string \| undefined` | No | Session id. Generated when omitted. |
| `info` | `Record<string, unknown> \| undefined` | No | Application data stored with the session when it is created. |
| `requestId` | `string \| undefined` | No | Request id sent with the `PUT`. Generated when omitted. |

No session is special: to keep one conversation going, reuse a session id you
choose.

```ts
const session = await client.createSession({
  id: `support-${authenticatedUser.id}`,
  agent: `users/${authenticatedUser.id}/support`,
  ownerUserId: authenticatedUser.id,
});
```

## Messages while a turn runs [#messages-while-a-turn-runs]

A message sent while the session's turn runs, or while it waits on an
approval, an answer, or an uncertain call, waits in the session's queue.
`input()` answers `{ status: "queued", queuedMessageId, position }` instead of
`{ status: "accepted", turnId }`, and the session writes `message.queued`.

```ts
const answer = await session.input("And the second order?", {
  idempotencyKey: crypto.randomUUID(),
});
if (answer.status === "queued") {
  console.log(`Queued at ${answer.position}: ${answer.queuedMessageId}`);
}
```

When the turn ends, completed, failed, or cancelled, the next turn takes every
queued message in order, each as its own user message, and the session writes
`queue.taken`. A flow session takes one queued message per turn. A cancel ends
the turn, not the queue. `session.inspect()` counts the waiting messages in
`queuedMessages`.

A session holds at most the Runtime limit `sessionQueuedMessages` (100 by
default; see [Runtime limits](/docs/run/limits)). One more message is
`429 queue_full`.

Queued messages never wait for good (Host feature `queue-recovery`). When the
Agent refuses the next turn's start, because its disk is being copied, its pod
was lost, or it was deleted, the Runtime tries the start again. Messages that
have waited past the Runtime limit `queuedStartMs` (15 minutes by default) are
removed with `queue.failed` (`error.code` `queue.start_expired`, and the
refusal's own code as `error.reason`). A refusal no retry changes, such as a turn
request the new version no longer resolves, fails them at once
(`queue.start_refused`), and the messages behind them are tried next.

To be refused instead of queued, send `delivery: "reject"`. A busy session then
answers `409 session_busy` and queues nothing:

```ts
await session.input("Only if you are free", {
  idempotencyKey: crypto.randomUUID(),
  delivery: "reject",
});
```

The CLI does the same with `nylorun sessions send <id> <text> --reject-if-busy`.

### Steer a running turn [#steer-a-running-turn]

To have the running turn read a message before its next step, instead of after
the turn ends, send `delivery: "steer"` (Host feature `steer`, Runtime 0.43).
The message waits in the queue marked `steer`, and the answer says so:

```ts
const answer = await session.input("Only the first three sections", {
  idempotencyKey: crypto.randomUUID(),
  delivery: "steer",
});
// { status: "queued", delivery: "steer", queuedMessageId, position }
```

Before each step after the first, the agent takes the steered messages. The
model reads them after the tool results it is about to see. The session writes
each one's `command.message` under the running turn, then `queue.taken` with
the `step`. A tool call that is already running finishes first. A steer the
turn doesn't take, because the model had already started its final answer,
starts the next turn like any queued message, so none is lost. A flow session
can't take a steer: it queues the message and answers `delivery: "queue"`.
On an idle session, a steered message starts a turn as any message does.

Messages from [triggers and wakes](/docs/run/triggers) go through the same
queue. AG-UI runs on a busy session are refused (`session_busy`). An A2A
message to a busy context is queued; see [Profile v2](/docs/a2a/profile/v2#the-rules).
Studio's message box is read-only while a turn runs.

## Errors [#errors]

| Code                   | Status | When                                                                                                                                   |
| ---------------------- | ------ | -------------------------------------------------------------------------------------------------------------------------------------- |
| `not_found`            | `404`  | Open: no Agent has that id. Acting for a person, also when it is out of reach or its owner guard names someone else.                   |
| `agent_owner_mismatch` | `403`  | Open or turn start: the Agent's `owner` names another owner. See [Owner guard](/docs/run/agents#owner-guard).                          |
| `agent_not_granted`    | `403`  | Turn start: a trusted issuer's token no longer reaches the Agent.                                                                      |
| `agent_busy`           | `409`  | Turn start: a snapshot or restore is copying the Agent's disk. Retry after `Retry-After`.                                              |
| `agent_unavailable`    | `409`  | The Agent was deleted, or it is a pod Agent and the Runtime has no sandbox pods.                                                       |
| `agent_lost`           | `409`  | Turn start: a pod's volume or node is gone. Reset the Agent.                                                                           |
| `placement_refused`    | `409`  | Open: the Tenant's placement keeps the session's harness off the host its Agent needs.                                                 |
| `harness_mismatch`     | `409`  | Turn start: the Agent id was deleted and made again with another harness than the one the session pinned. Open a new session.          |
| `limit_exceeded`       | `413`  | Open: a skill of the Agent's manifest holds more bytes than the Agent's skill limit allows.                                            |
| `session_closed`       | `409`  | A message, approval, or answer: the session was opened before protocol 16. Its history stays readable; open a new session on an Agent. |
| `session_busy`         | `409`  | A message sent with `delivery: "reject"` while a turn runs or waits. See [Messages while a turn runs](#messages-while-a-turn-runs).    |
| `queue_full`           | `429`  | A message to a session whose queue holds `sessionQueuedMessages` messages.                                                             |

## Continue and inspect [#continue-and-inspect]

| Helper                                                                                  | Purpose                                                                                                                                                                                                                                                             |
| --------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `client.session(id)`                                                                    | Reattach to an existing session.                                                                                                                                                                                                                                    |
| `client.listSessions({ agentId? })`                                                     | List sessions, or those on one Agent.                                                                                                                                                                                                                               |
| `client.sessions.page({ agentId?, manifest?, status?, ownerUserId?, limit?, cursor? })` | Page sessions, newest first, filtered by Agent, agent manifest, status, or owner.                                                                                                                                                                                   |
| `session.input(value, { idempotencyKey, delivery?, removeTools? })`                     | Start a turn, or queue or steer a message while one runs.                                                                                                                                                                                                           |
| `session.inputParts(parts, { idempotencyKey, delivery?, removeTools? })`                | Send text and file parts.                                                                                                                                                                                                                                           |
| `session.approve(id, approved, { idempotencyKey? })`                                    | Resolve an approval. See [Tool policy](/docs/run/tool-policy#approve-a-held-call).                                                                                                                                                                                  |
| `session.respond(id, value, { idempotencyKey? })`                                       | Resolve a request for input.                                                                                                                                                                                                                                        |
| `session.cancel({ idempotencyKey })`                                                    | Cancel the active turn.                                                                                                                                                                                                                                             |
| `session.history({ cursor?, agent? })`                                                  | Page canonical history.                                                                                                                                                                                                                                             |
| `session.observe({ cursor?, follow?, idleTimeoutMs? })`                                 | Live events, reconnecting after `idleTimeoutMs` (45 s) without bytes.                                                                                                                                                                                               |
| `session.inspect()`                                                                     | Snapshot of status, waits, `agentId`, `manifest`, `harness`, `manifestHash`, and `queuedMessages`.                                                                                                                                                                  |
| `session.pending()`                                                                     | Open interactions.                                                                                                                                                                                                                                                  |
| `session.usage({ turnId? })`                                                            | The session's recorded model usage: tokens and cost, or one turn's, with the cost by token kind (`costSplit`, over `splitCalls` calls) and the calls' time (`modelTimeMs`, over `timedCalls` calls). See [Models](/docs/run/models#a-sessions-usage-by-token-kind). |
| `session.toolCalls({ turnId?, limit?, cursor? })`                                       | The session's tool calls: tool, input, status, sends, and timing.                                                                                                                                                                                                   |
| `session.modelCalls({ turnId?, limit?, cursor? })`                                      | The session's model calls and their usage, each with `startedAt`, `endedAt`, and `usage.costSplit`.                                                                                                                                                                 |
| `session.trace(turnId)`                                                                 | One turn as OpenTelemetry spans. See [Traces](/docs/run/traces).                                                                                                                                                                                                    |
| `session.manifest()`                                                                    | The manifest the session's harness runs.                                                                                                                                                                                                                            |
| `session.command()`                                                                     | Send a raw session command, including a per-turn manifest.                                                                                                                                                                                                          |

Every command takes an idempotency key. `approve` and `respond` make one when
you pass none; pass your own to retry the same answer safely.

`GET /v1/sessions/{id}` (`session.inspect()`) returns `agentId`, the Agent the
session runs on, and `manifest` as `{ name, version }`: the agent manifest
version its latest turn ran. Each turn takes the version its Agent runs when
the turn starts, so a session moves with its Agent between turns. A flow
session keeps the version it opened on, as does a turn sent with its own turn
manifest. `manifestHash` hashes the manifest the session runs, `harness` is the
harness it pinned when it opened (its manifest's `harness.id`, else
`nylorun`), `queuedMessages` counts its queue, and `closedReason` says why a
closed session takes no turn.

`session.manifest()` (`GET /v1/sessions/{id}/manifest`) returns
`{ sessionId, agentId, definition: { name, version }, manifestHash, manifest }`:
`manifest` is that version's harness section as the harness runs it.

## Next step [#next-step]

<Cards>
  <Card title="Events" description="Read history and stream live progress." href="/docs/run/events" />

  <Card title="Agents" description="Give the session a sandbox and secrets." href="/docs/run/agents" />
</Cards>
