| 1 |
#!/usr/bin/env python3 |
| 2 |
"""End-to-end self-hosted environment worker demo. |
| 3 |
|
| 4 |
Creates an agent with the built-in agent_toolset_20260401 plus a custom |
| 5 |
`current_time` tool, opens a session against your self-hosted environment, |
| 6 |
sends a prompt, runs an `EnvironmentWorker` in-process to service the tool |
| 7 |
calls locally, then prints the resulting transcript and cleans up. |
| 8 |
|
| 9 |
Required env vars: |
| 10 |
ANTHROPIC_API_KEY your standard API key (used for agent/session calls) |
| 11 |
ANTHROPIC_ENVIRONMENT_ID the self-hosted environment to poll |
| 12 |
ANTHROPIC_ENVIRONMENT_KEY the environment key (the worker's single credential) |
| 13 |
|
| 14 |
Security model: the worker executes bash and file operations directly on the |
| 15 |
host. Run inside a container or other isolation boundary you control. |
| 16 |
""" |
| 17 |
|
| 18 |
from __future__ import annotations |
| 19 |
|
| 20 |
import os |
| 21 |
import sys |
| 22 |
import asyncio |
| 23 |
import logging |
| 24 |
import contextlib |
| 25 |
from typing import Any, cast |
| 26 |
from datetime import datetime |
| 27 |
|
| 28 |
from anthropic import AsyncAnthropic |
| 29 |
from anthropic.lib.tools import beta_async_tool |
| 30 |
from anthropic.types.beta import BetaManagedAgentsCustomToolParams |
| 31 |
from anthropic.lib.environments import MANAGED_AGENTS_BETA |
| 32 |
from anthropic.lib.tools.agent_toolset import beta_agent_toolset_20260401 |
| 33 |
|
| 34 |
POLL_TIMEOUT_S = 60 |
| 35 |
MODEL_ID = "claude-haiku-4-5" |
| 36 |
|
| 37 |
|
| 38 |
# A custom tool. Because @beta_async_tool produces the same type that |
| 39 |
# client.beta.messages.tool_runner accepts, the worker can run it alongside the |
| 40 |
# built-in agent_toolset tools with no extra wiring. |
| 41 |
@beta_async_tool |
| 42 |
async def current_time() -> str: |
| 43 |
"""Return the host's current local time as an ISO-8601 string.""" |
| 44 |
return datetime.now().isoformat() |
| 45 |
|
| 46 |
|
| 47 |
def _require_env(name: str) -> str: |
| 48 |
val = os.environ.get(name) |
| 49 |
if not val: |
| 50 |
sys.exit(f"error: environment variable {name} is required") |
| 51 |
return val |
| 52 |
|
| 53 |
|
| 54 |
async def main() -> None: |
| 55 |
logging.basicConfig(level=logging.INFO) |
| 56 |
client = AsyncAnthropic() |
| 57 |
|
| 58 |
environment_id = _require_env("ANTHROPIC_ENVIRONMENT_ID") |
| 59 |
environment_key = _require_env("ANTHROPIC_ENVIRONMENT_KEY") |
| 60 |
workdir = os.environ.get("ANTHROPIC_WORKDIR", ".") |
| 61 |
|
| 62 |
# 1. Create an agent that has both the built-in toolset and our custom tool. |
| 63 |
# The Agents API uses its own custom-tool TypedDict and rejects |
| 64 |
# `additionalProperties` (which pydantic emits), so derive a clean schema. |
| 65 |
schema = {k: v for k, v in dict(current_time.input_schema).items() if k != "additionalProperties"} |
| 66 |
custom_tool_param: BetaManagedAgentsCustomToolParams = { |
| 67 |
"type": "custom", |
| 68 |
"name": current_time.name, |
| 69 |
"description": current_time.description or "Return the host's current local time.", |
| 70 |
"input_schema": cast("Any", schema), |
| 71 |
} |
| 72 |
agent = await client.beta.agents.create( |
| 73 |
name="self-hosted-runner-example", |
| 74 |
model={"id": MODEL_ID}, |
| 75 |
system="You are a test agent running in a self-hosted sandbox. Use the available tools.", |
| 76 |
tools=[{"type": "agent_toolset_20260401"}, custom_tool_param], |
| 77 |
) |
| 78 |
print(f"created agent {agent.id}") |
| 79 |
|
| 80 |
# 2. Create a session bound to the self-hosted environment. The |
| 81 |
# MANAGED_AGENTS_BETA header is required for the server to accept a |
| 82 |
# self-hosted environment_id on Sessions endpoints. |
| 83 |
session = await client.beta.sessions.create( |
| 84 |
agent=agent.id, |
| 85 |
environment_id=environment_id, |
| 86 |
title="self-hosted-runner-example", |
| 87 |
betas=[MANAGED_AGENTS_BETA], |
| 88 |
) |
| 89 |
print(f"created session {session.id}") |
| 90 |
|
| 91 |
try: |
| 92 |
# 3. Send the user prompt that will trigger both a built-in tool (bash) |
| 93 |
# and the custom tool (current_time). |
| 94 |
await client.beta.sessions.events.send( |
| 95 |
session.id, |
| 96 |
events=[ |
| 97 |
{ |
| 98 |
"type": "user.message", |
| 99 |
"content": [ |
| 100 |
{ |
| 101 |
"type": "text", |
| 102 |
"text": "What is the current time? Also run pwd to show me the working directory.", |
| 103 |
} |
| 104 |
], |
| 105 |
} |
| 106 |
], |
| 107 |
betas=[MANAGED_AGENTS_BETA], |
| 108 |
) |
| 109 |
|
| 110 |
# 4. Service the work locally: the worker polls for work, and for each |
| 111 |
# claimed session sets up the workdir + downloads the agent's skills, |
| 112 |
# runs the local tools against the session's tool calls while |
| 113 |
# heartbeating the work-item lease, then force-stops the work. The |
| 114 |
# `tools` factory binds the built-in toolset to the per-session |
| 115 |
# `AgentToolContext` and adds our custom tool. (Use |
| 116 |
# `client.beta.sessions.events.tool_runner(...)` directly if you want |
| 117 |
# to observe each dispatched tool call.) |
| 118 |
# |
| 119 |
# `client.beta.environments.work.worker(...)` builds an |
| 120 |
# `EnvironmentWorker`; you can also construct one directly with |
| 121 |
# `EnvironmentWorker(client, ...)` from `anthropic.lib.environments`. |
| 122 |
# |
| 123 |
# If you already hold a single claimed work item — e.g. an |
| 124 |
# `ant worker poll --on-work` script spawned this process for one |
| 125 |
# item — use `handle_item()` instead of `run()`. With no arguments it |
| 126 |
# serves the item described by the `ANTHROPIC_WORK_ID` / |
| 127 |
# `ANTHROPIC_ENVIRONMENT_ID` / `ANTHROPIC_SESSION_ID` / |
| 128 |
# `ANTHROPIC_ENVIRONMENT_KEY` env vars that command sets, and |
| 129 |
# `environment_id` isn't needed: |
| 130 |
# await client.beta.environments.work.worker(workdir=workdir, tools=...).handle_item() |
| 131 |
worker = client.beta.environments.work.worker( |
| 132 |
environment_id=environment_id, |
| 133 |
environment_key=environment_key, |
| 134 |
workdir=workdir, |
| 135 |
tools=lambda env: [*beta_agent_toolset_20260401(env), current_time], |
| 136 |
) |
| 137 |
|
| 138 |
# The worker runs forever; bound it for the demo so the script exits |
| 139 |
# after the model has finished responding. |
| 140 |
with contextlib.suppress(asyncio.TimeoutError): |
| 141 |
await asyncio.wait_for(worker.run(), timeout=POLL_TIMEOUT_S) |
| 142 |
|
| 143 |
# 5. Print the resulting transcript. |
| 144 |
print("\n--- transcript ---") |
| 145 |
async for ev in client.beta.sessions.events.list(session.id, limit=100, betas=[MANAGED_AGENTS_BETA]): |
| 146 |
print(_summarise_event(ev)) |
| 147 |
|
| 148 |
finally: |
| 149 |
# 6. Clean up the session so the environment's work queue stays empty. |
| 150 |
await client.beta.sessions.delete(session.id, betas=[MANAGED_AGENTS_BETA]) |
| 151 |
print(f"\ndeleted session {session.id}") |
| 152 |
|
| 153 |
|
| 154 |
def _summarise_event(ev: Any) -> str: |
| 155 |
ev_type: str = getattr(ev, "type", "?") |
| 156 |
if ev_type == "agent.tool_use": |
| 157 |
return f"{ev_type}: name={getattr(ev, 'name', '?')} input={getattr(ev, 'input', {})!r}" |
| 158 |
content: Any = getattr(ev, "content", None) |
| 159 |
if not content: |
| 160 |
return ev_type |
| 161 |
first = content[0] |
| 162 |
text: str | None = getattr(first, "text", None) |
| 163 |
if text is None and hasattr(first, "get"): |
| 164 |
text = first.get("text") |
| 165 |
if not text: |
| 166 |
return ev_type |
| 167 |
snippet = text[:120] + ("..." if len(text) > 120 else "") |
| 168 |
return f"{ev_type}: {snippet}" |
| 169 |
|
| 170 |
|
| 171 |
if __name__ == "__main__": |
| 172 |
asyncio.run(main()) |