Debian Codegraph @

src/anthropic/lib/environments/_worker.py

raw
1 """The self-hosted environment worker — the full composition of the
2 control-plane poller and the per-session tool runner.
3
4 `EnvironmentWorker` claims work items from a self-hosted environment, and
5 for each claimed `session` work item: builds the per-session
6 `anthropic.lib.tools.agent_toolset.AgentToolContext` and downloads the
7 session agent's skills, then runs a
8 `anthropic.lib.tools._beta_session_runner.SessionToolRunner` for the
9 session *while* heartbeating the work-item lease in parallel; on exit it
10 force-stops the work item (unless the lease was lost, in which case the item is
11 left to whoever holds it now) and loops to the next one. The lease heartbeat
12 reporting `state == "stopping"` (or a lost lease) ends the session run.
13
14 Build one from the generated work resource:
15
16 ```py
17 client.beta.environments.work.worker(environment_id=..., environment_key=...)
18 ```
19
20 or construct it directly:
21
22 ```py
23 from anthropic.lib.environments import EnvironmentWorker
24
25 EnvironmentWorker(client, environment_id=..., environment_key=...)
26 ```
27
28 `EnvironmentWorker.handle_item` runs that same per-work-item flow for a
29 single work item you've already claimed (e.g. a `worker poll --on-work` script
30 handed one to a fresh process); with no arguments it reads the `ANTHROPIC_*`
31 env vars that command sets.
32 """
33
34 from __future__ import annotations
35
36 import os
37 import enum
38 import json
39 import time
40 import base64
41 import logging
42 from typing import TYPE_CHECKING, Union, Callable, cast, overload
43 from collections.abc import Mapping, Sequence
44 from typing_extensions import deprecated
45
46 import anyio
47
48 from .._retry import TRANSIENT_ERRORS
49 from ._poller import _is_status, aiter_work, _is_fatal_4xx
50 from ..._types import Headers, NotGiven, not_given
51 from ..._utils import is_mapping
52 from ..._exceptions import APIStatusError
53 from .._scoped_client import _copy_client_with_bearer_auth
54 from ..tools._memories import (
55 MEMORY_FLUSH_TIMEOUT,
56 MIN_MEMORY_SYNC_INTERVAL,
57 DEFAULT_MEMORY_SYNC_INTERVAL,
58 MemoryDeleteMode,
59 SessionMemoryError,
60 SessionMemoryStores,
61 _check_sync_interval,
62 )
63 from ..tools._deprecations import UNRESTRICTED_PATHS_DEPRECATION, reject_unrestricted_paths
64 from ...types.beta.environments import BetaSelfHostedWork, BetaSessionWorkData
65 from ..tools._beta_session_runner import (
66 DEFAULT_MAX_IDLE,
67 BetaAnyRunnableTool,
68 _run_session_tools,
69 )
70
71 if TYPE_CHECKING:
72 from ..._client import AsyncAnthropic
73 from ...types.beta import BetaManagedAgentsSession
74 from ..tools.agent_toolset import AgentToolContext
75 from ...resources.beta.environments.work import AsyncWork
76
77 # `agent_toolset` pulls in host-only modules (`subprocess`, `tarfile`, …),
78 # so it is never imported at module level here — only as a type above, and
79 # lazily for its values inside `_tools_for` / `_handle_item`. That keeps this
80 # module host-dep-free so the generated `work` resource can expose
81 # `EnvironmentWorker` without dragging those imports into `import anthropic`.
82
83 __all__ = [
84 "EnvironmentWorker",
85 "EnvironmentWorkerTools",
86 "DEFAULT_MEMORY_SYNC_INTERVAL",
87 "MIN_MEMORY_SYNC_INTERVAL",
88 "MEMORY_FLUSH_TIMEOUT",
89 ]
90
91 log = logging.getLogger(__name__)
92
93 _HEARTBEAT_DEFAULT = 30.0
94 # Assumed lease TTL before the server's first heartbeat response tells us the
95 # real value — used to decide when a run of transient failures means the lease
96 # is gone.
97 _HEARTBEAT_TTL_DEFAULT = 90.0
98 _NO_HEARTBEAT_SENTINEL = "NO_HEARTBEAT"
99
100 # A fixed tool list, or a factory invoked once per claimed session with that
101 # session's `AgentToolContext` — use the factory form to bind
102 # `beta_agent_toolset_20260401` (or any tool that needs the workdir /
103 # session id) to the right session.
104 EnvironmentWorkerTools = Union[
105 Sequence[BetaAnyRunnableTool], Callable[["AgentToolContext"], Sequence[BetaAnyRunnableTool]]
106 ]
107
108 # Transient errors the heartbeat loop retries on top of `TRANSIENT_ERRORS`:
109 # `anyio.fail_after` (which bounds each heartbeat) raises the builtin
110 # `TimeoutError` rather than an `APIError`, so it would otherwise fall
111 # through to the un-retried branch. Declared at module level with an explicit
112 # type so mypy can verify the `except` clause; an inline
113 # `except (*TRANSIENT_ERRORS, TimeoutError)` types as `tuple[Any, ...]`
114 # and mypy rejects it as not-an-exception-tuple.
115 _HEARTBEAT_TRANSIENT_ERRORS: tuple[type[Exception], ...] = (*TRANSIENT_ERRORS, TimeoutError)
116
117
118 class _LeaseEndReason(enum.Enum):
119 """Why heartbeating of a work item ended, as recorded on its `_Lease`."""
120
121 RUNNER_DONE = "runner_done" # the session run ended first; the lease was held throughout
122 CONTROL_PLANE_STOP = "control_plane_stop" # state stopping / stopped, or lease_extended false
123 LEASE_LOST = "lease_lost" # a heartbeat met 412: the item was re-queued or another worker holds it
124 HEARTBEAT_REJECTED = "heartbeat_rejected" # a heartbeat met another 4xx that retrying will not fix
125 ASSUMED_LOST = "assumed_lost" # no heartbeat succeeded for a full lease TTL
126
127
128 class _Lease:
129 """This worker's view of one work-item lease: whether it has ended, and why.
130
131 Shared by `_heartbeat_loop` and the code serving the item. The first
132 recorded reason wins, so a run cancelled *because* the lease was lost still
133 reads as lost afterwards.
134 """
135
136 _end_reason: _LeaseEndReason | None
137
138 def __init__(self) -> None:
139 self._end_reason = None
140 self._ended = anyio.Event()
141
142 def finish(self, reason: _LeaseEndReason) -> None:
143 if self._end_reason is None:
144 self._end_reason = reason
145 self._ended.set()
146
147 @property
148 def ended(self) -> bool:
149 return self._ended.is_set()
150
151 async def wait_ended(self) -> None:
152 await self._ended.wait()
153
154 @property
155 def lost(self) -> bool:
156 """True once the item belongs to the queue or another worker, so this one must not stop it."""
157 return self._end_reason in (_LeaseEndReason.LEASE_LOST, _LeaseEndReason.ASSUMED_LOST)
158
159
160 def _server_lease_state(err: APIStatusError) -> Mapping[str, object]:
161 """The server's view of the lease carried by a 412 heartbeat response, or empty if absent."""
162 node: object = err.body
163 for key in ("error", "details", "current_state"):
164 if not is_mapping(node):
165 return {}
166 node = node.get(key)
167 return node if is_mapping(node) else {}
168
169
170 async def _heartbeat_loop(
171 work: AsyncWork,
172 *,
173 work_id: str,
174 environment_id: str,
175 lease: _Lease,
176 extra_headers: Headers | None = None,
177 on_lease_ttl: Callable[[float], object] | None = None,
178 ) -> None:
179 """Keep the work-item lease alive while a session is being served.
180
181 `work` must be bound to a sub-client authenticated for the environment;
182 this loop adds no auth of its own. Returns once `lease` has ended, and
183 ends it itself when the control plane reports the work is `stopping` /
184 `stopped` or no longer extends the lease, when a heartbeat is rejected
185 (a 412 means the lease already belongs to someone else), or when
186 transient failures have run long enough that the lease must be assumed
187 lost (so two runners don't end up serving the same work). `on_lease_ttl`
188 is called with the server-reported TTL after every successful beat.
189 """
190 interval = _HEARTBEAT_DEFAULT
191 ttl = _HEARTBEAT_TTL_DEFAULT
192 last = _NO_HEARTBEAT_SENTINEL
193 last_success = time.monotonic()
194 while not lease.ended:
195 try:
196 # Bound each heartbeat: a network blackhole must not leave us
197 # awaiting for the SDK's multi-minute default while the lease TTL
198 # (tens of seconds) expires out from under us.
199 with anyio.fail_after(interval):
200 resp = await work.heartbeat(
201 work_id,
202 environment_id=environment_id,
203 expected_last_heartbeat=last,
204 extra_headers=extra_headers,
205 )
206 # Anything outside `_HEARTBEAT_TRANSIENT_ERRORS` is a real bug and
207 # propagates rather than being swallowed and retried until the lease
208 # is assumed lost.
209 except _HEARTBEAT_TRANSIENT_ERRORS as e:
210 if _is_status(e, 412):
211 server = _server_lease_state(e)
212 log.error(
213 "lease lost: heartbeat precondition failed work_id=%s "
214 "server_state=%s server_ttl_seconds=%s server_last_heartbeat=%s",
215 work_id,
216 server.get("state"),
217 server.get("ttl_seconds"),
218 server.get("last_heartbeat"),
219 )
220 lease.finish(_LeaseEndReason.LEASE_LOST)
221 return
222 if _is_fatal_4xx(e):
223 log.error("permanent heartbeat failure error=%s", e)
224 lease.finish(_LeaseEndReason.HEARTBEAT_REJECTED)
225 return
226 # A transient failure (5xx, timeout, connection error) is not a 4xx,
227 # so retrying forever risks split-brain once the lease expires. If no
228 # heartbeat has succeeded within the lease TTL, assume it's lost.
229 if time.monotonic() - last_success > ttl:
230 log.error("lease assumed lost: no successful heartbeat in %.0fs error=%s", ttl, e)
231 lease.finish(_LeaseEndReason.ASSUMED_LOST)
232 return
233 log.warning("transient heartbeat failure error=%s", e)
234 else:
235 last = resp.last_heartbeat
236 last_success = time.monotonic()
237 if resp.ttl_seconds > 0:
238 ttl = resp.ttl_seconds
239 interval = max(1.0, min(resp.ttl_seconds / 2, _HEARTBEAT_DEFAULT))
240 if on_lease_ttl is not None:
241 on_lease_ttl(ttl)
242 if resp.state in ("stopping", "stopped") or not resp.lease_extended:
243 log.info("heartbeat signals shutdown state=%s lease_extended=%s", resp.state, resp.lease_extended)
244 lease.finish(_LeaseEndReason.CONTROL_PLANE_STOP)
245 return
246 with anyio.move_on_after(interval):
247 await lease.wait_ended()
248
249
250 def _flattened_causes(exc: BaseException) -> str:
251 """The causes under an exception group — anyio's wrapper message says nothing."""
252 inner = getattr(exc, "exceptions", None)
253 if not inner:
254 return str(exc)
255 return "; ".join(_flattened_causes(e) for e in inner)
256
257
258 def _has_memory_store(session: BetaManagedAgentsSession) -> bool:
259 """True when the session has at least one memory store attached."""
260 return any(r.type == "memory_store" for r in session.resources)
261
262
263 def _sessions_token_from_secret(secret: str | None) -> str | None:
264 """Extract the per-item sessions token from a work item's `secret` payload.
265
266 The `secret` the poll response populates is not itself a credential: it
267 is a URL-safe base64 JSON payload bundling the per-item material — the
268 `sessions_token` (the bearer for this item's work lifecycle and
269 session-level calls) plus ingress / source tokens this worker does not
270 consume. Returns the sessions token, or `None` (the caller then falls
271 back to the environment key, or fails the item when there is none) when
272 the payload is missing, doesn't decode, or carries no token. Never log
273 the payload or anything extracted from it.
274 """
275 if not secret:
276 return None
277 try:
278 # The payload may arrive without base64 padding; restore it.
279 decoded = base64.urlsafe_b64decode(secret + "=" * (-len(secret) % 4))
280 parsed: object = json.loads(decoded)
281 except (ValueError, TypeError):
282 return None
283 if not isinstance(parsed, dict):
284 return None
285 payload = cast("dict[str, object]", parsed)
286 token = payload.get("sessions_token")
287 return token if isinstance(token, str) and token else None
288
289
290 def _require(value: str | None, *, name: str, env_var: str) -> str:
291 """Fall back to `env_var` for `value`; raise a clear error if still empty.
292
293 The `ANTHROPIC_*` env vars are the ones the `ant worker poll --on-work`
294 command sets on the process it spawns for a claimed work item.
295 """
296 resolved = value or os.environ.get(env_var)
297 if not resolved:
298 raise ValueError(f"handle_item: {name} is required — pass it or set {env_var}")
299 return resolved
300
301
302 class EnvironmentWorker:
303 """Run a self-hosted environment worker.
304
305 Composed from the control-plane poller (`client.beta.environments.work.poller`)
306 and the per-session `SessionToolRunner`. For each claimed `session`
307 work item it builds the per-session `AgentToolContext` and downloads
308 the session agent's skills, then runs a session tool runner for the session
309 *while* heartbeating the work-item lease in parallel; on exit it force-stops
310 the work item (unless the lease was lost, in which case the item is left to
311 whoever holds it now) and loops to the next one.
312
313 The `environment_key` is the worker's standing credential: polling
314 always uses it, and per-session calls fall back to it when a work item's
315 `secret` doesn't yield a sessions token (every request rides a
316 Bearer-only scoped sub-client, never the parent client's `X-Api-Key`).
317 `handle_item` can run without it when the work item's `secret`
318 carries a sessions token — that token then authorizes every per-item call.
319
320 Async only — `run` loops forever, so bound it (cancel the task or wrap
321 it in `asyncio.wait_for`) when you want it to stop.
322
323 Use `handle_item` if you already hold a claimed work item (e.g. a
324 `worker poll --on-work` script handed one to a fresh process) and just
325 want the per-item flow without the poll loop — with no arguments it reads the
326 `ANTHROPIC_*` env vars that command sets, so `environment_id` (only used
327 by `run`) isn't needed.
328
329 Prefer `client.beta.environments.work.worker(...)` to build one; the direct
330 constructor below is equivalent.
331
332 Example:
333
334 ```py
335 from anthropic import AsyncAnthropic
336
337 client = AsyncAnthropic()
338
339 # Long-running daemon: poll for work, serve each session, loop.
340 await client.beta.environments.work.worker(
341 environment_id=environment_id,
342 environment_key=environment_key,
343 workdir="/workspace",
344 ).run()
345
346 # Already-claimed item (e.g. inside `ant worker poll --on-work ...`):
347 await client.beta.environments.work.worker(workdir="/workspace").handle_item()
348
349 # Equivalent, constructing the worker directly:
350 from anthropic.lib.environments import EnvironmentWorker
351
352 await EnvironmentWorker(client, workdir="/workspace").handle_item()
353 ```
354
355 Args:
356 client: The async Anthropic client.
357 environment_id: The self-hosted environment to poll for work. Required by
358 `run`; not used by `handle_item`.
359 environment_key: The environment key — the worker's standing credential.
360 Used as the Bearer credential on the scoped sub-clients the worker
361 constructs for the control-plane (poll / ack / stop) and session-level
362 (events stream / list / send + heartbeat / force-stop) calls, except
363 where a claimed item's own `secret` takes precedence (see the class
364 docstring). Required by `run`; `handle_item` falls back to
365 it (then to `ANTHROPIC_ENVIRONMENT_KEY`) when not passed one, and
366 requires it only when the work item carries no `work_secret`.
367 tools: Tools to expose to each claimed session. Either a fixed list, or a
368 factory invoked once per session with that session's
369 `AgentToolContext`. Defaults to
370 `beta_agent_toolset_20260401(env)` (the standard
371 `agent_toolset_20260401` set bound to the per-session context).
372 Async tools share the event loop with the lease heartbeat, so keep
373 them non-blocking.
374 workdir: Base directory for the per-session `AgentToolContext`.
375 Defaults to `os.getcwd` captured when the worker is constructed
376 (matches the TS worker's `process.cwd()`-at-construction), so a
377 `chdir` between constructing the worker and serving a session does not
378 change where tools resolve paths.
379 unrestricted_paths: Deprecated and no longer accepted; passing either value
380 raises `TypeError` (see `AgentToolContext`).
381 max_idle: Forwarded to the session tool runner — seconds to keep running
382 after the session goes idle with `stop_reason` `end_turn`. Defaults
383 to `anthropic.lib.environments.DEFAULT_MAX_IDLE` (60s). `None`
384 disables it.
385 memory_sync_interval: How often (seconds) to sync the session's
386 attached memory stores back while it runs — checked after each
387 dispatched tool call, plus one final sync when the session ends
388 cleanly. Defaults to `DEFAULT_MEMORY_SYNC_INTERVAL` (15s).
389 The interval floors at `MIN_MEMORY_SYNC_INTERVAL` (5s): any
390 value below it raises `ValueError` — each sync lists every
391 attached store, and a tighter cadence would hammer the memory
392 endpoints.
393 A session that ends on an error or cancel instead gets a
394 push-only flush — best-effort, bounded by
395 `MEMORY_FLUSH_TIMEOUT` like the final sync, with a warning
396 logged when either bound cuts work off; it deletes and pulls
397 nothing, so an errored session can still lose its last edits.
398 `None` disables memory download and sync entirely. Memory
399 stores are only touched for work items whose `secret` carries a
400 `sessions_token`; while memory sync is enabled, a work item
401 without one fails when its session has memory stores attached,
402 because those stores cannot be mounted without the token. With
403 `None` the same item runs, without memory, and nothing is
404 logged — disabling sync is the operator's explicit choice.
405 memory_sync_deletions: Whether a file deleted locally in a memory
406 store's folder may delete its server memory. `"log_only"` runs
407 the same checks and only logs — use it to watch a deployment
408 before trusting `"enabled"`; `"disabled"` never deletes.
409 Uploads and pulls are unaffected. Defaults to `"enabled"`.
410 worker_id: Optional identifier sent on each poll. Defaults to a unique,
411 hostname-prefixed id.
412 extra_headers: Optional headers passed through per request on every
413 call the worker makes (poll / ack / stop / heartbeat and the session
414 tool runner's event stream / list / send). They are threaded into
415 each call's `extra_headers=` and never assigned onto the client, so
416 client state is not mutated. Auth and `x-stainless-helper` are
417 supplied by the worker's scoped sub-clients (and the parent client's
418 `default_headers` propagate via their `client.copy()`); a header
419 given here overrides a scoped client's same-named default for that
420 request, so use it for caller passthrough (e.g. trace ids), not auth.
421 """
422
423 @overload
424 def __init__(
425 self,
426 client: AsyncAnthropic,
427 *,
428 environment_id: str | None = None,
429 environment_key: str | None = None,
430 tools: EnvironmentWorkerTools | None = None,
431 workdir: str | os.PathLike[str] | None = None,
432 max_file_bytes: int | None | NotGiven = not_given,
433 max_idle: float | None = DEFAULT_MAX_IDLE,
434 memory_sync_interval: float | None = DEFAULT_MEMORY_SYNC_INTERVAL,
435 memory_sync_deletions: MemoryDeleteMode = "enabled",
436 worker_id: str | None = None,
437 extra_headers: Headers | None = None,
438 ) -> None: ...
439
440 @overload
441 @deprecated(UNRESTRICTED_PATHS_DEPRECATION)
442 def __init__(
443 self,
444 client: AsyncAnthropic,
445 *,
446 environment_id: str | None = None,
447 environment_key: str | None = None,
448 tools: EnvironmentWorkerTools | None = None,
449 workdir: str | os.PathLike[str] | None = None,
450 unrestricted_paths: bool,
451 max_file_bytes: int | None | NotGiven = not_given,
452 max_idle: float | None = DEFAULT_MAX_IDLE,
453 memory_sync_interval: float | None = DEFAULT_MEMORY_SYNC_INTERVAL,
454 memory_sync_deletions: MemoryDeleteMode = "enabled",
455 worker_id: str | None = None,
456 extra_headers: Headers | None = None,
457 ) -> None: ...
458
459 def __init__(
460 self,
461 client: AsyncAnthropic,
462 *,
463 environment_id: str | None = None,
464 environment_key: str | None = None,
465 tools: EnvironmentWorkerTools | None = None,
466 workdir: str | os.PathLike[str] | None = None,
467 unrestricted_paths: bool | NotGiven = not_given,
468 max_file_bytes: int | None | NotGiven = not_given,
469 max_idle: float | None = DEFAULT_MAX_IDLE,
470 memory_sync_interval: float | None = DEFAULT_MEMORY_SYNC_INTERVAL,
471 memory_sync_deletions: MemoryDeleteMode = "enabled",
472 worker_id: str | None = None,
473 extra_headers: Headers | None = None,
474 ) -> None:
475 reject_unrestricted_paths(unrestricted_paths)
476 self._client = client
477 self._environment_id = environment_id
478 self._environment_key = environment_key
479 self._tools = tools
480 # Snapshot the cwd at construction time when no explicit workdir was
481 # given (TS parity: `process.cwd()` captured up front). Resolving "."
482 # lazily at first tool use would instead pick up any intervening chdir.
483 self._workdir: str | os.PathLike[str] = os.getcwd() if workdir is None else workdir
484 self._max_file_bytes = max_file_bytes
485 self._max_idle = max_idle
486 if memory_sync_interval is not None:
487 _check_sync_interval(memory_sync_interval)
488 self._memory_sync_interval = memory_sync_interval
489 self._memory_sync_deletions: MemoryDeleteMode = memory_sync_deletions
490 self._worker_id = worker_id
491 self._extra_headers = extra_headers
492
493 def _tools_for(self, env: AgentToolContext) -> Sequence[BetaAnyRunnableTool]:
494 if callable(self._tools):
495 return self._tools(env)
496 if self._tools is not None:
497 return self._tools
498 # Lazy import: keeps the host-only `agent_toolset` module out of this
499 # module's import graph (see the note next to the imports).
500 from ..tools.agent_toolset import beta_agent_toolset_20260401
501
502 return beta_agent_toolset_20260401(env)
503
504 async def run(self) -> None:
505 """Poll the environment and service each claimed session until cancelled.
506
507 Loops forever; cancel the task (or wrap it in `asyncio.wait_for`)
508 to stop it. Equivalent to claiming work items via
509 `client.beta.environments.work.poller` and running the per-item flow
510 for each.
511
512 Raises:
513 ValueError: if `environment_id` / `environment_key` were not passed
514 to the constructor.
515 """
516 environment_id = self._environment_id
517 environment_key = self._environment_key
518 if environment_id is None or environment_key is None:
519 raise ValueError("EnvironmentWorker.run: environment_id and environment_key are required to poll for work")
520 # Poll/ack/stop calls run through a Bearer-only sub-client tagged with
521 # the poller's helper telemetry. `_handle_item` builds its own
522 # `environments-worker`-tagged sub-client for the heartbeat / force-stop.
523 poll_client = _copy_client_with_bearer_auth(
524 self._client, auth_token=environment_key, helper="environments-work-poller"
525 )
526 async for work_item in aiter_work(
527 poll_client.beta.environments.work,
528 environment_id=environment_id,
529 worker_id=self._worker_id,
530 auto_stop=False,
531 extra_headers=self._extra_headers,
532 ):
533 try:
534 await self._handle_item(work_item, environment_key)
535 except Exception as e: # noqa: BLE001
536 # One bad item fails that item, not the worker: the teardown
537 # already stopped or released it, so polling continues.
538 # Cancellation is a BaseException and still ends the loop.
539 log.error("work item failed work_id=%s error=%s", work_item.id, _flattened_causes(e))
540
541 async def handle_item(
542 self,
543 *,
544 work_id: str | None = None,
545 environment_id: str | None = None,
546 session_id: str | None = None,
547 environment_key: str | None = None,
548 work_secret: str | None = None,
549 ) -> None:
550 """Service a single, already-claimed work item without the poll loop.
551
552 Builds the per-session `AgentToolContext` (workdir from this
553 worker's options) and downloads the session agent's skills, then runs a
554 `SessionToolRunner` for the session *while* heartbeating the
555 work-item lease in parallel, and force-stops the work item on exit
556 (whether the runner finishes normally, raises, or the control plane
557 signals shutdown). The one exception is a lost lease: the item then
558 belongs to the queue or another worker and is left alone.
559
560 Use this when something else does the claiming — e.g. a
561 `worker poll --on-work` script that hands an already-claimed item to a
562 fresh process. `work_id` / `environment_id` / `session_id` fall
563 back to `ANTHROPIC_WORK_ID` / `ANTHROPIC_ENVIRONMENT_ID` /
564 `ANTHROPIC_SESSION_ID` (the env vars that command sets) when not
565 passed; `environment_key` resolves in order: the explicit argument,
566 then this worker's own `environment_key`, then
567 `ANTHROPIC_ENVIRONMENT_KEY` — so with no arguments inside that command
568 it just works. It is required only when no `work_secret` is present:
569 a sandbox that hands the process only the work secret (e.g. a pod that
570 must never hold the environment key) runs on the secret's sessions
571 token alone.
572
573 `work_secret` is the work item's per-item `secret` payload from the
574 poll response, falling back to `ANTHROPIC_WORK_SECRET`. Unlike the
575 others it is optional. When present, the sessions token extracted from
576 it is preferred as the Bearer credential for this item's heartbeat,
577 force-stop, and session calls. When it yields no token, those calls use
578 `environment_key` — and with no `environment_key` either, the item
579 fails rather than run unauthenticated.
580
581 Non-session work items are ignored (but still force-stopped so the
582 lease doesn't sit until TTL).
583
584 Raises:
585 ValueError: if any of `work_id` / `environment_id` / `session_id`
586 is still empty after the fallbacks; if `environment_key` is, while
587 no `work_secret` is present; or if the `work_secret` yields no
588 sessions token and there is no `environment_key` to fall back to.
589 SessionMemoryError: if the session has memory stores attached but
590 they cannot be mounted — the work item carried no
591 `sessions_token`, or a store failed to download. May arrive
592 wrapped in an `ExceptionGroup` by the task group.
593 """
594 work_id = _require(work_id, name="work_id", env_var="ANTHROPIC_WORK_ID")
595 environment_id = _require(environment_id, name="environment_id", env_var="ANTHROPIC_ENVIRONMENT_ID")
596 session_id = _require(session_id, name="session_id", env_var="ANTHROPIC_SESSION_ID")
597
598 # The per-item secret is optional: explicit arg -> ANTHROPIC_WORK_SECRET
599 # -> None (use the environment key).
600 work_secret = work_secret or os.environ.get("ANTHROPIC_WORK_SECRET")
601
602 # environment_key resolves: explicit arg -> this worker's own key ->
603 # ANTHROPIC_ENVIRONMENT_KEY. Required only when there is no work
604 # secret; a secret's sessions token can carry the item on its own.
605 environment_key = (
606 environment_key or self._environment_key or os.environ.get("ANTHROPIC_ENVIRONMENT_KEY") or None
607 )
608 if environment_key is None and work_secret is None:
609 raise ValueError("handle_item: environment_key is required — pass it or set ANTHROPIC_ENVIRONMENT_KEY")
610
611 # The per-item flow only reads work.id / work.environment_id /
612 # work.secret / work.data.type / work.data.id, so a minimally populated
613 # model is enough.
614 work_item = BetaSelfHostedWork.model_construct(
615 id=work_id,
616 environment_id=environment_id,
617 secret=work_secret,
618 data=BetaSessionWorkData.model_construct(type="session", id=session_id),
619 )
620 await self._handle_item(work_item, environment_key)
621
622 async def _handle_item(self, work_item: BetaSelfHostedWork, environment_key: str | None) -> None:
623 """The per-item body shared by `run`'s poll loop and `handle_item`.
624
625 Runs a `SessionToolRunner` for the work item's session while
626 heartbeating its lease, force-stopping the work item on exit unless the
627 lease was lost. All control-plane traffic for this work item —
628 heartbeat + force-stop — flows through a Bearer-only sub-client built
629 here; the session tool runner builds its own
630 `session-tool-runner`-tagged sub-client internally.
631
632 When the poll response carried a per-item `secret` (a short-lived
633 payload scoped to this work item), the sessions token extracted from
634 it is preferred over `environment_key` as the Bearer credential for
635 those per-item calls. A secret that yields no token falls back to
636 `environment_key`; with no key available either, the item fails
637 rather than run unauthenticated.
638 """
639 # Lazy import: keeps the host-only `agent_toolset` module out of this
640 # module's import graph (see the note next to the imports).
641 from ..tools.agent_toolset import AgentToolContext
642
643 # The per-item credential: the sessions token carried inside the work
644 # item's secret payload when the server issued one, otherwise the
645 # environment key. `getattr` because items synthesized by older
646 # callers (or test fakes) may predate the field. Never log this value.
647 secret = getattr(work_item, "secret", None)
648 sessions_token = _sessions_token_from_secret(secret)
649 item_credential = sessions_token or environment_key
650 if item_credential is None:
651 raise ValueError(
652 "the work item's secret payload yielded no sessions token and no environment key "
653 "is available; provide a secret whose payload carries a sessions_token, or an "
654 f"environment key (pass one or set ANTHROPIC_ENVIRONMENT_KEY) work_id={work_item.id}"
655 )
656 if secret and sessions_token is None:
657 log.warning(
658 "work item carried a secret payload but no sessions token could be extracted; "
659 "falling back to the environment key work_id=%s",
660 work_item.id,
661 )
662
663 # `environments-worker`-scoped sub-client for the heartbeat and
664 # force-stop calls this item drives. The session tool runner is given
665 # the parent client + the same per-item credential and builds its own
666 # sub-client.
667 worker_client = _copy_client_with_bearer_auth(
668 self._client, auth_token=item_credential, helper="environments-worker"
669 )
670 work_res = worker_client.beta.environments.work
671 # Memory stores: the memory_stores endpoints accept the per-item
672 # sessions token but reject the environment key, so download and sync
673 # only run when the item carried a usable secret (and the interval is
674 # set). `worker_client` is already scoped to that token then, so the
675 # memory calls ride the same sub-client.
676 interval = self._memory_sync_interval
677 stores: SessionMemoryStores | None = None
678 if sessions_token is not None and interval is not None:
679 stores = SessionMemoryStores(
680 worker_client,
681 workdir=self._workdir,
682 sync_interval=interval,
683 sync_deletions=self._memory_sync_deletions,
684 )
685 else:
686 log.debug("memory stores disabled for this item work_id=%s", work_item.id)
687 lease = _Lease()
688 try:
689 # The queue also sends "healthcheck" items, which the generated type does not model.
690 work_type: str = work_item.data.type
691 if work_type != "session":
692 log.debug("skipping non-session work item work_id=%s type=%s", work_item.id, work_type)
693 return
694 session_id = work_item.data.id
695 clean_end = False
696 async with anyio.create_task_group() as tg:
697 # Latest server-reported lease TTL; the runner reads it back as
698 # its tool-result send retry window.
699 lease_ttl: float | None = None
700
701 def _on_lease_ttl(ttl: float) -> None:
702 nonlocal lease_ttl
703 lease_ttl = ttl
704
705 async def _heartbeat(
706 work_id: str = work_item.id,
707 environment_id: str = work_item.environment_id,
708 ) -> None:
709 try:
710 await _heartbeat_loop(
711 work_res,
712 work_id=work_id,
713 environment_id=environment_id,
714 lease=lease,
715 extra_headers=self._extra_headers,
716 on_lease_ttl=_on_lease_ttl,
717 )
718 finally:
719 tg.cancel_scope.cancel()
720
721 # Start the lease heartbeat BEFORE entering AgentToolContext.
722 # AgentToolContext.__aenter__ downloads and extracts every skill
723 # the session agent has; that can take longer than the lease
724 # TTL. If the first heartbeat only fired *after* the download
725 # (the old ordering), a slow download would let the lease lapse
726 # and another worker reclaim the item — both workers then serve
727 # the same session (split-brain). Heartbeating concurrently with
728 # the download keeps the lease ours the entire time. The
729 # heartbeat only needs work_id / environment_id, both available
730 # before any download.
731 tg.start_soon(_heartbeat)
732
733 # Drive AgentToolContext's enter/exit explicitly rather than via
734 # `async with` so its async cleanup (bash subprocess teardown
735 # + downloaded-skill removal) runs *shielded*: by the time we
736 # tear down, the heartbeat may have cancelled the task-group
737 # scope (lost lease), and that cancel must not abort the
738 # subprocess kill / skill rmtree. A heartbeat-driven cancel
739 # during __aenter__ still interrupts an in-progress skill
740 # download (the desired split-brain protection) — __aexit__ is
741 # then a no-op since no bash/skills were set up.
742 # One session fetch, shared by the skills download and the
743 # memory-store download — two fetches could disagree about the
744 # attached resources.
745 session = await worker_client.beta.sessions.retrieve(session_id)
746 # Only here, after the fetch, can we tell a session that
747 # simply has no memory from one whose memory we cannot mount.
748 # The interval knob is a deliberate opt-out and stays quiet.
749 if stores is None and interval is not None and _has_memory_store(session):
750 raise SessionMemoryError(
751 "this session has memory stores attached, but the work item carried no "
752 "sessions token; the memory endpoints reject the environment key, so the "
753 "session's memories cannot be mounted. The work item was failed rather "
754 "than run without them, matching how hosted sandboxes behave "
755 f"(work_id={work_item.id}, session_id={session_id})"
756 )
757 env = AgentToolContext(
758 workdir=self._workdir,
759 max_file_bytes=self._max_file_bytes,
760 client=worker_client,
761 session=session,
762 )
763 try:
764 await env.__aenter__()
765 if stores is not None:
766 await stores.download(session)
767 # A store mounted outside the workdir must stay reachable
768 # by the file tools; read-only stores still refuse writes
769 # via read_only_roots.
770 env.allowed_roots = stores.roots
771 env.read_only_roots = stores.read_only_roots
772 tools = self._tools_for(env)
773 async with _run_session_tools(
774 self._client,
775 session_id,
776 tools=tools,
777 max_idle=self._max_idle,
778 # Despite the parameter name, this is just the
779 # runner's Bearer credential (see its docstring).
780 environment_key=item_credential,
781 extra_headers=self._extra_headers,
782 send_retry_window=lambda: lease_ttl,
783 ) as calls:
784 async for _ in calls:
785 if stores is not None:
786 await stores.sync_if_due()
787 # The last full sync runs in the teardown below,
788 # after the bash subprocesses are killed — its
789 # waived delete window must not race a writer.
790 clean_end = True
791 finally:
792 # The heartbeat keeps the lease alive until this teardown is done.
793 with anyio.CancelScope(shield=True):
794 try:
795 # First — so nothing is still writing when the syncs read.
796 await env.__aexit__(None, None, None)
797 finally:
798 if stores is not None:
799 if clean_end:
800 with anyio.move_on_after(MEMORY_FLUSH_TIMEOUT) as scope:
801 await stores.finish()
802 if scope.cancelled_caught:
803 log.warning(
804 "final memory sync cut off after %gs; the flush that follows still "
805 "uploads changed files work_id=%s session_id=%s",
806 MEMORY_FLUSH_TIMEOUT,
807 work_item.id,
808 session_id,
809 )
810 # Push whatever is still on disk before dispose
811 # removes it — even after finish(), which may
812 # have failed or timed out; a clean flush is free.
813 with anyio.move_on_after(MEMORY_FLUSH_TIMEOUT) as scope:
814 await stores.flush_writes()
815 if scope.cancelled_caught:
816 log.warning(
817 "memory flush cut off after %gs; changed files it had not uploaded yet "
818 "are not saved work_id=%s session_id=%s",
819 MEMORY_FLUSH_TIMEOUT,
820 work_item.id,
821 session_id,
822 )
823 await stores.dispose()
824 lease.finish(_LeaseEndReason.RUNNER_DONE)
825 tg.cancel_scope.cancel()
826 finally:
827 # Stop only an item this worker still holds — after a lost lease it
828 # belongs to the queue or another worker. A 409 means it already
829 # stopped; shielded so the post survives surrounding cancellation.
830 if lease.lost:
831 log.info(
832 "lease lost; released work_id=%s session_id=%s without stopping it",
833 work_item.id,
834 work_item.data.id,
835 )
836 else:
837 with anyio.CancelScope(shield=True):
838 try:
839 await work_res.stop(
840 work_item.id,
841 environment_id=work_item.environment_id,
842 force=True,
843 extra_headers=self._extra_headers,
844 )
845 except Exception as e:
846 if not _is_status(e, 409):
847 log.error("force-stop on exit failed work_id=%s error=%s", work_item.id, e)