Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
Build LLM-powered apps with the Anthropic Claude API or SDK across Python, TypeScript, Java, Go, Ruby, C#, and PHP.
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
shared/managed-agents-core.md
1# Managed Agents — Core Concepts23## Architecture45Managed Agents is built around four core concepts:67| Concept | Endpoint | What it is |8|---|---|---|9| **Agent** | `/v1/agents` | A persisted, versioned object defining the agent's capabilities and persona: model, system prompt, tools, MCP servers, skills. **Must be created before starting a session.** See the Agents section below. |10| **Session** | `/v1/sessions` | A stateful interaction with an agent. References a pre-created agent by ID + an environment + initial instructions. Produces an event stream. |11| **Environment** | `/v1/environments` | A template defining the configuration for container provisioning. |12| **Container** | N/A | An isolated compute instance where the agent's **tools** execute (bash, file ops, code). The agent loop does not run here — it runs on Anthropic's orchestration layer and acts on the container via tool calls. |1314```15┌─────────────────────────────────────┐16│ Anthropic orchestration layer │17Agent (config) ───────▶│ (agent loop: Claude + tool calls) │18└──────────────┬──────────────────────┘19│ tool calls20▼21Environment (template) ──▶ Container (tool execution workspace)22│23Session ─┤24├── Resources (files, repos, memory stores — attached at startup)25├── Vault IDs (MCP credential references)26└── Conversation (event stream in/out)27```2829> **Agent creation is a prerequisite.** Sessions reference a pre-created agent by ID — `model`/`system`/`tools` live on the agent object, never on the session. Every flow starts with `POST /v1/agents`.3031---3233## Session Lifecycle3435```36rescheduling → running ↔ idle → terminated37```3839| Status | Description |40| -------------- | ------------------------------------------------------------------ |41| `idle` | Agent has finished the current task, and is awaiting input. It's either waiting for input to continue working via a `user.message` or blocked awaiting a `user.custom_tool_result` or `user.tool_confirmation`. The `stop_reason` attached contains more information about why the Agent has stopped working. |42| `running` | Session has starting running, and the Agent is actively doing work. |43| `rescheduling` | Session is (re)scheduling after a retryable error has occurred, ready to be picked up by the orchestration system. |44| `terminated` | Session has terminated, entering an irreversible and unusable state. |4546- Events can be sent when the session is `running` or `idle`. Messages are queued and processed in order.47- The agent transitions `idle → running` when it receives a new event, then back to `idle` when done.48- Errors surface as `session.error` events in the stream, not as a status value.4950### Built-in session features5152- **Context compaction** — if you approach max context, the API automatically condenses session history to keep the interaction going53- **Prompt caching** — historical repeated tokens are cached, reducing processing time and cost54- **Extended thinking** — on by default, returned as `agent.thinking` events5556### Session operations5758| Operation | Notes |59|---|---|60| List / fetch | Paginated list or single resource by ID |61| Update | Only `title` is updatable |62| Archive | Session becomes **read-only**. Not reversible. |63| Delete | Permanently deletes session, event history, container, and checkpoints. |6465---6667## Sessions6869A session is a running agent instance inside an environment.7071### Session Object7273Key fields returned by the API:7475| Field | Type | Description |76| --------------- | -------- | --------------------------------------------------- |77| `type` | string | Always `"session"` |78| `id` | string | Unique session ID |79| `title` | string | Human-readable title |80| `status` | string | `idle`, `running`, `rescheduling`, `terminated` |81| `created_at` | string | ISO 8601 timestamp |82| `updated_at` | string | ISO 8601 timestamp |83| `archived_at` | string | ISO 8601 timestamp (nullable) |84| `environment_id` | string | Environment ID |85| `agent` | object | Agent configuration |86| `resources` | array | Attached files, repos, and memory stores |87| `metadata` | object | User-provided key-value pairs (max 8 keys) |88| `usage` | object | Token usage statistics |8990### Creating a session9192**A session is meaningless without an agent.** Sessions reference a pre-created agent by ID. Create the agent first via `agents.create()`, then reference it:9394```ts95// 1. Create the agent (reusable, versioned)96const agent = await client.beta.agents.create(97{98name: "Coding Assistant",99model: "claude-opus-4-7",100system: "You are a helpful coding agent.",101tools: [{ type: "agent_toolset_20260401"}],102},103);104105// 2. Start a session that references it106const session = await client.beta.sessions.create(107{108agent: agent.id, // string shorthand → latest version. Or: { type: "agent", id: agent.id, version: agent.version }109environment_id: environmentId,110title: "Hello World Session",111},112);113```114115**Session creation parameters:**116117| Field | Type | Required | Description |118| --------------- | -------- | -------- | ---------------------------------------------- |119| `agent` | string or object | **Yes** | String shorthand `"agent_abc123"` (latest version) or `{type: "agent", id, version}` |120| `environment_id`| string | **Yes** | Environment ID |121| `title` | string | No | Human-readable name (appears in logs/dashboards) |122| `resources` | array | No | Files, GitHub repos, or memory stores, attached to the container at startup. Memory stores are session-create-only (not addable via `resources.add()`). |123| `vault_ids` | array | No | Vault IDs (`vlt_*`) — MCP credentials with auto-refresh. See `shared/managed-agents-tools.md` → Vaults. |124| `metadata` | object | No | User-provided key-value pairs |125126**Agent configuration fields** (passed to `agents.create()`, not `sessions.create()`):127128| Field | Type | Required | Description |129| ------------- | -------- | -------- | ---------------------------------------------- |130| `name` | string | **Yes** | Human-readable name (1-256 chars) |131| `model` | string or object | **Yes** | Claude model ID (bare string, or `{id, speed}` object). All Claude 4.5+ models supported. |132| `system` | string | No | System prompt — defines the agent's behavior (up to 100K chars) |133| `tools` | array | No | Encompasses three kinds: (1) pre-built Claude Agent tools (`agent_toolset_20260401`), (2) MCP tools (`mcp_toolset`), and (3) custom client-side tools. Max 128. |134| `mcp_servers` | array | No | MCP server connections — standardized third-party capabilities (e.g. GitHub, Asana). Max 20, unique names. See `shared/managed-agents-tools.md` → MCP Servers. |135| `skills` | array | No | Customized "best-practices" context with progressive disclosure. Max 20. See `shared/managed-agents-tools.md` → Skills. |136| `description` | string | No | Description of the agent (up to 2048 chars) |137| `multiagent` | object | No | `{type: "coordinator", agents: [...]}` — roster this agent may delegate to. See `shared/managed-agents-multiagent.md`. |138| `metadata` | object | No | Arbitrary key-value pairs (max 16, keys ≤64 chars, values ≤512 chars) |139140---141142## Agents143144**This is where every Managed Agents flow begins.** The agent object is a persisted, versioned configuration — you create it once, then reference it by ID every time you start a session. No agent → no session.145146### Agent Object147148The API is **flat** — `model`, `system`, `tools` etc. are top-level fields, not wrapped in an `agent:{}` sub-object.149150| Field | Type | Required | Description |151| ------------------ | -------- | -------- | -------------------------------------------------- |152| `name` | string | Yes | Human-readable name |153| `model` | string | Yes | Claude model ID |154| `system` | string | No | System prompt |155| `tools` | array | No | Agent toolset / MCP toolset / custom tools |156| `mcp_servers` | array | No | MCP server connections |157| `skills` | array | No | Skill references (max 20) |158| `description` | string | No | Description of the agent |159| `multiagent` | object | No | Coordinator roster — see `shared/managed-agents-multiagent.md` |160| `metadata` | object | No | Arbitrary key-value pairs |161162### Lifecycle: create once, run many, update in place163164The agent is a **persistent resource**, not a per-run parameter. The intended pattern:165166```167┌─ setup (once) ─────────┐ ┌─ runtime (every invocation) ─┐168│ agents.create() │ │ sessions.create( │169│ → store agent_id │ ──→ │ agent={type:..., id: ID} │170│ in config/env/db │ │ ) │171└────────────────────────┘ └──────────────────────────────┘172```173174**Anti-pattern:** calling `agents.create()` at the top of every script run. This accumulates orphaned agent objects, pays create latency on every invocation, and defeats the versioning model. If you see `agents.create()` in a function that's called per-request or per-cron-tick, that's wrong — hoist it to one-time setup and persist the ID.175176### Versioning177178Each `POST /v1/agents/{id}` (update) creates a new immutable version (numeric timestamp, e.g. `1772585501101368014`). The agent's history is append-only — you can't edit a past version.179180**Why version:**181- **Reproducibility** — pin a session to a known-good config: `{type: "agent", id, version: 3}`182- **Safe iteration** — update the agent without breaking sessions already running on the old version183- **Rollback** — if a new system prompt regresses, pin new sessions back to the prior version while you debug184185**`version` is optional.** Omit it (or use the string shorthand `agent="agent_abc123"`) to get the latest version at session-creation time. Pass it explicitly (`{type: "agent", id, version: N}`) to pin for reproducibility.186187**Getting the version to pin:** `agents.create()` and `agents.update()` both return `version` in the response. Store it alongside `agent_id`. To fetch the current latest for an existing agent: `GET /v1/agents/{id}` → `.version`.188189**When to update vs create new:** Update (`POST /v1/agents/{id}`) when it's conceptually the same agent with tweaked behavior (better prompt, extra tool). Create a new agent when it's a different persona/purpose. Rule of thumb: if you'd give it the same `name`, update.190191### Agent Endpoints192193| Operation | Method | Path |194| ---------------- | -------- | ------------------------------------- |195| Create | `POST` | `/v1/agents` |196| List | `GET` | `/v1/agents` |197| Get | `GET` | `/v1/agents/{id}` |198| Update | `POST` | `/v1/agents/{id}` |199| Archive | `POST` | `/v1/agents/{id}/archive` |200201> ⚠️ **Archive is permanent.** Archiving makes the agent read-only: existing sessions continue to run, but **new sessions cannot reference it**, and there is no unarchive. Since agents have no `delete`, this is the terminal lifecycle state. Never archive a production agent as routine cleanup — confirm with the user first.202203### Using an Agent in a Session204205Reference the agent by string ID (latest version) or by object with an explicit version:206207```python208# String shorthand — uses the agent's latest version209session = client.beta.sessions.create(210agent=agent.id,211environment_id=environment_id,212)213214# Or pin to a specific version (int)215session = client.beta.sessions.create(216agent={"type": "agent", "id": agent.id, "version": agent.version},217environment_id=environment_id,218)219```220221