> ## Documentation Index
> Fetch the complete documentation index at: https://www.truefoundry.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Runtime API reference

> SDK methods for sessions and turns — AgentSessionClient, prepareTurn, execute, stream, listEvents — plus turn input types.

For a guided walkthrough, see [SDK overview](/docs/agent-platform/agent-harness/sdk/overview).

## Turn input

Each Turn's `input` is a list of one of these types. Resuming a Turn paused by [`mcp.auth_required`](/docs/agent-platform/agent-harness/sdk/turn-events-reference#mcpauthrequiredevent) needs no input - omit `input` or pass `[]`.

<Note>
  User messages (`UserMessage`) cannot be mixed with tool approvals or client-side tool responses in the same `input` list. `UserToolApprovalEvent` and `UserToolResponseEvent` may be mixed together.
</Note>

### UserMessage

Start a new conversation or send the next user message. `content` is either a plain string or a list of content parts, letting you attach files alongside text.

```json lines theme={"dark"}
{ "type": "user.message", "content": "I would like to file a support ticket." }
```

```json lines theme={"dark"}
{
    "type": "user.message",
    "content": [
        { "type": "text", "text": "Please review this document." },
        {
            "type": "file",
            "name": "report.pdf",
            "data": "data:application/pdf;base64,JVBERi0xLjQK..."
        }
    ]
}
```

| Field     | Type                                 | Required | Description                                                                               |
| --------- | ------------------------------------ | -------- | ----------------------------------------------------------------------------------------- |
| `type`    | `"user.message"`                     | Yes      |                                                                                           |
| `content` | string \| `UserMessageContentItem[]` | Yes      | The message text, or a list of [content parts](#usermessagecontentitem) (text and files). |

#### UserMessageContentItem

A content part is one of:

**Text**

| Field  | Type     | Required | Description       |
| ------ | -------- | -------- | ----------------- |
| `type` | `"text"` | Yes      |                   |
| `text` | string   | Yes      | The message text. |

**File**

| Field  | Type     | Required | Description                                                                 |
| ------ | -------- | -------- | --------------------------------------------------------------------------- |
| `type` | `"file"` | Yes      |                                                                             |
| `name` | string   | Yes      | Name of the uploaded file.                                                  |
| `data` | string   | Yes      | Data URI: `data:<mime>;base64,<payload>`. MIME type is parsed from the URI. |

***

### UserToolApprovalEvent

Sent to resume a turn paused by [`tool.approval_required`](/docs/agent-platform/agent-harness/sdk/turn-events-reference#toolapprovalrequiredevent). One item per pending tool call.

```json lines theme={"dark"}
{
    "type": "user.tool_approval",
    "thread_id": "main",
    "tool_call_id": "call_restart_billing",
    "approval": { "status": "allow" }
}
```

| Field          | Type                              | Required | Description                                                                                                               |
| -------------- | --------------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------- |
| `type`         | `"user.tool_approval"`            | Yes      |                                                                                                                           |
| `thread_id`    | string                            | Yes      | `thread_id` from the `tool.approval_required` event.                                                                      |
| `tool_call_id` | string                            | Yes      | ID of the tool call being approved or denied.                                                                             |
| `approval`     | `ApprovalAllow` \| `ApprovalDeny` | Yes      | Use `{"status": "allow"}` to permit the call, or `{"status": "deny", "reason": "..."}` to block it. `reason` is optional. |

***

### UserToolResponseEvent

Sent to resume a turn paused by [`tool.response_required`](/docs/agent-platform/agent-harness/sdk/turn-events-reference#toolresponserequiredevent). One item per pending tool call.

```json lines theme={"dark"}
{
    "type": "user.tool_response",
    "thread_id": "main",
    "tool_call_id": "call_a1b2",
    "content": "tfy-prod-us (production)"
}
```

| Field          | Type                   | Required | Description                                          |
| -------------- | ---------------------- | -------- | ---------------------------------------------------- |
| `type`         | `"user.tool_response"` | Yes      |                                                      |
| `thread_id`    | string                 | Yes      | `thread_id` from the `tool.response_required` event. |
| `tool_call_id` | string                 | Yes      | ID of the tool call whose result is being supplied.  |
| `content`      | string                 | Yes      | The result to return to the agent.                   |

***

## Reference

<Note>
  The signatures below document the **low-level** generated client (`TrueFoundryGateway` → `client.agents.sessions.*`). For application code, prefer the high-level [`AgentSessionClient`](#python-reference) / [`AgentSessionClient`](#typescript-reference) wrapper from `truefoundry_gateway_sdk.agents` (Python) or `truefoundry-gateway-sdk/agents` (TypeScript) — same `prepare_turn` / `execute` / `Turn` model as the examples in [Use an agent](/docs/agent-platform/agent-harness/sdk/use-agent).
</Note>

## Python reference

```python theme={"dark"}
import os
from truefoundry_gateway_sdk.agents import AgentSessionClient

client = AgentSessionClient(
    base_url=os.environ["TFY_GATEWAY_URL"],
    api_key=os.environ["TFY_API_KEY"],
)
session = client.create_session(agent_name="support-bot")
turn = session.prepare_turn(input=[...])
for data in turn.execute(stream=True):
    print(data.event)
```

| Method                                                  | Description                                          |
| ------------------------------------------------------- | ---------------------------------------------------- |
| `create_session(agent_name)`                            | Create a session                                     |
| `list_sessions(agent_name, ...)`                        | List sessions (newest-first pager)                   |
| `get_session(session_id)`                               | Fetch session by id                                  |
| `session.prepare_turn(input=..., previous_turn_id=...)` | Stage a turn (no HTTP yet)                           |
| `turn.execute(stream=True\|False)`                      | Start turn; stream events or wait for terminal state |
| `turn.refresh()`                                        | Refetch lifecycle state from the server              |
| `turn.wait_for_completion(poll_interval_ms=...)`        | Block until the turn reaches a terminal state        |
| `turn.stream(after_sequence_number=...)`                | Reconnect to a running turn's SSE                    |
| `turn.list_events(order=...)`                           | Merged event log for a completed turn                |
| `turn.cancel()`                                         | Cancel a running turn                                |
| `session.list_turns()`                                  | List turns in the session                            |
| `session.get_turn(turn_id)`                             | Fetch a single turn by id                            |
| `session.cancel()`                                      | Cancel the running turn                              |

Import `is_event_delta`, `merge_event_delta`, and event types from `truefoundry_gateway_sdk.agents`. Import `UserMessage` and content-part types from `truefoundry_gateway_sdk.types`.

***

## Low-level reference (`TrueFoundryGateway`)

```python theme={"dark"}
import os
from truefoundry_gateway_sdk import TrueFoundryGateway

client = TrueFoundryGateway(
    base_url=os.environ["TFY_GATEWAY_URL"],
    api_key=os.environ["TFY_API_KEY"],
)
```

### create

```text lines theme={"dark"}
client.agents.sessions.create(agent_name=...) -> GetSessionResponse
```

Create a conversation [Session](#session) for a saved agent. The returned response wraps the session in `.data`.

| Param        | Type   | Required | Description                        |
| ------------ | ------ | -------- | ---------------------------------- |
| `agent_name` | string | Yes      | Name of the saved agent to invoke. |

***

### list

```text lines theme={"dark"}
client.agents.sessions.list(agent_name=..., limit=10, order=None, page_token=None, start_timestamp=None, end_timestamp=None)
  -> SyncPager[Session, ListSessionsResponse]
```

List [Sessions](#session) for a saved agent, newest-first by default. The pager auto-paginates when iterated.

| Param             | Type                | Required | Description                                                                        |
| ----------------- | ------------------- | -------- | ---------------------------------------------------------------------------------- |
| `agent_name`      | string              | Yes      | Filter to sessions for a specific named agent.                                     |
| `limit`           | int                 | No       | Number of sessions fetched per page (not a total cap).                             |
| `order`           | `"asc"` \| `"desc"` | No       | Sort order by creation time. Defaults to `"desc"`.                                 |
| `page_token`      | string              | No       | Pagination token from a previous page. Usually omitted — iteration handles paging. |
| `start_timestamp` | string              | No       | ISO-8601 lower bound on session creation time.                                     |
| `end_timestamp`   | string              | No       | ISO-8601 upper bound on session creation time.                                     |

***

### get

```text lines theme={"dark"}
client.agents.sessions.get(session_id) -> GetSessionResponse
```

Fetch an existing session by ID. The returned response wraps the session in `.data`.

| Param        | Type   | Required | Description             |
| ------------ | ------ | -------- | ----------------------- |
| `session_id` | string | Yes      | Session ID to retrieve. |

***

### cancel

```text lines theme={"dark"}
client.agents.sessions.cancel(session_id) -> CancelSessionResponse
```

Cancel the running turn for a session. Idempotent.

| Param        | Type   | Required | Description        |
| ------------ | ------ | -------- | ------------------ |
| `session_id` | string | Yes      | Session to cancel. |

***

### Session

The conversation context for a saved agent, returned by [`create`](#create) and [`get`](#get) in `.data`. Turns created within a session are chained automatically, so each turn sees the history of earlier ones. Key members:

| Member               | Type           | Description                                                              |
| -------------------- | -------------- | ------------------------------------------------------------------------ |
| `id`                 | string         | Unique session identifier. Persist it to resume later via [`get`](#get). |
| `agent_name`         | string         | Name of the saved agent this session belongs to.                         |
| `title`              | string \| None | Optional human-readable title for the session.                           |
| `created_by_subject` | `Subject`      | Subject (user / service account) that created this session.              |
| `created_at`         | string         | ISO-8601 timestamp of session creation.                                  |
| `updated_at`         | string         | ISO-8601 timestamp of the last session update.                           |

***

### create\_turn

```text lines theme={"dark"}
client.agents.sessions.create_turn(session_id, input=None, previous_turn_id="auto")
  -> Iterator[TurnStreamingEvent]
```

Start or continue a turn within a session. Responds with a Server-Sent Events stream. The first event is [`turn.created`](/docs/agent-platform/agent-harness/sdk/turn-events-reference#turncreatedevent); the stream closes with [`turn.done`](/docs/agent-platform/agent-harness/sdk/turn-events-reference#turndoneevent).

| Param              | Type                 | Required | Description                                                                                                                                                                              |
| ------------------ | -------------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `session_id`       | string               | Yes      | Session to run the turn in.                                                                                                                                                              |
| `input`            | `TurnInputItem[]`    | No       | Input items for this turn. See [Turn input](#turn-input). Omit to resume after [`mcp.auth_required`](/docs/agent-platform/agent-harness/sdk/turn-events-reference#mcpauthrequiredevent). |
| `previous_turn_id` | `string` \| `"auto"` | No       | Turn chaining point. Defaults to `"auto"`, letting the server chain to the latest turn.                                                                                                  |

***

### list\_turns

```text lines theme={"dark"}
client.agents.sessions.list_turns(session_id, page_token=None, limit=10)
  -> SyncPager[Turn, ListTurnsResponse]
```

List turns in a session, newest-first. The pager auto-paginates when iterated.

| Param        | Type   | Required | Description                                         |
| ------------ | ------ | -------- | --------------------------------------------------- |
| `session_id` | string | Yes      | Session to list turns for.                          |
| `page_token` | string | No       | Pagination token from a previous page.              |
| `limit`      | int    | No       | Number of turns fetched per page (not a total cap). |

***

### get\_turn

```text lines theme={"dark"}
client.agents.sessions.get_turn(session_id, turn_id) -> GetTurnResponse
```

Fetch a single turn by ID. The returned response wraps the turn in `.data`.

| Param        | Type   | Required | Description                  |
| ------------ | ------ | -------- | ---------------------------- |
| `session_id` | string | Yes      | Session the turn belongs to. |
| `turn_id`    | string | Yes      | Turn ID to retrieve.         |

***

### Turn

A single request/response cycle within a session, returned by [`list_turns`](#list_turns) and [`get_turn`](#get_turn) in `.data`. Transitions: `running` → `done` | `cancelled` | `error`.

| Member               | Type                      | Description                                                                                                |
| -------------------- | ------------------------- | ---------------------------------------------------------------------------------------------------------- |
| `id`                 | string                    | Unique turn identifier (UUIDv7).                                                                           |
| `session_id`         | string                    | The session this turn belongs to.                                                                          |
| `previous_turn_id`   | string \| None            | Turn ID this turn chains from, or `None` for the first turn.                                               |
| `created_by_subject` | `Subject`                 | Subject (user / service account) that created this turn.                                                   |
| `created_at`         | string                    | ISO-8601 timestamp of turn creation.                                                                       |
| `input`              | `TurnInputItem[]` \| None | The [Turn input](#turn-input) that triggered this turn, if any.                                            |
| `state`              | `TurnState`               | Cached lifecycle state (`running`, `done`, `cancelled`, or `error`). Refetch with [`get_turn`](#get_turn). |

***

### subscribe\_to\_turn

```text lines theme={"dark"}
client.agents.sessions.subscribe_to_turn(session_id, turn_id, after_sequence_number=None)
  -> Iterator[TurnStreamingEvent]
```

Reconnect to a running turn's live SSE stream. Pass `after_sequence_number` to resume after a known point. Closes when the turn reaches a terminal state. Use [`list_turn_events`](#list_turn_events) for completed turns.

| Param                   | Type   | Required | Description                        |
| ----------------------- | ------ | -------- | ---------------------------------- |
| `session_id`            | string | Yes      | Session the turn belongs to.       |
| `turn_id`               | string | Yes      | Turn to subscribe to.              |
| `after_sequence_number` | int    | No       | Resume after this sequence number. |

***

### list\_turn\_events

```text lines theme={"dark"}
client.agents.sessions.list_turn_events(session_id, turn_id, page_token=None, limit=25, order=None)
  -> SyncPager[TurnEvent, ListEventsResponse]
```

Return a paginated snapshot of stored events for a completed turn. Pass `order="asc"` to replay forward. The pager auto-paginates when iterated.

| Param        | Type                | Required | Description                                          |
| ------------ | ------------------- | -------- | ---------------------------------------------------- |
| `session_id` | string              | Yes      | Session the turn belongs to.                         |
| `turn_id`    | string              | Yes      | Turn whose events to list.                           |
| `page_token` | string              | No       | Pagination token from a previous page.               |
| `limit`      | int                 | No       | Number of events fetched per page (not a total cap). |
| `order`      | `"asc"` \| `"desc"` | No       | Sort order by sequence number. Defaults to `"asc"`.  |

***

## TypeScript reference

Import the high-level client from `truefoundry-gateway-sdk/agents`. Method names below use camelCase; [Turn input](#turn-input) JSON shapes are the same in every language.

```typescript theme={"dark"}
import { AgentSessionClient } from "truefoundry-gateway-sdk/agents";

const client = new AgentSessionClient({
  apiKey: process.env.TFY_API_KEY!,
  baseUrl: process.env.TFY_GATEWAY_URL!,
});
```

### createSession

```text lines theme={"dark"}
client.createSession({ agentName, title? }) -> Promise<AgentSession>
```

Create a conversation [`AgentSession`](#agentsession) for a saved agent.

| Param       | Type   | Required | Description                                    |
| ----------- | ------ | -------- | ---------------------------------------------- |
| `agentName` | string | Yes      | Name of the saved agent to invoke.             |
| `title`     | string | No       | Optional human-readable title for the session. |

***

### listSessions

```text lines theme={"dark"}
client.listSessions({ agentName, startTimestamp?, endTimestamp?, limit?, order?, pageToken? })
  -> Promise<Page<AgentSession>>
```

List [`AgentSession`](#agentsession) objects for a saved agent, newest-first. The returned `Page` is async-iterable and auto-paginates.

| Param            | Type                | Required | Description                                                                        |
| ---------------- | ------------------- | -------- | ---------------------------------------------------------------------------------- |
| `agentName`      | string              | Yes      | Filter to sessions for a specific named agent.                                     |
| `startTimestamp` | string              | No       | ISO-8601 lower bound on session creation time.                                     |
| `endTimestamp`   | string              | No       | ISO-8601 upper bound on session creation time.                                     |
| `limit`          | number              | No       | Number of sessions fetched per page (not a total cap).                             |
| `order`          | `"asc"` \| `"desc"` | No       | Sort order by creation time. Defaults to `"desc"`.                                 |
| `pageToken`      | string              | No       | Pagination token from a previous page. Usually omitted — iteration handles paging. |

***

### getSession

```text lines theme={"dark"}
client.getSession({ sessionId }) -> Promise<AgentSession>
```

Fetch an existing session by ID.

| Param       | Type   | Required | Description             |
| ----------- | ------ | -------- | ----------------------- |
| `sessionId` | string | Yes      | Session ID to retrieve. |

***

### AgentSession

The conversation context for a saved agent. Turns created within a session are chained automatically. Key members:

| Member                | Type                | Description                                                                                                                                                                                                                                     |
| --------------------- | ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `id`                  | string              | Unique session identifier. Persist it to resume later via `client.getSession({ sessionId })`.                                                                                                                                                   |
| `agentName`           | string              | Name of the saved agent this session belongs to.                                                                                                                                                                                                |
| `title`               | string \| undefined | Optional human-readable title for the session.                                                                                                                                                                                                  |
| `createdBySubject`    | `Subject`           | Subject (user / service account) that created this session.                                                                                                                                                                                     |
| `createdAt`           | string              | ISO-8601 timestamp of session creation.                                                                                                                                                                                                         |
| `updatedAt`           | string              | ISO-8601 timestamp of the last session update.                                                                                                                                                                                                  |
| `prepareTurn(...)`    | method              | Stage a turn locally and return a [`PreparedTurn`](#preparedturn) with no network call. Start it with `execute({ stream: true })` (stream events) or `execute({ stream: false })` (wait for terminal state). See [`prepareTurn`](#prepareturn). |
| `listTurns(...)`      | method              | Return a `Page<Turn>` of turns in this session (default order: newest-first). Async-iterate the page to walk every turn.                                                                                                                        |
| `getTurn({ turnId })` | method              | Fetch a single [`Turn`](#turn) by ID.                                                                                                                                                                                                           |
| `cancel()`            | method              | Cancel the session and any currently running turn. Idempotent.                                                                                                                                                                                  |

***

### prepareTurn

```text lines theme={"dark"}
session.prepareTurn({ input?, previousTurnId? }) -> PreparedTurn
```

Stage a turn in the session. Makes no network call and returns a [`PreparedTurn`](#preparedturn) with no `id` yet. The turn is created server-side on the first `execute()` call:

* `execute({ stream: true })` — POST createTurn and stream the SSE response as `{ sequenceNumber, event }` data objects.
* `execute({ stream: false, pollIntervalMs? })` — POST createTurn without streaming, then poll until the turn reaches a terminal state.

After `execute()` starts the turn, call `stream()`, `refresh()`, `waitForCompletion()`, `listEvents()`, or `cancel()` on the same object. Calling those methods before `execute()` raises.

| Param            | Type                 | Required | Description                                                                                                                                                                              |
| ---------------- | -------------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `input`          | `TurnInputItem[]`    | No       | Input items for this turn. See [Turn input](#turn-input). Omit to resume after [`mcp.auth_required`](/docs/agent-platform/agent-harness/sdk/turn-events-reference#mcpauthrequiredevent). |
| `previousTurnId` | `string` \| `"auto"` | No       | Turn chaining point. Defaults to `"auto"`.                                                                                                                                               |

***

### PreparedTurn

Output of `prepareTurn()`. Not yet started — no HTTP until `execute()`. Identity fields delegate to the inner `Turn` once started (undefined until then).

| Member                                        | Type                           | Description                                                                                                                                                                 |
| --------------------------------------------- | ------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `id`                                          | string \| undefined            | Turn ID. Undefined until `execute()` starts the turn.                                                                                                                       |
| `session`                                     | `AgentSession`                 | The session this turn belongs to.                                                                                                                                           |
| `previousTurnId`                              | string \| undefined            | Turn ID this turn chains from. Undefined until started.                                                                                                                     |
| `createdBySubject`                            | `Subject` \| undefined         | Subject that created this turn. Undefined until started.                                                                                                                    |
| `createdAt`                                   | string \| undefined            | ISO-8601 timestamp of turn creation. Undefined until started.                                                                                                               |
| `input`                                       | `TurnInputItem[]` \| undefined | The [Turn input](#turn-input) passed to `prepareTurn()`, if any.                                                                                                            |
| `state`                                       | `TurnState` \| undefined       | Cached lifecycle state. Undefined until started; use `refresh()` to refresh.                                                                                                |
| `execute({ stream: true })`                   | method                         | Start the turn and stream SSE data until terminal. Returns `AsyncIterable<TurnStreamData>`. Each item has `{ sequenceNumber, event }`.                                      |
| `execute({ stream: false, pollIntervalMs? })` | method                         | Start the turn without streaming and block until terminal. Returns `Promise<TurnState>`. Default poll interval is 3000 ms (minimum 3000 ms).                                |
| `stream({ afterSequenceNumber? })`            | method                         | Reconnect to a running turn's live SSE stream after `execute()` has started it. Yields the same `{ sequenceNumber, event }` shape. Raises if the turn has not been started. |
| `refresh()`                                   | method                         | Refetch lifecycle state from the server and return `this`. Raises if the turn has not been started.                                                                         |
| `waitForCompletion({ pollIntervalMs? })`      | method                         | Block until the turn reaches a terminal state. Raises if the turn has not been started.                                                                                     |
| `listEvents(...)`                             | method                         | Return a paginated snapshot of stored events. Async-iterate the returned `Page`. Raises if the turn has not been started.                                                   |
| `cancel()`                                    | method                         | Request cancellation. Raises if the turn has not been started.                                                                                                              |

***

### Turn

A started turn returned by `listTurns()`, `getTurn()`, or after `PreparedTurn.execute()`. Same methods as [`PreparedTurn`](#preparedturn) except there is no `execute()` — the turn already exists server-side.

| Member                                   | Type                           | Description                                                                                                                                |
| ---------------------------------------- | ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------ |
| `id`                                     | string                         | Unique turn identifier (UUIDv7).                                                                                                           |
| `session`                                | `AgentSession`                 | The session this turn belongs to.                                                                                                          |
| `previousTurnId`                         | string \| undefined            | Turn ID this turn chains from, or undefined for the first turn.                                                                            |
| `createdBySubject`                       | `Subject`                      | Subject (user / service account) that created this turn.                                                                                   |
| `createdAt`                              | string                         | ISO-8601 timestamp of turn creation.                                                                                                       |
| `input`                                  | `TurnInputItem[]` \| undefined | The [Turn input](#turn-input) that triggered this turn, if any.                                                                            |
| `state`                                  | `TurnState`                    | Cached lifecycle state (`running`, `done`, `cancelled`, or `error`). Updated in place by `stream()` and `refresh()`.                       |
| `stream({ afterSequenceNumber? })`       | method                         | Subscribe to the turn's live SSE stream. Resumes after `afterSequenceNumber` (default `0`). Closes when the turn reaches a terminal state. |
| `refresh()`                              | method                         | Refetch state from the server and return `this`.                                                                                           |
| `waitForCompletion({ pollIntervalMs? })` | method                         | Block until terminal. Returns immediately if already terminal.                                                                             |
| `listEvents(...)`                        | method                         | Paginated snapshot of stored events. Pass `order: "asc"` to replay forward.                                                                |
| `cancel()`                               | method                         | Request cancellation. Idempotent on terminal turns.                                                                                        |

***

To define or configure the agent itself, see [Create an agent](/docs/agent-platform/agent-harness/sdk/create-agent).
