# client (/docs/reference/agents/client)



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

Guides: [Sessions](/docs/run/sessions), [Events](/docs/run/events),
[App server](/docs/deploy/app-server).

## `createClient` [#createclient]

```ts
createClient(destination: Destination): AgentsClient
createClient(): Promise<AgentsClient>
```

Creates a Tenant API client. With a destination it returns synchronously. With
no argument it resolves the connection (environment, then the nearest project
link) and returns a promise.

| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| `url` | `string \| undefined` | No | Runtime URL. |
| `key` | `string \| undefined` | No | Application or executor key. |
| `tenant` | `string \| undefined` | No | Tenant id. |
| `fetch` | `((input: RequestInfo \| URL, init?: RequestInit) => Promise<Response>) \| undefined` | No | Custom fetch implementation. |

`url`, `key`, and `tenant` are optional in the type. When a destination is
passed, each one must be set here or in `NYLORUN_RUNTIME_URL`,
`NYLORUN_SERVER_KEY`, or `NYLORUN_TENANT`.

**Throws** `ConnectionError` (`connection_missing`) when no complete source is
found. The first call checks `/health`; version skew throws
`IncompatibleRuntimeError`.

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

## `resolveConnection` [#resolveconnection]

```ts
resolveConnection(options?: { url?, tenant?, key?, cwd? }): Promise<ResolvedConnection>
```

Returns `{ url, tenant, key, role, source }` using the same order as
`createClient()`: explicit options, then environment, then project link.
Sources never mix. `role` is `"executor"` when `NYLORUN_EXECUTOR_KEY` is used.

## `AgentsClient` [#agentsclient]

| Method                                                                                             | HTTP                           | Returns           |
| -------------------------------------------------------------------------------------------------- | ------------------------------ | ----------------- |
| `as(subject, { scopes? })`                                                                         | none                           | `AgentsClient`    |
| `saveAgent(runnable, options)`                                                                     | `PUT /v1/agents/:id`           | saved definition  |
| `listAgents()`                                                                                     | `GET /v1/agents`               | agent summaries   |
| `createSession(options)`                                                                           | `PUT /v1/sessions/:id`         | `SessionClient`   |
| `listSessions()`                                                                                   | `GET /v1/sessions`             | session summaries |
| `session(id)`                                                                                      | none                           | `SessionClient`   |
| `hostFeatures()`                                                                                   | `GET /health`                  | `string[]`        |
| `createVault` / `listVaults` / `getVault` / `deleteVault`                                          | `/v1/vaults/…`                 | vault info        |
| `createCredential` / `listCredentials` / `getCredential` / `rotateCredential` / `deleteCredential` | `/v1/vaults/:id/credentials/…` | credential info   |

### `createSession` [#createsession]

| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| `agentId` | `string` | Yes | Agent or workflow id. |
| `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 | Session info available to hooks and tools. |
| `vaultIds` | `readonly string[] \| undefined` | No | End-user vaults to attach. |
| `credentialSelections` | `readonly { serverName: string; credentialId: string; }[] \| undefined` | No | Which credentials to use. |
| `sandbox` | `{ session: string; } \| undefined` | No | Share another session's sandbox. |
| `requestId` | `string \| undefined` | No | Request id sent with the `PUT`. Generated when omitted. |

### `as` [#as]

```ts
client.as(subject: string, options?: { scopes?: SubjectScope[] }): AgentsClient
```

Returns a copy of the client that acts for one person. Every call, event
streams included, sends `Nylorun-Subject` and `Nylorun-Scopes`, and the Runtime
limits it to those scopes and to the subject's own sessions and vaults.

| Parameter        | Type             | Default            | Description                                                             |
| ---------------- | ---------------- | ------------------ | ----------------------------------------------------------------------- |
| `subject`        | `string`         | none               | 1–200 visible ASCII characters; spaces only inside. `host` is reserved. |
| `options.scopes` | `SubjectScope[]` | `["sessions:own"]` | What the subject may do.                                                |

| Scope             | Allows                                                                                   |
| ----------------- | ---------------------------------------------------------------------------------------- |
| `sessions:own`    | The person's own sessions: create, list, read, stream, message, approve, respond, cancel |
| `vaults:own`      | The person's own vaults and credentials                                                  |
| `agents:read`     | Listing the Tenant's agents                                                              |
| `agents:write`    | Saving agents; listing agents, models, and providers                                     |
| `tenant:settings` | The Tenant's status, model provider, and sandbox settings                                |

**Throws** `TypeError` for an invalid subject or scope, and `Error` when the
client already acts for a subject. At request time, another person's session
or vault answers `404`; a route outside the scopes answers `403`
(`scope_required`); an executor key answers `403`. No scope reaches Tenant
reset, config seed, executors, actions, or sandbox tool routes; call those
without `as()`. Requires the Runtime feature `subject-headers`.

## `SessionClient` [#sessionclient]

| Method                                                 | Description                                                                        |
| ------------------------------------------------------ | ---------------------------------------------------------------------------------- |
| `input(value, { idempotencyKey })`                     | Start a turn. Strings become `message.content`; other JSON becomes `message.data`. |
| `approve(interactionId, approved, { idempotencyKey })` | Resolve an approval.                                                               |
| `respond(interactionId, value, { idempotencyKey })`    | Resolve a request for input.                                                       |
| `cancel({ idempotencyKey, reason? })`                  | Cooperatively cancel the active turn.                                              |
| `history({ cursor?, agent?, signal? })`                | Page canonical history (`GET /v1/sessions/:id/items`).                             |
| `observe({ cursor?, follow?, signal? })`               | Async iterator over live events. `follow` merges linked workflow child sessions.   |
| `inspect()`                                            | Snapshot of status, waits, outstanding actions, and uncertainty.                   |
| `pending()`                                            | Open interactions.                                                                 |
| `command(command)`                                     | Send a raw session command.                                                        |

Every command needs a stable `idempotencyKey`. Retrying with changed content
under the same key answers `409`. `history({ agent })` filters by
`payload.agent.delegationId` or `payload.agent.path`.

## Errors [#errors]

| Error                      | When                                                    |
| -------------------------- | ------------------------------------------------------- |
| `ConnectionError`          | No complete connection source (`connection_missing`).   |
| `IncompatibleRuntimeError` | Protocol or required-feature mismatch with the Runtime. |
| `RuntimeError`             | Any other non-2xx Runtime response; has `status`.       |

All error codes are in [Errors](/docs/reference/errors).
