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-environments.md
1# Managed Agents — Environments & Resources23## Environments45Creating a session requires an `environment_id`. Environments are **reusable configuration templates** for spinning up containers in Anthropic's infrastructure — you might create different environments for different use cases (e.g. data visualization vs web development, with different package sets). Anthropic handles scaling, container lifecycle, and work orchestration.67**Environment names must be unique.** Creating an environment with an existing name returns 409.89### Networking1011| Network Policy | Description |12| ------------------------------- | ------------------------------------------------------------- |13| `unrestricted` | Full egress (except legal blocklist) |14| `package_managers_and_custom` | Package managers + custom `allowed_hosts` |1516```json17{18"networking": {19"type": "package_managers_and_custom",20"allowed_hosts": ["api.example.com"]21}22}23```2425**MCP caveat:** If using restricted networking, make sure `allowed_hosts` includes your MCP server domains. Otherwise the container can't reach them and tools silently fail.2627### Creating an environment2829The SDK adds `managed-agents-2026-04-01` automatically. TypeScript:3031```ts32const env = await client.beta.environments.create({33name: "my_env",34config: {35type: "cloud",36networking: { type: "unrestricted" },37},38});39```4041### Environment CRUD4243| Operation | Method | Path | Notes |44| ---------------- | -------- | ------------------------------------------ | ----- |45| Create | `POST` | `/v1/environments` | |46| List | `GET` | `/v1/environments` | Paginated (`limit`, `after_id`, `before_id`) |47| Get | `GET` | `/v1/environments/{id}` | |48| Update | `POST` | `/v1/environments/{id}` | Changes apply only to **new** containers; existing sessions keep their original config |49| Delete | `DELETE` | `/v1/environments/{id}` | Returns 204. |50| Archive | `POST` | `/v1/environments/{id}/archive` | Makes it **read-only**; existing sessions continue, new sessions cannot reference it. No unarchive — terminal state. |5152---5354## Resources5556Attach files, GitHub repositories, and memory stores to a session. **Session creation blocks until all resources are mounted** — the container won't go `running` until every file and repo is in place. Max **999 file resources** per session. Multiple GitHub repositories per session are supported. For `type: "memory_store"` resources (persistent cross-session memory — max 8 per session), see `shared/managed-agents-memory.md`.5758### File Uploads (input — host → agent)5960Upload a file first via the Files API, then reference by `file_id` + `mount_path`:6162```ts63// 1. Upload64const file = await client.beta.files.upload({65file: fs.createReadStream("data.csv"),66});6768// 2. Attach as a session resource69const session = await client.beta.sessions.create({70agent: agent.id,71environment_id: envId,72resources: [73{ type: "file", file_id: file.id, mount_path: "/workspace/data.csv" }74],75});76```7778**`mount_path` is required** and must be absolute. Parent directories are created automatically. Agent working directory defaults to `/workspace`. Files are mounted read-only — the agent writes modified versions to new paths.7980### Session outputs (output — agent → host)8182The agent can write files to `/mnt/session/outputs/` during a session. These are automatically captured by the Files API and can be listed and downloaded afterwards:8384```ts85// After the turn completes, list output files scoped to this session:86for await (const f of client.beta.files.list({87scope_id: session.id,88betas: ["managed-agents-2026-04-01"],89})) {90console.log(f.filename, f.size_bytes);91const resp = await client.beta.files.download(f.id);92const text = await resp.text();93}94```9596**Requirements:**97- The `write` tool (or `bash`) must be enabled for the agent to create output files.98- Session-scoped `files.list` / `files.download` captures outputs written to `/mnt/session/outputs/`.99- The filter parameter is **`scope_id`** (REST query param `?scope_id=<session_id>`). The SDK's files resource auto-adds only the `files-api-2025-04-14` header, so pass `betas: ["managed-agents-2026-04-01"]` explicitly (or both headers on raw HTTP) — without it the API may reject `scope_id` as an unknown field. Requires `@anthropic-ai/sdk` ≥ 0.88.0 / `anthropic` (Python) ≥ 0.92.0 — older versions don't type `scope_id`. The `ant` CLI does **not** expose this flag yet; use the SDK or curl.100- Pass the session ID returned by `sessions.create()` verbatim (e.g. `sesn_011CZx...`) — the API validates the prefix.101- There's a brief indexing lag (~1–3s) between `session.status_idle` and output files appearing in `files.list`. Retry once or twice if empty.102103> **Fallback when `scope_id` filtering is unavailable** (older SDK, or endpoint returns an error): send a follow-up `user.message` asking the agent to `read` each file under `/mnt/session/outputs/` and return the contents. The agent streams the file bodies back as `agent.message` text. This works for text files only and costs output tokens — use it to unblock, not as the primary path.104105This gives you a bidirectional file bridge: upload reference data in, download agent artifacts out.106107### GitHub Repositories108109Clones a GitHub repository into the session container during initialization, before the agent begins execution. The agent can read, edit, commit, and push via `bash` (`git`). Multiple repositories per session are supported — add one `resources` entry per repo. Repositories are cached, so future sessions that use the same repository start faster.110111Repositories are attached for the lifetime of the session — to change which repositories are mounted, create a new session. You **can** rotate a repository's `authorization_token` on a running session via `client.beta.sessions.resources.update(resource_id, {session_id, authorization_token})`; the resource `id` is returned at session creation and by `resources.list()`.112113**Fields:**114115| Field | Required | Notes |116|---|---|---|117| `type` | ✅ | `"github_repository"` |118| `url` | ✅ | The GitHub repository URL |119| `authorization_token` | ✅ | GitHub Personal Access Token with repository access. **Never echoed in API responses.** |120| `mount_path` | ❌ | Path where the repository will be cloned. Defaults to `/workspace/<repo-name>`. |121| `checkout` | ❌ | `{type: "branch", name: "..."}` or `{type: "commit", sha: "..."}`. Defaults to the repo's default branch. |122123**Token permission levels** (fine-grained PATs):124- `Contents: Read` — clone only125- `Contents: Read and write` — push changes and create pull requests126127**How auth works:** `authorization_token` is never placed inside the container. `git pull` / `git push` and GitHub REST calls against the attached repository are routed through an Anthropic-side git proxy that injects the token after the request leaves the sandbox. Code running in the container — including anything the agent writes — cannot read or exfiltrate it.128129> ‼️ **To generate pull requests** you also need GitHub **MCP server** access — the `github_repository` resource gives filesystem + git access only. See `shared/managed-agents-tools.md` → MCP Servers. The PR workflow is: edit files in the mounted repo → push branch via `bash` (authenticated via the git proxy using `authorization_token`) → create PR via the MCP `create_pull_request` tool (authenticated via the vault).130131**TypeScript:**132133```ts134// 1. Create the agent — declare GitHub MCP (no auth here)135const agent = await client.beta.agents.create(136{137name: 'GitHub Agent',138model: 'claude-opus-4-7',139mcp_servers: [140{ type: 'url', name: 'github', url: 'https://api.githubcopilot.com/mcp/' },141],142tools: [143{ type: 'agent_toolset_20260401', default_config: { enabled: true } },144{ type: 'mcp_toolset', mcp_server_name: 'github' },145],146},147);148149// 2. Start a session — attach vault for MCP auth + mount the repo150const session = await client.beta.sessions.create({151agent: agent.id,152environment_id: envId,153vault_ids: [vaultId], // vault contains the GitHub MCP OAuth credential154resources: [155{156type: 'github_repository',157url: 'https://github.com/owner/repo',158authorization_token: process.env.GITHUB_TOKEN, // repo clone token (≠ MCP auth)159checkout: { type: 'branch', name: 'main' },160},161],162});163```164165**Python:**166167```python168import os169170agent = client.beta.agents.create(171name="GitHub Agent",172model="claude-opus-4-7",173mcp_servers=[{174"type": "url",175"name": "github",176"url": "https://api.githubcopilot.com/mcp/",177}],178tools=[179{"type": "agent_toolset_20260401", "default_config": {"enabled": True}},180{"type": "mcp_toolset", "mcp_server_name": "github"},181],182)183184session = client.beta.sessions.create(185agent=agent.id,186environment_id=env_id,187vault_ids=[vault_id], # vault contains the GitHub MCP OAuth credential188resources=[{189"type": "github_repository",190"url": "https://github.com/owner/repo",191"authorization_token": os.environ["GITHUB_TOKEN"], # repo clone token (≠ MCP auth)192"checkout": {"type": "branch", "name": "main"},193}],194)195```196197---198199## Files API200201Upload and manage files for use as session resources, and download files the agent wrote to `/mnt/session/outputs/`.202203| Operation | Method | Path | SDK |204| ---------------- | -------- | ------------------------------------- | --- |205| Upload | `POST` | `/v1/files` | `client.beta.files.upload({ file })` |206| List | `GET` | `/v1/files?scope_id=...` | `client.beta.files.list({ scope_id, betas: ["managed-agents-2026-04-01"] })` |207| Get Metadata | `GET` | `/v1/files/{id}` | `client.beta.files.retrieveMetadata(id)` |208| Download | `GET` | `/v1/files/{id}/content` | `client.beta.files.download(id)` → `Response` |209| Delete | `DELETE` | `/v1/files/{id}` | `client.beta.files.delete(id)` |210211The `scope_id` filter on List scopes the results to files written to `/mnt/session/outputs/` by that session. Without the filter, you get all files uploaded to your account.212