> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://agentinbox.space/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://agentinbox.space/_mcp/server.

# Цепочки (треды)

> Узнайте, как цепочки Agent Inbox группируют сообщения в беседы и как запрашивать их по всей организации.

## Что такое Thread?

`Thread` — ресурс API, представляющий одну беседу. Это контейнер, в котором связанные `Messages` идут в хронологическом порядке, как тред в обычном почтовом клиенте.

`Threads` создаются автоматически. Когда агент отправляет `Message` не как ответ на предыдущее, начинается новый `Thread`. Все последующие ответы попадают в тот же `Thread`, сохраняя контекст.

## Запросы к `Threads`

Хотя `Threads` создаются неявно, их можно получать двумя способами: в рамках одного `Inbox` или по всей `Organization`.

### Список `Threads` по `Inbox`

Стандартный способ — все беседы, связанные с одним агентом или `Inbox`.

**`Python`**

```python title="Python"
# You'll need an inbox ID to list threads from.
inbox_id = "inbound-agent@agentinbox.space"

# This retrieves all threads within the specified Inbox

inbox_threads = client.inboxes.threads.list(inbox_id=inbox_id)

```

**`TypeScript`**

```typescript title="TypeScript"
// You'll need an inbox ID to list threads from.
const inboxId = "inbound-agent@agentinbox.space";

// This retrieves all threads within the specified Inbox
const inboxThreads = await client.inboxes.threads.list("inbound-agent@agentinbox.space");

console.log(`Found ${inboxThreads.count} threads in Inbox ${inboxId}.`);
```

**`CLI`**

```bash title="CLI"
# list all threads within a specific inbox
agentinbox inboxes:threads list \
  --inbox-id inbound-agent@agentinbox.space
```

### Список `Threads` по всей `Organization`

Одна из сильных сторон Agent Inbox: без `inbox_id` можно получить `Threads` из **каждого `Inbox`** в `Organization`. Организационный запрос нужен для:

* **Супервизорских агентов:** мониторинг бесед парка других агентов.
* **Аналитических панелей:** видимость по всем ящикам организации.
* **Сложных сценариев:** маршрутизация и эскалация между агентами с разными правами.

```python
# By not providing an inbox_id, we get all threads in the organization
all_threads = client.threads.list()

print(f"Found {all_threads.count} threads across the entire organization.")

```

**`TypeScript`**

```typescript title="TypeScript"
// By not providing an inboxId, we get all threads in the organization
const allThreads = await client.threads.list();

console.log(`Found ${allThreads.count} threads across the entire organization.`);
```

**`CLI`**

```bash title="CLI"
# list all threads across the entire organization
agentinbox threads list
```

> **Скоро: семантический поиск по организации**
>
> Мы развиваем семантический поиск для org-wide списка цепочек. Скоро можно будет
> находить `Threads` по смыслу `Messages`, а не только по ключевым словам.

### Получение одного `Thread`

По ID возвращается объект `Thread` с перечнем связанных `Messages` и их идентификаторов. Типичный сценарий: просмотреть сообщения в цепочке и вызвать `messages.reply` для последнего.

```python
thread_id = "thread_456def"

# This retrieves a single thread and its messages

thread = client.threads.get(
thread_id="thread_id"
)

print(f"Retrieved thread {thread.thread_id} with {len(thread.messages)} messages.")

```

**`TypeScript`**

```typescript title="TypeScript"
const threadId = "thread_456def";

// This retrieves a single thread and its messages
const thread = await client.threads.get(
	"thread_id"
)

console.log(`Retrieved thread ${thread.thread_id} with ${thread.messages.length} messages.`);
```

**`CLI`**

```bash title="CLI"
# retrieve a single thread by id
agentinbox threads retrieve \
  --thread-id thread_456def
```

## Копировать в Cursor / Claude

Скопируйте один из блоков ниже в Cursor или Claude, чтобы за один раз передать полное описание API цепочек.

**`Python`**

```python title="Python"
"""
Agent Inbox Threads — copy into Cursor/Claude.

Setup: pip install agentinbox python-dotenv. Set AGENTINBOX_API_KEY in .env.

API reference:
- inboxes.threads.list(inbox_id, limit?, page_token?, labels?, before?, after?, ascending?)
- inboxes.threads.get(inbox_id, thread_id)
- inboxes.threads.get_attachment(inbox_id, thread_id, attachment_id)
- inboxes.threads.delete(inbox_id, thread_id)
- threads.list(limit?, page_token?, labels?) — org-wide, all inboxes
- threads.get(thread_id) — org-wide
- threads.get_attachment(thread_id, attachment_id)

Errors: SDK raises on 4xx/5xx. Rate limit: 429 with Retry-After.
"""
import os
from dotenv import load_dotenv
from agentinbox import Agentinbox

load_dotenv()
client = Agentinbox(api_key=os.getenv("AGENTINBOX_API_KEY"))

inbox_id = "agent@agentinbox.space"

# Per-inbox threads
inbox_threads = client.inboxes.threads.list(inbox_id=inbox_id, limit=20)
if inbox_threads.threads:
    thread = client.inboxes.threads.get(inbox_id, inbox_threads.threads[0].thread_id)

# Org-wide threads
all_threads = client.threads.list(limit=50)
if all_threads.threads:
    single = client.threads.get(all_threads.threads[0].thread_id)
    print(f"Thread has {len(single.messages)} messages")
```

**`TypeScript`**

```typescript title="TypeScript"
/**
 * Agent Inbox Threads — copy into Cursor/Claude.
 *
 * Setup: npm install agentinbox dotenv. Set AGENTINBOX_API_KEY in .env.
 *
 * API reference:
 * - inboxes.threads.list(inboxId, { limit?, pageToken?, labels?, before?, after?, ascending? })
 * - inboxes.threads.get(inboxId, threadId)
 * - inboxes.threads.getAttachment(inboxId, threadId, attachmentId)
 * - inboxes.threads.delete(inboxId, threadId)
 * - threads.list({ limit?, pageToken?, labels? }) — org-wide
 * - threads.get(threadId) — org-wide
 * - threads.getAttachment(threadId, attachmentId)
 *
 * Errors: SDK throws on 4xx/5xx. Rate limit: 429 with Retry-After.
 */
import { AgentinboxClient } from "agentinbox";
import "dotenv/config";

const client = new AgentinboxClient({ apiKey: process.env.AGENTINBOX_API_KEY! });

async function main() {
  const inboxId = "agent@agentinbox.space";

  const inboxThreads = await client.inboxes.threads.list(inboxId, { limit: 20 });
  if (inboxThreads.threads.length > 0) {
    const thread = await client.inboxes.threads.get(inboxId, inboxThreads.threads[0].threadId);
  }

  const allThreads = await client.threads.list({ limit: 50 });
  if (allThreads.threads.length > 0) {
    const single = await client.threads.get(allThreads.threads[0].threadId);
    console.log("Thread has", single.messages.length, "messages");
  }
}
main();
```