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

# Agents and sessions

> Create agents and sessions, send messages at any time, stop turns, and find sessions by your own keys.

An agent is created from one template version and owns one sandbox; a session is an endless conversation inside it. This page covers both from your backend. The examples assume a server SDK client named `client` (Go, Python) or `paddock` (TypeScript), created as in the [quickstart](https://docs.paddock.build/quickstart.md).

## Create an agent

```go Go theme={null}
agent, err := client.Agents.Create(ctx, paddock.AgentCreate{
	Template: "code-maintainer@1",
	Metadata: map[string]string{"teamId": "t_42"},
})
if err != nil {
	return err
}
// Store agent.ID next to your team record.
```

```python Python theme={null}
agent = client.agents.create(template="code-maintainer@1", metadata={"teamId": "t_42"})
# Store agent.id next to your team record.
```

```ts TypeScript theme={null}
const agent = await paddock.agents.create({ template: "code-maintainer@1", metadata: { teamId: "t_42" } });
// Store agent.id next to your team record.
```

* `template` must name an exact version, `name@version`.
* `metadata` is up to 50 string pairs of your own. Lists filter by it.
* Creating returns before the sandbox exists; the sandbox is created the first time a session needs it.

The returned agent carries its effective `model`, its `status` (`sleeping`, `waking`, `awake`, or `unavailable`), its `generation` (see [Capabilities](https://docs.paddock.build/guides/capabilities.md)), the `capabilities` its harness supports, and `sessionCount`. Read it again with `agents.get(id)`, and list agents, filtered by template (`name` or `name@version`) and metadata:

```go Go theme={null}
agent, err := client.Agents.Get(ctx, "agt_01h455vb4pex5vsknk084sn02q")
if err != nil {
	return err
}
fmt.Println(agent.Status, agent.SessionCount)

for a, err := range client.Agents.List(ctx, paddock.AgentList{
	Template: "code-maintainer",
	Metadata: map[string]string{"teamId": "t_42"},
}) {
	if err != nil {
		return err
	}
	fmt.Println(a.ID, a.Template)
}
```

```python Python theme={null}
agent = client.agents.get("agt_01h455vb4pex5vsknk084sn02q")
print(agent.status, agent.session_count)

for a in client.agents.list(template="code-maintainer", metadata={"teamId": "t_42"}):
    print(a.id, a.template)
```

```ts TypeScript theme={null}
const agent = await paddock.agents.get("agt_01h455vb4pex5vsknk084sn02q");
console.log(agent.status, agent.sessionCount);

for await (const a of paddock.agents.list({ template: "code-maintainer", metadata: { teamId: "t_42" } })) {
  console.log(a.id, a.template);
}
```

Deleting an agent ends every running turn, deletes all its sessions with their history, revokes their tokens, and deletes the sandbox with its files:

```go Go theme={null}
err := client.Agents.Delete(ctx, agent.ID)
```

```python Python theme={null}
client.agents.delete(agent.id)
```

```ts TypeScript theme={null}
await paddock.agents.delete(agent.id);
```

## Create a session

```go Go theme={null}
session, err := agent.Sessions.Create(ctx, paddock.SessionCreate{
	Cwd:          "repos/web",
	SystemPrompt: "You are working on Acme's web app.",
	Metadata:     map[string]string{"userId": "u_7"},
})
```

```python Python theme={null}
session = agent.sessions.create(
    cwd="repos/web",
    system_prompt="You are working on Acme's web app.",
    metadata={"userId": "u_7"},
)
```

```ts TypeScript theme={null}
const session = await agent.sessions.create({
  cwd: "repos/web",
  systemPrompt: "You are working on Acme's web app.",
  metadata: { userId: "u_7" },
});
```

Every field is optional:

| Field | Meaning |
| - | - |
| `cwd` | The working directory, relative to the agent's workspace root; default the root, created if missing. The harness runs there for every turn of the session |
| `systemPrompt` | Appended, after a blank line, to the agent's own system prompt; the result is the session's system prompt for its whole life |
| `metadata` | Your own string pairs, to find the session later |

A session's system prompt, environment, and permissions are fixed when it is created; see [Configuration](https://docs.paddock.build/guides/configuration.md). All of an agent's sessions share its sandbox and its files, and each runs its own turns concurrently with the others.

## Send messages

`send` stores a user message and returns once it is stored. It does not wait for the agent to wake or for a turn to start.

```go Go theme={null}
ev, err := session.Send(ctx, "CI failed on main; fix it.")
if err != nil {
	return err
}
fmt.Println("stored as seq", ev.Seq, "message", ev.Message.ID)
```

```python Python theme={null}
from paddock import types

event = session.send("CI failed on main; fix it.")
if isinstance(event, types.MessageEvent):  # a sent message is always a message event
    print("stored as seq", event.seq)
```

```ts TypeScript theme={null}
const event = await session.send("CI failed on main; fix it.");
console.log("stored as seq", event.seq);
```

* **Any time, from anywhere.** Your backend, your frontend, and triggers can all send to one session at any time.
* **In order.** Messages are processed in the order they were stored (their `seq`). A message sent while a turn runs waits; the next turn takes every waiting message together, as one batch.
* **At most 100 KB** of text per message.
* **Never retried automatically.** A failed `send` raises its error; before sending again, look for the message in the session's events, since the first attempt may have been stored.

A user message is **waiting** while its `seq` is above the session's `processedSeq`.

## Stop a turn

`stop` stores a `stop.requested` event and returns it.

```go Go theme={null}
_, err := session.Stop(ctx)
```

```python Python theme={null}
session.stop()
```

```ts TypeScript theme={null}
await session.stop();
```

What it does depends on the session's state:

| State | Effect |
| - | - |
| A turn is running | The turn ends as `stopped`; its input messages count as processed. Background tasks the harness started keep running |
| A retry is planned | The retry is cancelled |
| Messages are waiting | They are held: they start no turn on their own. The next message you send starts a turn that includes them |
| Idle | Nothing changes |

Held messages are those at or below the session's `heldSeq`. A turn that failed and that the agent gave up on holds the waiting messages the same way.

## Read the history

A session's history is its [events](https://docs.paddock.build/concepts.md#event): its messages, turn starts and ends, stops, configuration changes, and its agent's availability. Read them as pages by `seq`:

```go Go theme={null}
page, err := session.Events.List(ctx, paddock.EventList{
	Types: []paddock.EventType{paddock.EventMessage},
	Limit: 100,
})
if err != nil {
	return err
}
for _, ev := range page.Data {
	if m := ev.Message; m != nil && m.Assistant != nil {
		fmt.Println(m.Assistant.Text)
	}
}
```

```python Python theme={null}
from paddock import types

page = session.events.list(types=["message"], limit=100)
for event in page.data:
    if isinstance(event, types.MessageEvent) and isinstance(event.message, types.AssistantMessage):
        print(event.message.text)
```

```ts TypeScript theme={null}
const page = await session.events.list({ types: ["message"], limit: 100 });
for (const event of page.data) {
  if (event.type === "message" && event.message.kind === "assistant") console.log(event.message.text);
}
```

| Option | Meaning |
| - | - |
| `after` | Events with a greater `seq`, ascending |
| `before` | The `limit` events just below it, ascending |
| neither | The latest `limit` events, ascending |
| `types` | Only these event types |
| `limit` | Default 50, at most 200 |

The answer is `{ data, hasMore }`. Turns are also readable as records, with their status, inputs, attempt, error, retry time, and timing:

```go Go theme={null}
for turn, err := range session.Turns.List(ctx, paddock.TurnList{}) {
	if err != nil {
		return err
	}
	fmt.Println(turn.ID, turn.Status, turn.InputSeqs)
}
```

```python Python theme={null}
for turn in session.turns.list():
    print(turn.id, turn.status, turn.input_seqs)
```

```ts TypeScript theme={null}
for await (const turn of session.turns.list()) {
  console.log(turn.id, turn.status, turn.inputSeqs);
}
```

A turn's model usage is in its `turn.ended` event. To follow a session live from your backend, use `session.stream()`; see [Streaming](https://docs.paddock.build/guides/streaming.md#from-your-backend).

## Find sessions by your own keys

paddock does not keep the mapping between your users and sessions; keep it in your own database, or put your keys in a session's metadata and filter by them. `sessions.list` lists every session of the project, newest first, across agents:

```go Go theme={null}
for s, err := range client.Sessions.List(ctx, paddock.ProjectSessionList{
	Metadata: map[string]string{"userId": "u_7"},
}) {
	if err != nil {
		return err
	}
	fmt.Println(s.ID, s.AgentID, s.Status)
}
```

```python Python theme={null}
for s in client.sessions.list(metadata={"userId": "u_7"}):
    print(s.id, s.agent_id, s.status)
```

```ts TypeScript theme={null}
for await (const s of paddock.sessions.list({ metadata: { userId: "u_7" } })) {
  console.log(s.id, s.agentId, s.status);
}
```

`sessions.list` also takes `agentId` and a creation range, `createdAfter` (inclusive) and `createdBefore` (exclusive); `agent.sessions.list` lists one agent's. Every metadata key you pass must match exactly. Sessions are not filtered or sorted by status.

A session that a [trigger](https://docs.paddock.build/guides/triggers.md) rule created carries its rendered session key as the `triggerKey` metadata, so `sessions.list({ metadata: { triggerKey: "acme/web#42" } })` finds the conversation about pull request 42.

## Get and delete a session

```go Go theme={null}
s, err := client.Sessions.Get(ctx, "ses_01h455vb4pex5vsknk084sn02q")
if err != nil {
	return err
}
err = client.Sessions.Delete(ctx, s.ID)
```

```python Python theme={null}
s = client.sessions.get("ses_01h455vb4pex5vsknk084sn02q")
client.sessions.delete(s.id)
```

```ts TypeScript theme={null}
const s = await paddock.sessions.get("ses_01h455vb4pex5vsknk084sn02q");
await paddock.sessions.delete(s.id);
```

Deleting a session ends its running turn, drops its waiting messages, deletes its events and turns, revokes its tokens, and ends its open streams. The agent and its files stay.

## Lists and pagination

Lists of templates, agents, sessions, turns, capability entries, model providers, triggers, and deliveries take `limit` (default 50, at most 200) and `cursor`, and return `{ data, nextCursor }`. The SDKs page for you:

* **TypeScript**: `await list()` is the first page; `for await (const x of list())` iterates every item.
* **Python**: the returned page iterates every item; `.data` and `.next_cursor` are the first page.
* **Go**: `List` returns an iterator over every item; `ListPage` returns one page.

The other lists are not paged this way. `models.list` takes no parameters and returns every model in one page. A session's `events.list` is paged by `seq`, with `after`, `before`, `types`, and `limit`, and returns `{ data, hasMore }` with no cursor. `files.list` and `memory.list` return every entry at once as `{ data }`.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.