Debian Codegraph @

src/anthropic/resources/beta/environments/work.py

raw
1 from __future__ import annotations
2
3 import os
4 from typing import TYPE_CHECKING, Dict, List, Optional, cast, overload
5 from itertools import chain
6 from typing_extensions import deprecated
7
8 import httpx2
9
10 if TYPE_CHECKING:
11 from collections.abc import AsyncIterator
12
13 from ...._client import AsyncAnthropic
14 from ....lib.tools._memories import MemoryDeleteMode
15 from ....lib.environments._worker import EnvironmentWorker, EnvironmentWorkerTools
16
17 from ...._types import Body, Omit, Query, Headers, NotGiven, omit, not_given
18 from ...._utils import is_given, path_template, strip_not_given
19 from ...._compat import cached_property
20 from ...._resource import SyncAPIResource, AsyncAPIResource
21 from ...._response import (
22 to_raw_response_wrapper,
23 to_streamed_response_wrapper,
24 async_to_raw_response_wrapper,
25 async_to_streamed_response_wrapper,
26 )
27 from ....pagination import SyncPageCursor, AsyncPageCursor
28 from ...._base_client import AsyncPaginator, make_request_options
29 from ....lib.tools._deprecations import UNRESTRICTED_PATHS_DEPRECATION, reject_unrestricted_paths
30 from ....types.anthropic_beta_param import AnthropicBetaParam
31 from ....types.beta.environments.beta_self_hosted_work import BetaSelfHostedWork
32 from ....types.beta.environments.beta_self_hosted_work_queue_stats import BetaSelfHostedWorkQueueStats
33 from ....types.beta.environments.beta_self_hosted_work_heartbeat_response import BetaSelfHostedWorkHeartbeatResponse
34
35 __all__ = ["Work", "AsyncWork"]
36
37
38 class Work(SyncAPIResource):
39 @cached_property
40 def with_raw_response(self) -> WorkWithRawResponse:
41 """
42 This property can be used as a prefix for any HTTP method call to return
43 the raw response object instead of the parsed content.
44
45 For more information, see https://www.github.com/anthropics/anthropic-sdk-python#accessing-raw-response-data-eg-headers
46 """
47 return WorkWithRawResponse(self)
48
49 @cached_property
50 def with_streaming_response(self) -> WorkWithStreamingResponse:
51 """
52 An alternative to `.with_raw_response` that doesn't eagerly read the response body.
53
54 For more information, see https://www.github.com/anthropics/anthropic-sdk-python#with_streaming_response
55 """
56 return WorkWithStreamingResponse(self)
57
58 def retrieve(
59 self,
60 work_id: str,
61 *,
62 environment_id: str,
63 betas: List[AnthropicBetaParam] | Omit = omit,
64 workspace_id: str | Omit = omit,
65 # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
66 # The extra values given here take precedence over values defined on the client or passed to this method.
67 extra_headers: Headers | None = None,
68 extra_query: Query | None = None,
69 extra_body: Body | None = None,
70 timeout: float | httpx2.Timeout | None | NotGiven = not_given,
71 ) -> BetaSelfHostedWork:
72 """
73 Note: these endpoints are called automatically by the pre-built environment
74 worker provided in the SDKs and CLI, for orchestrating sessions with self-hosted
75 sandbox environments. They are included here as a reference; you do not need to
76 invoke them directly.
77
78 Retrieve detailed information about a specific work item.
79
80 Args:
81 betas: Optional header to specify the beta version(s) you want to use.
82
83 workspace_id: Optional header to select the Workspace for this request. The value is a
84 Workspace ID (for example, `wrkspc_011CZkZaBF1tNoB5wlCeusgy`).
85
86 Only needed for credentials that can act on more than one Workspace. A
87 credential that belongs to a specific Workspace may omit it; if sent, it must
88 match that Workspace.
89
90 extra_headers: Send extra headers
91
92 extra_query: Add additional query parameters to the request
93
94 extra_body: Add additional JSON properties to the request
95
96 timeout: Override the client-level default timeout for this request, in seconds
97 """
98 if not environment_id:
99 raise ValueError(f"Expected a non-empty value for `environment_id` but received {environment_id!r}")
100 if not work_id:
101 raise ValueError(f"Expected a non-empty value for `work_id` but received {work_id!r}")
102 extra_headers = {
103 **strip_not_given(
104 {
105 "anthropic-beta": ",".join(chain((str(e) for e in betas), ["managed-agents-2026-04-01"]))
106 if is_given(betas)
107 else not_given,
108 "anthropic-workspace-id": workspace_id,
109 }
110 ),
111 **(extra_headers or {}),
112 }
113 extra_headers = {"anthropic-beta": "managed-agents-2026-04-01", **(extra_headers or {})}
114 return self._get(
115 path_template(
116 "/v1/environments/{environment_id}/work/{work_id}?beta=true",
117 environment_id=environment_id,
118 work_id=work_id,
119 ),
120 options=make_request_options(
121 extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
122 ),
123 cast_to=BetaSelfHostedWork,
124 )
125
126 def update(
127 self,
128 work_id: str,
129 *,
130 environment_id: str,
131 metadata: Dict[str, Optional[str]],
132 betas: List[AnthropicBetaParam] | Omit = omit,
133 workspace_id: str | Omit = omit,
134 # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
135 # The extra values given here take precedence over values defined on the client or passed to this method.
136 extra_headers: Headers | None = None,
137 extra_query: Query | None = None,
138 extra_body: Body | None = None,
139 timeout: float | httpx2.Timeout | None | NotGiven = not_given,
140 ) -> BetaSelfHostedWork:
141 """
142 Note: these endpoints are called automatically by the pre-built environment
143 worker provided in the SDKs and CLI, for orchestrating sessions with self-hosted
144 sandbox environments. They are included here as a reference; you do not need to
145 invoke them directly.
146
147 Update work item metadata with merge semantics.
148
149 Args:
150 metadata: Metadata patch. Set a key to a string to upsert it, or to null to delete it.
151 Omit the field to preserve existing metadata.
152
153 betas: Optional header to specify the beta version(s) you want to use.
154
155 workspace_id: Optional header to select the Workspace for this request. The value is a
156 Workspace ID (for example, `wrkspc_011CZkZaBF1tNoB5wlCeusgy`).
157
158 Only needed for credentials that can act on more than one Workspace. A
159 credential that belongs to a specific Workspace may omit it; if sent, it must
160 match that Workspace.
161
162 extra_headers: Send extra headers
163
164 extra_query: Add additional query parameters to the request
165
166 extra_body: Add additional JSON properties to the request
167
168 timeout: Override the client-level default timeout for this request, in seconds
169 """
170 if not environment_id:
171 raise ValueError(f"Expected a non-empty value for `environment_id` but received {environment_id!r}")
172 if not work_id:
173 raise ValueError(f"Expected a non-empty value for `work_id` but received {work_id!r}")
174 extra_headers = {
175 **strip_not_given(
176 {
177 "anthropic-beta": ",".join(chain((str(e) for e in betas), ["managed-agents-2026-04-01"]))
178 if is_given(betas)
179 else not_given,
180 "anthropic-workspace-id": workspace_id,
181 }
182 ),
183 **(extra_headers or {}),
184 }
185 extra_headers = {"anthropic-beta": "managed-agents-2026-04-01", **(extra_headers or {})}
186 return self._post(
187 path_template(
188 "/v1/environments/{environment_id}/work/{work_id}?beta=true",
189 environment_id=environment_id,
190 work_id=work_id,
191 ),
192 body={"metadata": metadata},
193 options=make_request_options(
194 extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
195 ),
196 cast_to=BetaSelfHostedWork,
197 )
198
199 def list(
200 self,
201 environment_id: str,
202 *,
203 limit: int | Omit = omit,
204 page: Optional[str] | Omit = omit,
205 betas: List[AnthropicBetaParam] | Omit = omit,
206 # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
207 # The extra values given here take precedence over values defined on the client or passed to this method.
208 extra_headers: Headers | None = None,
209 extra_query: Query | None = None,
210 extra_body: Body | None = None,
211 timeout: float | httpx2.Timeout | None | NotGiven = not_given,
212 ) -> SyncPageCursor[BetaSelfHostedWork]:
213 """
214 Note: these endpoints are called automatically by the pre-built environment
215 worker provided in the SDKs and CLI, for orchestrating sessions with self-hosted
216 sandbox environments. They are included here as a reference; you do not need to
217 invoke them directly.
218
219 List work items in an environment.
220
221 Args:
222 limit: Maximum number of work items to return
223
224 page: Opaque cursor from previous response for pagination
225
226 betas: Optional header to specify the beta version(s) you want to use.
227
228 extra_headers: Send extra headers
229
230 extra_query: Add additional query parameters to the request
231
232 extra_body: Add additional JSON properties to the request
233
234 timeout: Override the client-level default timeout for this request, in seconds
235 """
236 if not environment_id:
237 raise ValueError(f"Expected a non-empty value for `environment_id` but received {environment_id!r}")
238 extra_headers = {
239 **strip_not_given(
240 {
241 "anthropic-beta": ",".join(chain((str(e) for e in betas), ["managed-agents-2026-04-01"]))
242 if is_given(betas)
243 else not_given
244 }
245 ),
246 **(extra_headers or {}),
247 }
248 extra_headers = {"anthropic-beta": "managed-agents-2026-04-01", **(extra_headers or {})}
249 return self._get_api_list(
250 path_template("/v1/environments/{environment_id}/work?beta=true", environment_id=environment_id),
251 page=SyncPageCursor[BetaSelfHostedWork],
252 options=make_request_options(
253 extra_headers=extra_headers,
254 extra_query=extra_query,
255 extra_body=extra_body,
256 timeout=timeout,
257 query={
258 "limit": limit,
259 "page": page,
260 },
261 ),
262 model=BetaSelfHostedWork,
263 )
264
265 def ack(
266 self,
267 work_id: str,
268 *,
269 environment_id: str,
270 betas: List[AnthropicBetaParam] | Omit = omit,
271 # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
272 # The extra values given here take precedence over values defined on the client or passed to this method.
273 extra_headers: Headers | None = None,
274 extra_query: Query | None = None,
275 extra_body: Body | None = None,
276 timeout: float | httpx2.Timeout | None | NotGiven = not_given,
277 ) -> BetaSelfHostedWork:
278 """
279 Note: these endpoints are called automatically by the pre-built environment
280 worker provided in the SDKs and CLI, for orchestrating sessions with self-hosted
281 sandbox environments. They are included here as a reference; you do not need to
282 invoke them directly.
283
284 Acknowledge receipt of a work item, transitioning it from 'queued' to 'starting'
285 and removing it from the queue.
286
287 Args:
288 betas: Optional header to specify the beta version(s) you want to use.
289
290 extra_headers: Send extra headers
291
292 extra_query: Add additional query parameters to the request
293
294 extra_body: Add additional JSON properties to the request
295
296 timeout: Override the client-level default timeout for this request, in seconds
297 """
298 if not environment_id:
299 raise ValueError(f"Expected a non-empty value for `environment_id` but received {environment_id!r}")
300 if not work_id:
301 raise ValueError(f"Expected a non-empty value for `work_id` but received {work_id!r}")
302 extra_headers = {
303 **strip_not_given(
304 {
305 "anthropic-beta": ",".join(chain((str(e) for e in betas), ["managed-agents-2026-04-01"]))
306 if is_given(betas)
307 else not_given
308 }
309 ),
310 **(extra_headers or {}),
311 }
312 extra_headers = {"anthropic-beta": "managed-agents-2026-04-01", **(extra_headers or {})}
313 return self._post(
314 path_template(
315 "/v1/environments/{environment_id}/work/{work_id}/ack?beta=true",
316 environment_id=environment_id,
317 work_id=work_id,
318 ),
319 options=make_request_options(
320 extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
321 ),
322 cast_to=BetaSelfHostedWork,
323 )
324
325 def heartbeat(
326 self,
327 work_id: str,
328 *,
329 environment_id: str,
330 desired_ttl_seconds: Optional[int] | Omit = omit,
331 expected_last_heartbeat: Optional[str] | Omit = omit,
332 betas: List[AnthropicBetaParam] | Omit = omit,
333 # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
334 # The extra values given here take precedence over values defined on the client or passed to this method.
335 extra_headers: Headers | None = None,
336 extra_query: Query | None = None,
337 extra_body: Body | None = None,
338 timeout: float | httpx2.Timeout | None | NotGiven = not_given,
339 ) -> BetaSelfHostedWorkHeartbeatResponse:
340 """
341 Note: these endpoints are called automatically by the pre-built environment
342 worker provided in the SDKs and CLI, for orchestrating sessions with self-hosted
343 sandbox environments. They are included here as a reference; you do not need to
344 invoke them directly.
345
346 Record a heartbeat for a work item to maintain the lease.
347
348 Args:
349 desired_ttl_seconds: Desired TTL in seconds
350
351 expected_last_heartbeat: Expected last_heartbeat for conditional update (optimistic concurrency). Use
352 literal 'NO_HEARTBEAT' to claim an unclaimed lease (first heartbeat). For
353 subsequent heartbeats, echo the server's previous last_heartbeat value exactly.
354 Returns 412 Precondition Failed if the actual value doesn't match.
355
356 betas: Optional header to specify the beta version(s) you want to use.
357
358 extra_headers: Send extra headers
359
360 extra_query: Add additional query parameters to the request
361
362 extra_body: Add additional JSON properties to the request
363
364 timeout: Override the client-level default timeout for this request, in seconds
365 """
366 if not environment_id:
367 raise ValueError(f"Expected a non-empty value for `environment_id` but received {environment_id!r}")
368 if not work_id:
369 raise ValueError(f"Expected a non-empty value for `work_id` but received {work_id!r}")
370 extra_headers = {
371 **strip_not_given(
372 {
373 "anthropic-beta": ",".join(chain((str(e) for e in betas), ["managed-agents-2026-04-01"]))
374 if is_given(betas)
375 else not_given
376 }
377 ),
378 **(extra_headers or {}),
379 }
380 extra_headers = {"anthropic-beta": "managed-agents-2026-04-01", **(extra_headers or {})}
381 return self._post(
382 path_template(
383 "/v1/environments/{environment_id}/work/{work_id}/heartbeat?beta=true",
384 environment_id=environment_id,
385 work_id=work_id,
386 ),
387 options=make_request_options(
388 extra_headers=extra_headers,
389 extra_query=extra_query,
390 extra_body=extra_body,
391 timeout=timeout,
392 query={
393 "desired_ttl_seconds": desired_ttl_seconds,
394 "expected_last_heartbeat": expected_last_heartbeat,
395 },
396 ),
397 cast_to=BetaSelfHostedWorkHeartbeatResponse,
398 )
399
400 def poll(
401 self,
402 environment_id: str,
403 *,
404 block_ms: Optional[int] | Omit = omit,
405 reclaim_older_than_ms: Optional[int] | Omit = omit,
406 betas: List[AnthropicBetaParam] | Omit = omit,
407 anthropic_worker_id: str | Omit = omit,
408 # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
409 # The extra values given here take precedence over values defined on the client or passed to this method.
410 extra_headers: Headers | None = None,
411 extra_query: Query | None = None,
412 extra_body: Body | None = None,
413 timeout: float | httpx2.Timeout | None | NotGiven = not_given,
414 ) -> Optional[BetaSelfHostedWork]:
415 """
416 Note: these endpoints are called automatically by the pre-built environment
417 worker provided in the SDKs and CLI, for orchestrating sessions with self-hosted
418 sandbox environments. They are included here as a reference; you do not need to
419 invoke them directly.
420
421 Long poll for work items in the queue.
422
423 Args:
424 block_ms: How long to wait for work to arrive before returning. Must be 1-999 in
425 milliseconds. Defaults to non-blocking (returns immediately if no work is
426 available).
427
428 reclaim_older_than_ms: Reclaim unacknowledged work items older than this many milliseconds. If omitted,
429 uses the default (5000ms).
430
431 betas: Optional header to specify the beta version(s) you want to use.
432
433 anthropic_worker_id: Unique identifier for the specific worker polling, used to track aggregated
434 environment-level work metrics in Console
435
436 extra_headers: Send extra headers
437
438 extra_query: Add additional query parameters to the request
439
440 extra_body: Add additional JSON properties to the request
441
442 timeout: Override the client-level default timeout for this request, in seconds
443 """
444 if not environment_id:
445 raise ValueError(f"Expected a non-empty value for `environment_id` but received {environment_id!r}")
446 extra_headers = {
447 **strip_not_given(
448 {
449 "anthropic-beta": ",".join(chain((str(e) for e in betas), ["managed-agents-2026-04-01"]))
450 if is_given(betas)
451 else not_given,
452 "Anthropic-Worker-ID": anthropic_worker_id,
453 }
454 ),
455 **(extra_headers or {}),
456 }
457 extra_headers = {"anthropic-beta": "managed-agents-2026-04-01", **(extra_headers or {})}
458 return self._get(
459 path_template("/v1/environments/{environment_id}/work/poll?beta=true", environment_id=environment_id),
460 options=make_request_options(
461 extra_headers=extra_headers,
462 extra_query=extra_query,
463 extra_body=extra_body,
464 timeout=timeout,
465 query={
466 "block_ms": block_ms,
467 "reclaim_older_than_ms": reclaim_older_than_ms,
468 },
469 ),
470 cast_to=BetaSelfHostedWork,
471 )
472
473 def stats(
474 self,
475 environment_id: str,
476 *,
477 betas: List[AnthropicBetaParam] | Omit = omit,
478 workspace_id: str | Omit = omit,
479 # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
480 # The extra values given here take precedence over values defined on the client or passed to this method.
481 extra_headers: Headers | None = None,
482 extra_query: Query | None = None,
483 extra_body: Body | None = None,
484 timeout: float | httpx2.Timeout | None | NotGiven = not_given,
485 ) -> BetaSelfHostedWorkQueueStats:
486 """
487 Get statistics about the work queue for an environment.
488
489 Args:
490 betas: Optional header to specify the beta version(s) you want to use.
491
492 workspace_id: Optional header to select the Workspace for this request. The value is a
493 Workspace ID (for example, `wrkspc_011CZkZaBF1tNoB5wlCeusgy`).
494
495 Only needed for credentials that can act on more than one Workspace. A
496 credential that belongs to a specific Workspace may omit it; if sent, it must
497 match that Workspace.
498
499 extra_headers: Send extra headers
500
501 extra_query: Add additional query parameters to the request
502
503 extra_body: Add additional JSON properties to the request
504
505 timeout: Override the client-level default timeout for this request, in seconds
506 """
507 if not environment_id:
508 raise ValueError(f"Expected a non-empty value for `environment_id` but received {environment_id!r}")
509 extra_headers = {
510 **strip_not_given(
511 {
512 "anthropic-beta": ",".join(chain((str(e) for e in betas), ["managed-agents-2026-04-01"]))
513 if is_given(betas)
514 else not_given,
515 "anthropic-workspace-id": workspace_id,
516 }
517 ),
518 **(extra_headers or {}),
519 }
520 extra_headers = {"anthropic-beta": "managed-agents-2026-04-01", **(extra_headers or {})}
521 return self._get(
522 path_template("/v1/environments/{environment_id}/work/stats?beta=true", environment_id=environment_id),
523 options=make_request_options(
524 extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
525 ),
526 cast_to=BetaSelfHostedWorkQueueStats,
527 )
528
529 def stop(
530 self,
531 work_id: str,
532 *,
533 environment_id: str,
534 force: bool | Omit = omit,
535 betas: List[AnthropicBetaParam] | Omit = omit,
536 workspace_id: str | Omit = omit,
537 # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
538 # The extra values given here take precedence over values defined on the client or passed to this method.
539 extra_headers: Headers | None = None,
540 extra_query: Query | None = None,
541 extra_body: Body | None = None,
542 timeout: float | httpx2.Timeout | None | NotGiven = not_given,
543 ) -> BetaSelfHostedWork:
544 """
545 Note: these endpoints are called automatically by the pre-built environment
546 worker provided in the SDKs and CLI, for orchestrating sessions with self-hosted
547 sandbox environments. They are included here as a reference; you do not need to
548 invoke them directly.
549
550 Stop a work item, initiating graceful or forced shutdown.
551
552 Args:
553 force: If true, immediately stop work without graceful shutdown
554
555 betas: Optional header to specify the beta version(s) you want to use.
556
557 workspace_id: Optional header to select the Workspace for this request. The value is a
558 Workspace ID (for example, `wrkspc_011CZkZaBF1tNoB5wlCeusgy`).
559
560 Only needed for credentials that can act on more than one Workspace. A
561 credential that belongs to a specific Workspace may omit it; if sent, it must
562 match that Workspace.
563
564 extra_headers: Send extra headers
565
566 extra_query: Add additional query parameters to the request
567
568 extra_body: Add additional JSON properties to the request
569
570 timeout: Override the client-level default timeout for this request, in seconds
571 """
572 if not environment_id:
573 raise ValueError(f"Expected a non-empty value for `environment_id` but received {environment_id!r}")
574 if not work_id:
575 raise ValueError(f"Expected a non-empty value for `work_id` but received {work_id!r}")
576 extra_headers = {
577 **strip_not_given(
578 {
579 "anthropic-beta": ",".join(chain((str(e) for e in betas), ["managed-agents-2026-04-01"]))
580 if is_given(betas)
581 else not_given,
582 "anthropic-workspace-id": workspace_id,
583 }
584 ),
585 **(extra_headers or {}),
586 }
587 extra_headers = {"anthropic-beta": "managed-agents-2026-04-01", **(extra_headers or {})}
588 return self._post(
589 path_template(
590 "/v1/environments/{environment_id}/work/{work_id}/stop?beta=true",
591 environment_id=environment_id,
592 work_id=work_id,
593 ),
594 body={"force": force},
595 options=make_request_options(
596 extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
597 ),
598 cast_to=BetaSelfHostedWork,
599 )
600
601
602 class AsyncWork(AsyncAPIResource):
603 @cached_property
604 def with_raw_response(self) -> AsyncWorkWithRawResponse:
605 """
606 This property can be used as a prefix for any HTTP method call to return
607 the raw response object instead of the parsed content.
608
609 For more information, see https://www.github.com/anthropics/anthropic-sdk-python#accessing-raw-response-data-eg-headers
610 """
611 return AsyncWorkWithRawResponse(self)
612
613 @cached_property
614 def with_streaming_response(self) -> AsyncWorkWithStreamingResponse:
615 """
616 An alternative to `.with_raw_response` that doesn't eagerly read the response body.
617
618 For more information, see https://www.github.com/anthropics/anthropic-sdk-python#with_streaming_response
619 """
620 return AsyncWorkWithStreamingResponse(self)
621
622 async def retrieve(
623 self,
624 work_id: str,
625 *,
626 environment_id: str,
627 betas: List[AnthropicBetaParam] | Omit = omit,
628 workspace_id: str | Omit = omit,
629 # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
630 # The extra values given here take precedence over values defined on the client or passed to this method.
631 extra_headers: Headers | None = None,
632 extra_query: Query | None = None,
633 extra_body: Body | None = None,
634 timeout: float | httpx2.Timeout | None | NotGiven = not_given,
635 ) -> BetaSelfHostedWork:
636 """
637 Note: these endpoints are called automatically by the pre-built environment
638 worker provided in the SDKs and CLI, for orchestrating sessions with self-hosted
639 sandbox environments. They are included here as a reference; you do not need to
640 invoke them directly.
641
642 Retrieve detailed information about a specific work item.
643
644 Args:
645 betas: Optional header to specify the beta version(s) you want to use.
646
647 workspace_id: Optional header to select the Workspace for this request. The value is a
648 Workspace ID (for example, `wrkspc_011CZkZaBF1tNoB5wlCeusgy`).
649
650 Only needed for credentials that can act on more than one Workspace. A
651 credential that belongs to a specific Workspace may omit it; if sent, it must
652 match that Workspace.
653
654 extra_headers: Send extra headers
655
656 extra_query: Add additional query parameters to the request
657
658 extra_body: Add additional JSON properties to the request
659
660 timeout: Override the client-level default timeout for this request, in seconds
661 """
662 if not environment_id:
663 raise ValueError(f"Expected a non-empty value for `environment_id` but received {environment_id!r}")
664 if not work_id:
665 raise ValueError(f"Expected a non-empty value for `work_id` but received {work_id!r}")
666 extra_headers = {
667 **strip_not_given(
668 {
669 "anthropic-beta": ",".join(chain((str(e) for e in betas), ["managed-agents-2026-04-01"]))
670 if is_given(betas)
671 else not_given,
672 "anthropic-workspace-id": workspace_id,
673 }
674 ),
675 **(extra_headers or {}),
676 }
677 extra_headers = {"anthropic-beta": "managed-agents-2026-04-01", **(extra_headers or {})}
678 return await self._get(
679 path_template(
680 "/v1/environments/{environment_id}/work/{work_id}?beta=true",
681 environment_id=environment_id,
682 work_id=work_id,
683 ),
684 options=make_request_options(
685 extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
686 ),
687 cast_to=BetaSelfHostedWork,
688 )
689
690 async def update(
691 self,
692 work_id: str,
693 *,
694 environment_id: str,
695 metadata: Dict[str, Optional[str]],
696 betas: List[AnthropicBetaParam] | Omit = omit,
697 workspace_id: str | Omit = omit,
698 # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
699 # The extra values given here take precedence over values defined on the client or passed to this method.
700 extra_headers: Headers | None = None,
701 extra_query: Query | None = None,
702 extra_body: Body | None = None,
703 timeout: float | httpx2.Timeout | None | NotGiven = not_given,
704 ) -> BetaSelfHostedWork:
705 """
706 Note: these endpoints are called automatically by the pre-built environment
707 worker provided in the SDKs and CLI, for orchestrating sessions with self-hosted
708 sandbox environments. They are included here as a reference; you do not need to
709 invoke them directly.
710
711 Update work item metadata with merge semantics.
712
713 Args:
714 metadata: Metadata patch. Set a key to a string to upsert it, or to null to delete it.
715 Omit the field to preserve existing metadata.
716
717 betas: Optional header to specify the beta version(s) you want to use.
718
719 workspace_id: Optional header to select the Workspace for this request. The value is a
720 Workspace ID (for example, `wrkspc_011CZkZaBF1tNoB5wlCeusgy`).
721
722 Only needed for credentials that can act on more than one Workspace. A
723 credential that belongs to a specific Workspace may omit it; if sent, it must
724 match that Workspace.
725
726 extra_headers: Send extra headers
727
728 extra_query: Add additional query parameters to the request
729
730 extra_body: Add additional JSON properties to the request
731
732 timeout: Override the client-level default timeout for this request, in seconds
733 """
734 if not environment_id:
735 raise ValueError(f"Expected a non-empty value for `environment_id` but received {environment_id!r}")
736 if not work_id:
737 raise ValueError(f"Expected a non-empty value for `work_id` but received {work_id!r}")
738 extra_headers = {
739 **strip_not_given(
740 {
741 "anthropic-beta": ",".join(chain((str(e) for e in betas), ["managed-agents-2026-04-01"]))
742 if is_given(betas)
743 else not_given,
744 "anthropic-workspace-id": workspace_id,
745 }
746 ),
747 **(extra_headers or {}),
748 }
749 extra_headers = {"anthropic-beta": "managed-agents-2026-04-01", **(extra_headers or {})}
750 return await self._post(
751 path_template(
752 "/v1/environments/{environment_id}/work/{work_id}?beta=true",
753 environment_id=environment_id,
754 work_id=work_id,
755 ),
756 body={"metadata": metadata},
757 options=make_request_options(
758 extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
759 ),
760 cast_to=BetaSelfHostedWork,
761 )
762
763 def list(
764 self,
765 environment_id: str,
766 *,
767 limit: int | Omit = omit,
768 page: Optional[str] | Omit = omit,
769 betas: List[AnthropicBetaParam] | Omit = omit,
770 # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
771 # The extra values given here take precedence over values defined on the client or passed to this method.
772 extra_headers: Headers | None = None,
773 extra_query: Query | None = None,
774 extra_body: Body | None = None,
775 timeout: float | httpx2.Timeout | None | NotGiven = not_given,
776 ) -> AsyncPaginator[BetaSelfHostedWork, AsyncPageCursor[BetaSelfHostedWork]]:
777 """
778 Note: these endpoints are called automatically by the pre-built environment
779 worker provided in the SDKs and CLI, for orchestrating sessions with self-hosted
780 sandbox environments. They are included here as a reference; you do not need to
781 invoke them directly.
782
783 List work items in an environment.
784
785 Args:
786 limit: Maximum number of work items to return
787
788 page: Opaque cursor from previous response for pagination
789
790 betas: Optional header to specify the beta version(s) you want to use.
791
792 extra_headers: Send extra headers
793
794 extra_query: Add additional query parameters to the request
795
796 extra_body: Add additional JSON properties to the request
797
798 timeout: Override the client-level default timeout for this request, in seconds
799 """
800 if not environment_id:
801 raise ValueError(f"Expected a non-empty value for `environment_id` but received {environment_id!r}")
802 extra_headers = {
803 **strip_not_given(
804 {
805 "anthropic-beta": ",".join(chain((str(e) for e in betas), ["managed-agents-2026-04-01"]))
806 if is_given(betas)
807 else not_given
808 }
809 ),
810 **(extra_headers or {}),
811 }
812 extra_headers = {"anthropic-beta": "managed-agents-2026-04-01", **(extra_headers or {})}
813 return self._get_api_list(
814 path_template("/v1/environments/{environment_id}/work?beta=true", environment_id=environment_id),
815 page=AsyncPageCursor[BetaSelfHostedWork],
816 options=make_request_options(
817 extra_headers=extra_headers,
818 extra_query=extra_query,
819 extra_body=extra_body,
820 timeout=timeout,
821 query={
822 "limit": limit,
823 "page": page,
824 },
825 ),
826 model=BetaSelfHostedWork,
827 )
828
829 async def ack(
830 self,
831 work_id: str,
832 *,
833 environment_id: str,
834 betas: List[AnthropicBetaParam] | Omit = omit,
835 # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
836 # The extra values given here take precedence over values defined on the client or passed to this method.
837 extra_headers: Headers | None = None,
838 extra_query: Query | None = None,
839 extra_body: Body | None = None,
840 timeout: float | httpx2.Timeout | None | NotGiven = not_given,
841 ) -> BetaSelfHostedWork:
842 """
843 Note: these endpoints are called automatically by the pre-built environment
844 worker provided in the SDKs and CLI, for orchestrating sessions with self-hosted
845 sandbox environments. They are included here as a reference; you do not need to
846 invoke them directly.
847
848 Acknowledge receipt of a work item, transitioning it from 'queued' to 'starting'
849 and removing it from the queue.
850
851 Args:
852 betas: Optional header to specify the beta version(s) you want to use.
853
854 extra_headers: Send extra headers
855
856 extra_query: Add additional query parameters to the request
857
858 extra_body: Add additional JSON properties to the request
859
860 timeout: Override the client-level default timeout for this request, in seconds
861 """
862 if not environment_id:
863 raise ValueError(f"Expected a non-empty value for `environment_id` but received {environment_id!r}")
864 if not work_id:
865 raise ValueError(f"Expected a non-empty value for `work_id` but received {work_id!r}")
866 extra_headers = {
867 **strip_not_given(
868 {
869 "anthropic-beta": ",".join(chain((str(e) for e in betas), ["managed-agents-2026-04-01"]))
870 if is_given(betas)
871 else not_given
872 }
873 ),
874 **(extra_headers or {}),
875 }
876 extra_headers = {"anthropic-beta": "managed-agents-2026-04-01", **(extra_headers or {})}
877 return await self._post(
878 path_template(
879 "/v1/environments/{environment_id}/work/{work_id}/ack?beta=true",
880 environment_id=environment_id,
881 work_id=work_id,
882 ),
883 options=make_request_options(
884 extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
885 ),
886 cast_to=BetaSelfHostedWork,
887 )
888
889 async def heartbeat(
890 self,
891 work_id: str,
892 *,
893 environment_id: str,
894 desired_ttl_seconds: Optional[int] | Omit = omit,
895 expected_last_heartbeat: Optional[str] | Omit = omit,
896 betas: List[AnthropicBetaParam] | Omit = omit,
897 # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
898 # The extra values given here take precedence over values defined on the client or passed to this method.
899 extra_headers: Headers | None = None,
900 extra_query: Query | None = None,
901 extra_body: Body | None = None,
902 timeout: float | httpx2.Timeout | None | NotGiven = not_given,
903 ) -> BetaSelfHostedWorkHeartbeatResponse:
904 """
905 Note: these endpoints are called automatically by the pre-built environment
906 worker provided in the SDKs and CLI, for orchestrating sessions with self-hosted
907 sandbox environments. They are included here as a reference; you do not need to
908 invoke them directly.
909
910 Record a heartbeat for a work item to maintain the lease.
911
912 Args:
913 desired_ttl_seconds: Desired TTL in seconds
914
915 expected_last_heartbeat: Expected last_heartbeat for conditional update (optimistic concurrency). Use
916 literal 'NO_HEARTBEAT' to claim an unclaimed lease (first heartbeat). For
917 subsequent heartbeats, echo the server's previous last_heartbeat value exactly.
918 Returns 412 Precondition Failed if the actual value doesn't match.
919
920 betas: Optional header to specify the beta version(s) you want to use.
921
922 extra_headers: Send extra headers
923
924 extra_query: Add additional query parameters to the request
925
926 extra_body: Add additional JSON properties to the request
927
928 timeout: Override the client-level default timeout for this request, in seconds
929 """
930 if not environment_id:
931 raise ValueError(f"Expected a non-empty value for `environment_id` but received {environment_id!r}")
932 if not work_id:
933 raise ValueError(f"Expected a non-empty value for `work_id` but received {work_id!r}")
934 extra_headers = {
935 **strip_not_given(
936 {
937 "anthropic-beta": ",".join(chain((str(e) for e in betas), ["managed-agents-2026-04-01"]))
938 if is_given(betas)
939 else not_given
940 }
941 ),
942 **(extra_headers or {}),
943 }
944 extra_headers = {"anthropic-beta": "managed-agents-2026-04-01", **(extra_headers or {})}
945 return await self._post(
946 path_template(
947 "/v1/environments/{environment_id}/work/{work_id}/heartbeat?beta=true",
948 environment_id=environment_id,
949 work_id=work_id,
950 ),
951 options=make_request_options(
952 extra_headers=extra_headers,
953 extra_query=extra_query,
954 extra_body=extra_body,
955 timeout=timeout,
956 query={
957 "desired_ttl_seconds": desired_ttl_seconds,
958 "expected_last_heartbeat": expected_last_heartbeat,
959 },
960 ),
961 cast_to=BetaSelfHostedWorkHeartbeatResponse,
962 )
963
964 async def poll(
965 self,
966 environment_id: str,
967 *,
968 block_ms: Optional[int] | Omit = omit,
969 reclaim_older_than_ms: Optional[int] | Omit = omit,
970 betas: List[AnthropicBetaParam] | Omit = omit,
971 anthropic_worker_id: str | Omit = omit,
972 # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
973 # The extra values given here take precedence over values defined on the client or passed to this method.
974 extra_headers: Headers | None = None,
975 extra_query: Query | None = None,
976 extra_body: Body | None = None,
977 timeout: float | httpx2.Timeout | None | NotGiven = not_given,
978 ) -> Optional[BetaSelfHostedWork]:
979 """
980 Note: these endpoints are called automatically by the pre-built environment
981 worker provided in the SDKs and CLI, for orchestrating sessions with self-hosted
982 sandbox environments. They are included here as a reference; you do not need to
983 invoke them directly.
984
985 Long poll for work items in the queue.
986
987 Args:
988 block_ms: How long to wait for work to arrive before returning. Must be 1-999 in
989 milliseconds. Defaults to non-blocking (returns immediately if no work is
990 available).
991
992 reclaim_older_than_ms: Reclaim unacknowledged work items older than this many milliseconds. If omitted,
993 uses the default (5000ms).
994
995 betas: Optional header to specify the beta version(s) you want to use.
996
997 anthropic_worker_id: Unique identifier for the specific worker polling, used to track aggregated
998 environment-level work metrics in Console
999
1000 extra_headers: Send extra headers
1001
1002 extra_query: Add additional query parameters to the request
1003
1004 extra_body: Add additional JSON properties to the request
1005
1006 timeout: Override the client-level default timeout for this request, in seconds
1007 """
1008 if not environment_id:
1009 raise ValueError(f"Expected a non-empty value for `environment_id` but received {environment_id!r}")
1010 extra_headers = {
1011 **strip_not_given(
1012 {
1013 "anthropic-beta": ",".join(chain((str(e) for e in betas), ["managed-agents-2026-04-01"]))
1014 if is_given(betas)
1015 else not_given,
1016 "Anthropic-Worker-ID": anthropic_worker_id,
1017 }
1018 ),
1019 **(extra_headers or {}),
1020 }
1021 extra_headers = {"anthropic-beta": "managed-agents-2026-04-01", **(extra_headers or {})}
1022 return await self._get(
1023 path_template("/v1/environments/{environment_id}/work/poll?beta=true", environment_id=environment_id),
1024 options=make_request_options(
1025 extra_headers=extra_headers,
1026 extra_query=extra_query,
1027 extra_body=extra_body,
1028 timeout=timeout,
1029 query={
1030 "block_ms": block_ms,
1031 "reclaim_older_than_ms": reclaim_older_than_ms,
1032 },
1033 ),
1034 cast_to=BetaSelfHostedWork,
1035 )
1036
1037 async def stats(
1038 self,
1039 environment_id: str,
1040 *,
1041 betas: List[AnthropicBetaParam] | Omit = omit,
1042 workspace_id: str | Omit = omit,
1043 # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
1044 # The extra values given here take precedence over values defined on the client or passed to this method.
1045 extra_headers: Headers | None = None,
1046 extra_query: Query | None = None,
1047 extra_body: Body | None = None,
1048 timeout: float | httpx2.Timeout | None | NotGiven = not_given,
1049 ) -> BetaSelfHostedWorkQueueStats:
1050 """
1051 Get statistics about the work queue for an environment.
1052
1053 Args:
1054 betas: Optional header to specify the beta version(s) you want to use.
1055
1056 workspace_id: Optional header to select the Workspace for this request. The value is a
1057 Workspace ID (for example, `wrkspc_011CZkZaBF1tNoB5wlCeusgy`).
1058
1059 Only needed for credentials that can act on more than one Workspace. A
1060 credential that belongs to a specific Workspace may omit it; if sent, it must
1061 match that Workspace.
1062
1063 extra_headers: Send extra headers
1064
1065 extra_query: Add additional query parameters to the request
1066
1067 extra_body: Add additional JSON properties to the request
1068
1069 timeout: Override the client-level default timeout for this request, in seconds
1070 """
1071 if not environment_id:
1072 raise ValueError(f"Expected a non-empty value for `environment_id` but received {environment_id!r}")
1073 extra_headers = {
1074 **strip_not_given(
1075 {
1076 "anthropic-beta": ",".join(chain((str(e) for e in betas), ["managed-agents-2026-04-01"]))
1077 if is_given(betas)
1078 else not_given,
1079 "anthropic-workspace-id": workspace_id,
1080 }
1081 ),
1082 **(extra_headers or {}),
1083 }
1084 extra_headers = {"anthropic-beta": "managed-agents-2026-04-01", **(extra_headers or {})}
1085 return await self._get(
1086 path_template("/v1/environments/{environment_id}/work/stats?beta=true", environment_id=environment_id),
1087 options=make_request_options(
1088 extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
1089 ),
1090 cast_to=BetaSelfHostedWorkQueueStats,
1091 )
1092
1093 async def stop(
1094 self,
1095 work_id: str,
1096 *,
1097 environment_id: str,
1098 force: bool | Omit = omit,
1099 betas: List[AnthropicBetaParam] | Omit = omit,
1100 workspace_id: str | Omit = omit,
1101 # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
1102 # The extra values given here take precedence over values defined on the client or passed to this method.
1103 extra_headers: Headers | None = None,
1104 extra_query: Query | None = None,
1105 extra_body: Body | None = None,
1106 timeout: float | httpx2.Timeout | None | NotGiven = not_given,
1107 ) -> BetaSelfHostedWork:
1108 """
1109 Note: these endpoints are called automatically by the pre-built environment
1110 worker provided in the SDKs and CLI, for orchestrating sessions with self-hosted
1111 sandbox environments. They are included here as a reference; you do not need to
1112 invoke them directly.
1113
1114 Stop a work item, initiating graceful or forced shutdown.
1115
1116 Args:
1117 force: If true, immediately stop work without graceful shutdown
1118
1119 betas: Optional header to specify the beta version(s) you want to use.
1120
1121 workspace_id: Optional header to select the Workspace for this request. The value is a
1122 Workspace ID (for example, `wrkspc_011CZkZaBF1tNoB5wlCeusgy`).
1123
1124 Only needed for credentials that can act on more than one Workspace. A
1125 credential that belongs to a specific Workspace may omit it; if sent, it must
1126 match that Workspace.
1127
1128 extra_headers: Send extra headers
1129
1130 extra_query: Add additional query parameters to the request
1131
1132 extra_body: Add additional JSON properties to the request
1133
1134 timeout: Override the client-level default timeout for this request, in seconds
1135 """
1136 if not environment_id:
1137 raise ValueError(f"Expected a non-empty value for `environment_id` but received {environment_id!r}")
1138 if not work_id:
1139 raise ValueError(f"Expected a non-empty value for `work_id` but received {work_id!r}")
1140 extra_headers = {
1141 **strip_not_given(
1142 {
1143 "anthropic-beta": ",".join(chain((str(e) for e in betas), ["managed-agents-2026-04-01"]))
1144 if is_given(betas)
1145 else not_given,
1146 "anthropic-workspace-id": workspace_id,
1147 }
1148 ),
1149 **(extra_headers or {}),
1150 }
1151 extra_headers = {"anthropic-beta": "managed-agents-2026-04-01", **(extra_headers or {})}
1152 return await self._post(
1153 path_template(
1154 "/v1/environments/{environment_id}/work/{work_id}/stop?beta=true",
1155 environment_id=environment_id,
1156 work_id=work_id,
1157 ),
1158 body={"force": force},
1159 options=make_request_options(
1160 extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
1161 ),
1162 cast_to=BetaSelfHostedWork,
1163 )
1164
1165 def poller(
1166 self,
1167 *,
1168 environment_id: str,
1169 environment_key: str,
1170 worker_id: str | None = None,
1171 block_ms: int | None | NotGiven = not_given,
1172 reclaim_older_than_ms: int | None = None,
1173 drain: bool = False,
1174 auto_stop: bool = True,
1175 extra_headers: Headers | None = None,
1176 ) -> AsyncIterator[BetaSelfHostedWork]:
1177 """Async-iterate work items claimed from a self-hosted environment.
1178
1179 Each yielded item has been ack'd. The environment key authenticates the
1180 poll, ack, and stop calls via a scoped sub-client (built once per
1181 call). Async only — available on `anthropic.AsyncAnthropic`
1182 (the sync client does not expose `poller`).
1183
1184 With the defaults this loops forever and calls `stop` after the
1185 consuming `async for` body returns or raises (long-running runner
1186 shape). Pass `drain=True, auto_stop=False` to drain whatever is queued
1187 and return without owning the stop call (webhook-dispatch shape — each
1188 item is handed off to another process that calls `stop` when done).
1189
1190 Args:
1191 environment_id: The self-hosted environment to claim work from.
1192 environment_key: The environment key — used as the Bearer credential
1193 on the scoped sub-client that issues poll / ack / stop requests.
1194 worker_id: Optional identifier sent on each poll. Defaults to a
1195 unique, hostname-prefixed id.
1196 block_ms: How long the server should hold an empty poll open before
1197 returning (long-poll). Server caps this at 999. Defaults to
1198 `POLL_BLOCK_MS` (999) when not given. Pass `None` to omit for a
1199 non-blocking poll — the server rejects `0`.
1200 reclaim_older_than_ms: Reclaim un-ack'd work older than this many ms.
1201 Forwarded to the underlying poll request.
1202 drain: When True, return after the first empty poll instead of
1203 sleeping and re-polling.
1204 auto_stop: When True (default), call `stop` after the consumer's
1205 loop body completes. Set False when handing items off to another
1206 process that owns the stop call.
1207 extra_headers: Optional headers passed through per request on the
1208 poll / ack / stop calls. They are threaded into each call's
1209 `extra_headers=` and never assigned onto the client, so client
1210 state is not mutated. Auth and `x-stainless-helper` are supplied
1211 by the scoped sub-client built here (and the parent client's
1212 `default_headers` propagate via its `client.copy()`); a header
1213 given here overrides the scoped client's same-named default for
1214 that request, so use it for caller passthrough (e.g. trace ids),
1215 not to set auth.
1216 """
1217 # POLL_BLOCK_MS is resolved here, not used as a literal signature
1218 # default: importing _poller at module load would form an import cycle
1219 # (_poller imports this module) and pull the host-only environment lib
1220 # into `import anthropic`. The sentinel keeps a single source of truth
1221 # for the default so it can't drift from the constant.
1222 from ....lib._scoped_client import _copy_client_with_bearer_auth
1223 from ....lib.environments._poller import POLL_BLOCK_MS, aiter_work
1224
1225 if not is_given(block_ms):
1226 block_ms = POLL_BLOCK_MS
1227
1228 scoped = _copy_client_with_bearer_auth(
1229 cast("AsyncAnthropic", self._client),
1230 auth_token=environment_key,
1231 helper="environments-work-poller",
1232 )
1233 return aiter_work(
1234 scoped.beta.environments.work,
1235 environment_id=environment_id,
1236 worker_id=worker_id,
1237 block_ms=block_ms,
1238 reclaim_older_than_ms=reclaim_older_than_ms,
1239 drain=drain,
1240 auto_stop=auto_stop,
1241 extra_headers=extra_headers,
1242 )
1243
1244 @overload
1245 def worker(
1246 self,
1247 *,
1248 environment_id: str | None = None,
1249 environment_key: str | None = None,
1250 tools: EnvironmentWorkerTools | None = None,
1251 workdir: str | os.PathLike[str] | None = None,
1252 max_file_bytes: int | None | NotGiven = not_given,
1253 max_idle: float | None | NotGiven = not_given,
1254 memory_sync_interval: float | None | NotGiven = not_given,
1255 memory_sync_deletions: MemoryDeleteMode = "enabled",
1256 worker_id: str | None = None,
1257 extra_headers: Headers | None = None,
1258 ) -> EnvironmentWorker: ...
1259
1260 @overload
1261 @deprecated(UNRESTRICTED_PATHS_DEPRECATION)
1262 def worker(
1263 self,
1264 *,
1265 environment_id: str | None = None,
1266 environment_key: str | None = None,
1267 tools: EnvironmentWorkerTools | None = None,
1268 workdir: str | os.PathLike[str] | None = None,
1269 unrestricted_paths: bool,
1270 max_file_bytes: int | None | NotGiven = not_given,
1271 max_idle: float | None | NotGiven = not_given,
1272 memory_sync_interval: float | None | NotGiven = not_given,
1273 memory_sync_deletions: MemoryDeleteMode = "enabled",
1274 worker_id: str | None = None,
1275 extra_headers: Headers | None = None,
1276 ) -> EnvironmentWorker: ...
1277
1278 def worker(
1279 self,
1280 *,
1281 environment_id: str | None = None,
1282 environment_key: str | None = None,
1283 tools: EnvironmentWorkerTools | None = None,
1284 workdir: str | os.PathLike[str] | None = None,
1285 unrestricted_paths: bool | NotGiven = not_given,
1286 max_file_bytes: int | None | NotGiven = not_given,
1287 max_idle: float | None | NotGiven = not_given,
1288 memory_sync_interval: float | None | NotGiven = not_given,
1289 memory_sync_deletions: MemoryDeleteMode = "enabled",
1290 worker_id: str | None = None,
1291 extra_headers: Headers | None = None,
1292 ) -> EnvironmentWorker:
1293 """Build an `anthropic.lib.environments.EnvironmentWorker` bound to this async client.
1294
1295 The full worker: it polls the environment for work, and for each claimed
1296 session sets up the workdir + downloads the session agent's skills, runs
1297 the given `tools` against the session's tool-call events while
1298 heartbeating the work-item lease, force-stops the work on exit, and
1299 loops. Composed from this resource's `poller` and the per-session
1300 session tool runner.
1301
1302 `EnvironmentWorker` is async only — its `run` / `handle_item`
1303 coroutines need an event loop. With this `anthropic.AsyncAnthropic`
1304 client the returned worker is ready to `await worker.run()` (long-running
1305 poll loop) or `await worker.handle_item()` (single already-claimed work
1306 item). It can also be constructed directly:
1307 `EnvironmentWorker(client, ...)`.
1308
1309 Args:
1310 environment_id: The self-hosted environment to poll for work. Required
1311 by `EnvironmentWorker.run`; not used by
1312 `EnvironmentWorker.handle_item`.
1313 environment_key: The environment key — the worker's single credential,
1314 used as Bearer auth on the control-plane and session-level calls.
1315 tools: Tools to expose to each claimed session. Either a fixed list or
1316 a factory invoked once per session with that session's
1317 `AgentToolContext`. Defaults to `beta_agent_toolset_20260401(env)`.
1318 Async tools share the event loop with the lease heartbeat, so keep
1319 them non-blocking.
1320 workdir: Base directory for the per-session `AgentToolContext`.
1321 Defaults to `os.getcwd()` captured when the worker is constructed
1322 (TS parity: `process.cwd()` at construction).
1323 unrestricted_paths: Deprecated and no longer accepted; passing either
1324 value raises `TypeError` (see `AgentToolContext`).
1325 max_file_bytes: Forwarded to the per-session `AgentToolContext` — the
1326 size cap (bytes) for the `read`/`edit` tools. `not_given`
1327 (default) uses the built-in 256 KiB cap; a positive int sets a custom
1328 cap; `None` disables the cap.
1329 max_idle: Seconds to keep running after the session goes idle with
1330 `stop_reason` `end_turn`. Defaults to `DEFAULT_MAX_IDLE` (60s)
1331 when not given. `None` disables it.
1332 memory_sync_interval: How often (seconds) to sync the session's
1333 attached memory stores; `None` disables memory. Defaults to
1334 `DEFAULT_MEMORY_SYNC_INTERVAL` (15s) when not given.
1335 memory_sync_deletions: `"enabled"` (default), `"log_only"`, or
1336 `"disabled"`.
1337 worker_id: Optional identifier sent on each poll. Defaults to a unique,
1338 hostname-prefixed id.
1339 extra_headers: Optional headers passed through per request on every
1340 call the worker makes (poll / ack / stop / heartbeat and the
1341 session tool runner's event stream / list / send). They are
1342 threaded into each call's `extra_headers=` and never assigned
1343 onto the client, so client state is not mutated. Auth and
1344 `x-stainless-helper` are supplied by the worker's scoped
1345 sub-clients (and the parent client's `default_headers` propagate
1346 via their `client.copy()`); a header given here overrides a
1347 scoped client's same-named default for that request, so use it for
1348 caller passthrough (e.g. trace ids), not to set auth.
1349 """
1350 # DEFAULT_MAX_IDLE resolved here rather than as a literal signature
1351 # default so the value can't drift from the constant; the lazy import
1352 # also keeps the host-only environment lib out of `import anthropic`.
1353 from ....lib.environments._worker import DEFAULT_MEMORY_SYNC_INTERVAL, EnvironmentWorker
1354 from ....lib.tools._beta_session_runner import DEFAULT_MAX_IDLE
1355
1356 reject_unrestricted_paths(unrestricted_paths)
1357 if not is_given(max_idle):
1358 max_idle = DEFAULT_MAX_IDLE
1359 if not is_given(memory_sync_interval):
1360 memory_sync_interval = DEFAULT_MEMORY_SYNC_INTERVAL
1361
1362 return EnvironmentWorker(
1363 cast("AsyncAnthropic", self._client),
1364 environment_id=environment_id,
1365 environment_key=environment_key,
1366 tools=tools,
1367 workdir=workdir,
1368 max_file_bytes=max_file_bytes,
1369 max_idle=max_idle,
1370 memory_sync_interval=memory_sync_interval,
1371 memory_sync_deletions=memory_sync_deletions,
1372 worker_id=worker_id,
1373 extra_headers=extra_headers,
1374 )
1375
1376
1377 class WorkWithRawResponse:
1378 def __init__(self, work: Work) -> None:
1379 self._work = work
1380
1381 self.retrieve = to_raw_response_wrapper(
1382 work.retrieve,
1383 )
1384 self.update = to_raw_response_wrapper(
1385 work.update,
1386 )
1387 self.list = to_raw_response_wrapper(
1388 work.list,
1389 )
1390 self.ack = to_raw_response_wrapper(
1391 work.ack,
1392 )
1393 self.heartbeat = to_raw_response_wrapper(
1394 work.heartbeat,
1395 )
1396 self.poll = to_raw_response_wrapper(
1397 work.poll,
1398 )
1399 self.stats = to_raw_response_wrapper(
1400 work.stats,
1401 )
1402 self.stop = to_raw_response_wrapper(
1403 work.stop,
1404 )
1405
1406
1407 class AsyncWorkWithRawResponse:
1408 def __init__(self, work: AsyncWork) -> None:
1409 self._work = work
1410
1411 self.retrieve = async_to_raw_response_wrapper(
1412 work.retrieve,
1413 )
1414 self.update = async_to_raw_response_wrapper(
1415 work.update,
1416 )
1417 self.list = async_to_raw_response_wrapper(
1418 work.list,
1419 )
1420 self.ack = async_to_raw_response_wrapper(
1421 work.ack,
1422 )
1423 self.heartbeat = async_to_raw_response_wrapper(
1424 work.heartbeat,
1425 )
1426 self.poll = async_to_raw_response_wrapper(
1427 work.poll,
1428 )
1429 self.stats = async_to_raw_response_wrapper(
1430 work.stats,
1431 )
1432 self.stop = async_to_raw_response_wrapper(
1433 work.stop,
1434 )
1435
1436
1437 class WorkWithStreamingResponse:
1438 def __init__(self, work: Work) -> None:
1439 self._work = work
1440
1441 self.retrieve = to_streamed_response_wrapper(
1442 work.retrieve,
1443 )
1444 self.update = to_streamed_response_wrapper(
1445 work.update,
1446 )
1447 self.list = to_streamed_response_wrapper(
1448 work.list,
1449 )
1450 self.ack = to_streamed_response_wrapper(
1451 work.ack,
1452 )
1453 self.heartbeat = to_streamed_response_wrapper(
1454 work.heartbeat,
1455 )
1456 self.poll = to_streamed_response_wrapper(
1457 work.poll,
1458 )
1459 self.stats = to_streamed_response_wrapper(
1460 work.stats,
1461 )
1462 self.stop = to_streamed_response_wrapper(
1463 work.stop,
1464 )
1465
1466
1467 class AsyncWorkWithStreamingResponse:
1468 def __init__(self, work: AsyncWork) -> None:
1469 self._work = work
1470
1471 self.retrieve = async_to_streamed_response_wrapper(
1472 work.retrieve,
1473 )
1474 self.update = async_to_streamed_response_wrapper(
1475 work.update,
1476 )
1477 self.list = async_to_streamed_response_wrapper(
1478 work.list,
1479 )
1480 self.ack = async_to_streamed_response_wrapper(
1481 work.ack,
1482 )
1483 self.heartbeat = async_to_streamed_response_wrapper(
1484 work.heartbeat,
1485 )
1486 self.poll = async_to_streamed_response_wrapper(
1487 work.poll,
1488 )
1489 self.stats = async_to_streamed_response_wrapper(
1490 work.stats,
1491 )
1492 self.stop = async_to_streamed_response_wrapper(
1493 work.stop,
1494 )