Debian Codegraph @

src/anthropic/resources/beta/sessions/sessions.py

raw
1 from __future__ import annotations
2
3 from typing import Dict, List, Union, Iterable, Optional
4 from datetime import datetime
5 from itertools import chain
6 from typing_extensions import Literal
7
8 import httpx2
9
10 from .events import (
11 Events,
12 AsyncEvents,
13 EventsWithRawResponse,
14 AsyncEventsWithRawResponse,
15 EventsWithStreamingResponse,
16 AsyncEventsWithStreamingResponse,
17 )
18 from ...._types import Body, Omit, Query, Headers, NotGiven, SequenceNotStr, omit, not_given
19 from ...._utils import is_given, path_template, strip_not_given
20 from .resources import (
21 Resources,
22 AsyncResources,
23 ResourcesWithRawResponse,
24 AsyncResourcesWithRawResponse,
25 ResourcesWithStreamingResponse,
26 AsyncResourcesWithStreamingResponse,
27 )
28 from ...._compat import cached_property
29 from ...._resource import SyncAPIResource, AsyncAPIResource
30 from ...._response import (
31 to_raw_response_wrapper,
32 to_streamed_response_wrapper,
33 async_to_raw_response_wrapper,
34 async_to_streamed_response_wrapper,
35 )
36 from ....pagination import SyncBidirectionalPageCursor, AsyncBidirectionalPageCursor
37 from ....types.beta import (
38 session_create_params,
39 )
40 from ...._base_client import AsyncPaginator, make_request_options
41 from .threads.threads import (
42 Threads,
43 AsyncThreads,
44 ThreadsWithRawResponse,
45 AsyncThreadsWithRawResponse,
46 ThreadsWithStreamingResponse,
47 AsyncThreadsWithStreamingResponse,
48 )
49 from ....types.anthropic_beta_param import AnthropicBetaParam
50 from ....types.beta.beta_managed_agents_session import BetaManagedAgentsSession
51 from ....types.beta.beta_managed_agents_deleted_session import BetaManagedAgentsDeletedSession
52 from ....types.beta.beta_managed_agents_budget_limit_param import BetaManagedAgentsBudgetLimitParam
53 from ....types.beta.beta_managed_agents_session_agent_update_param import BetaManagedAgentsSessionAgentUpdateParam
54
55 __all__ = ["Sessions", "AsyncSessions"]
56
57
58 class Sessions(SyncAPIResource):
59 @cached_property
60 def events(self) -> Events:
61 return Events(self._client)
62
63 @cached_property
64 def resources(self) -> Resources:
65 return Resources(self._client)
66
67 @cached_property
68 def threads(self) -> Threads:
69 return Threads(self._client)
70
71 @cached_property
72 def with_raw_response(self) -> SessionsWithRawResponse:
73 """
74 This property can be used as a prefix for any HTTP method call to return
75 the raw response object instead of the parsed content.
76
77 For more information, see https://www.github.com/anthropics/anthropic-sdk-python#accessing-raw-response-data-eg-headers
78 """
79 return SessionsWithRawResponse(self)
80
81 @cached_property
82 def with_streaming_response(self) -> SessionsWithStreamingResponse:
83 """
84 An alternative to `.with_raw_response` that doesn't eagerly read the response body.
85
86 For more information, see https://www.github.com/anthropics/anthropic-sdk-python#with_streaming_response
87 """
88 return SessionsWithStreamingResponse(self)
89
90 def create(
91 self,
92 *,
93 agent: session_create_params.Agent,
94 environment_id: str,
95 budget: BetaManagedAgentsBudgetLimitParam | Omit = omit,
96 initial_events: Iterable[session_create_params.InitialEvent] | Omit = omit,
97 metadata: Dict[str, str] | Omit = omit,
98 resources: Iterable[session_create_params.Resource] | Omit = omit,
99 title: Optional[str] | Omit = omit,
100 vault_ids: SequenceNotStr[str] | Omit = omit,
101 betas: List[AnthropicBetaParam] | Omit = omit,
102 workspace_id: str | Omit = omit,
103 # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
104 # The extra values given here take precedence over values defined on the client or passed to this method.
105 extra_headers: Headers | None = None,
106 extra_query: Query | None = None,
107 extra_body: Body | None = None,
108 timeout: float | httpx2.Timeout | None | NotGiven = not_given,
109 ) -> BetaManagedAgentsSession:
110 """Create Session
111
112 Args:
113 agent: Agent identifier.
114
115 Accepts the `agent` ID string, which pins the latest version
116 for the session, or an `agent` object with both id and version specified.
117
118 environment_id: ID of the `environment` defining the container configuration for this session.
119
120 budget: Enforced spend ceiling for the session. Omit to create an uncapped session.
121 Every model the session can run — the agent's model and each callable agent's
122 model — must have a public list price, or the request is rejected with reason
123 `model_not_budgetable`.
124
125 initial_events: Initial events to send to the `session` at creation, processed in order.
126 Supports `user.message` and `user.define_outcome` events. Maximum 50 events.
127
128 metadata: Arbitrary key-value metadata attached to the session. Maximum 16 pairs, keys up
129 to 64 chars, values up to 512 chars.
130
131 resources: Resources (e.g. repositories, files) to mount into the session's container.
132
133 title: Human-readable session title.
134
135 vault_ids: Vault IDs for stored credentials the agent can use during the session.
136
137 betas: Optional header to specify the beta version(s) you want to use.
138
139 workspace_id: Optional header to select the Workspace for this request. The value is a
140 Workspace ID (for example, `wrkspc_011CZkZaBF1tNoB5wlCeusgy`).
141
142 Only needed for credentials that can act on more than one Workspace. A
143 credential that belongs to a specific Workspace may omit it; if sent, it must
144 match that Workspace.
145
146 extra_headers: Send extra headers
147
148 extra_query: Add additional query parameters to the request
149
150 extra_body: Add additional JSON properties to the request
151
152 timeout: Override the client-level default timeout for this request, in seconds
153 """
154 extra_headers = {
155 **strip_not_given(
156 {
157 "anthropic-beta": ",".join(chain((str(e) for e in betas), ["managed-agents-2026-04-01"]))
158 if is_given(betas)
159 else not_given,
160 "anthropic-workspace-id": workspace_id,
161 }
162 ),
163 **(extra_headers or {}),
164 }
165 extra_headers = {"anthropic-beta": "managed-agents-2026-04-01", **(extra_headers or {})}
166 return self._post(
167 "/v1/sessions?beta=true",
168 body={
169 "agent": agent,
170 "environment_id": environment_id,
171 "budget": budget,
172 "initial_events": initial_events,
173 "metadata": metadata,
174 "resources": resources,
175 "title": title,
176 "vault_ids": vault_ids,
177 },
178 options=make_request_options(
179 extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
180 ),
181 cast_to=BetaManagedAgentsSession,
182 )
183
184 def retrieve(
185 self,
186 session_id: str,
187 *,
188 betas: List[AnthropicBetaParam] | Omit = omit,
189 workspace_id: str | Omit = omit,
190 # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
191 # The extra values given here take precedence over values defined on the client or passed to this method.
192 extra_headers: Headers | None = None,
193 extra_query: Query | None = None,
194 extra_body: Body | None = None,
195 timeout: float | httpx2.Timeout | None | NotGiven = not_given,
196 ) -> BetaManagedAgentsSession:
197 """
198 Get Session
199
200 Args:
201 betas: Optional header to specify the beta version(s) you want to use.
202
203 workspace_id: Optional header to select the Workspace for this request. The value is a
204 Workspace ID (for example, `wrkspc_011CZkZaBF1tNoB5wlCeusgy`).
205
206 Only needed for credentials that can act on more than one Workspace. A
207 credential that belongs to a specific Workspace may omit it; if sent, it must
208 match that Workspace.
209
210 extra_headers: Send extra headers
211
212 extra_query: Add additional query parameters to the request
213
214 extra_body: Add additional JSON properties to the request
215
216 timeout: Override the client-level default timeout for this request, in seconds
217 """
218 if not session_id:
219 raise ValueError(f"Expected a non-empty value for `session_id` but received {session_id!r}")
220 extra_headers = {
221 **strip_not_given(
222 {
223 "anthropic-beta": ",".join(chain((str(e) for e in betas), ["managed-agents-2026-04-01"]))
224 if is_given(betas)
225 else not_given,
226 "anthropic-workspace-id": workspace_id,
227 }
228 ),
229 **(extra_headers or {}),
230 }
231 extra_headers = {"anthropic-beta": "managed-agents-2026-04-01", **(extra_headers or {})}
232 return self._get(
233 path_template("/v1/sessions/{session_id}?beta=true", session_id=session_id),
234 options=make_request_options(
235 extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
236 ),
237 cast_to=BetaManagedAgentsSession,
238 )
239
240 def update(
241 self,
242 session_id: str,
243 *,
244 agent: BetaManagedAgentsSessionAgentUpdateParam | Omit = omit,
245 budget: Optional[BetaManagedAgentsBudgetLimitParam] | Omit = omit,
246 metadata: Optional[Dict[str, Optional[str]]] | Omit = omit,
247 title: Optional[str] | Omit = omit,
248 vault_ids: SequenceNotStr[str] | Omit = omit,
249 betas: List[AnthropicBetaParam] | Omit = omit,
250 workspace_id: str | Omit = omit,
251 # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
252 # The extra values given here take precedence over values defined on the client or passed to this method.
253 extra_headers: Headers | None = None,
254 extra_query: Query | None = None,
255 extra_body: Body | None = None,
256 timeout: float | httpx2.Timeout | None | NotGiven = not_given,
257 ) -> BetaManagedAgentsSession:
258 """Update Session
259
260 Args:
261 agent: Agent configuration update.
262
263 Only `tools` and `mcp_servers` are updatable
264 mid-session. Only valid for sessions created from an agent or deployment
265 reference. The session must not be running.
266
267 budget: Enforced spend ceiling for the session. Set an object to replace the budget of a
268 session that was created with one, or `null` to remove it; omit to preserve. A
269 budget cannot be added to a session created without one (rejected with reason
270 `budget_create_only`), and a removed budget cannot be re-added. Allowed in any
271 non-terminated status. Lowering `max_list_cost` to at or below the session's
272 consumed list cost is rejected with reason `budget_not_raised`, and every model
273 the session can run must have a public list price or the request is rejected
274 with reason `model_not_budgetable`.
275
276 metadata: Metadata patch. Set a key to a string to upsert it, or to null to delete it.
277 Omit the field to preserve.
278
279 title: Human-readable session title.
280
281 vault_ids: Vault IDs (`vlt_*`) to attach to the session. Not yet supported; requests
282 setting this field are rejected. Reserved for future use.
283
284 betas: Optional header to specify the beta version(s) you want to use.
285
286 workspace_id: Optional header to select the Workspace for this request. The value is a
287 Workspace ID (for example, `wrkspc_011CZkZaBF1tNoB5wlCeusgy`).
288
289 Only needed for credentials that can act on more than one Workspace. A
290 credential that belongs to a specific Workspace may omit it; if sent, it must
291 match that Workspace.
292
293 extra_headers: Send extra headers
294
295 extra_query: Add additional query parameters to the request
296
297 extra_body: Add additional JSON properties to the request
298
299 timeout: Override the client-level default timeout for this request, in seconds
300 """
301 if not session_id:
302 raise ValueError(f"Expected a non-empty value for `session_id` but received {session_id!r}")
303 extra_headers = {
304 **strip_not_given(
305 {
306 "anthropic-beta": ",".join(chain((str(e) for e in betas), ["managed-agents-2026-04-01"]))
307 if is_given(betas)
308 else not_given,
309 "anthropic-workspace-id": workspace_id,
310 }
311 ),
312 **(extra_headers or {}),
313 }
314 extra_headers = {"anthropic-beta": "managed-agents-2026-04-01", **(extra_headers or {})}
315 return self._post(
316 path_template("/v1/sessions/{session_id}?beta=true", session_id=session_id),
317 body={
318 "agent": agent,
319 "budget": budget,
320 "metadata": metadata,
321 "title": title,
322 "vault_ids": vault_ids,
323 },
324 options=make_request_options(
325 extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
326 ),
327 cast_to=BetaManagedAgentsSession,
328 )
329
330 def list(
331 self,
332 *,
333 agent_id: str | Omit = omit,
334 agent_version: int | Omit = omit,
335 created_at_gt: Union[str, datetime] | Omit = omit,
336 created_at_gte: Union[str, datetime] | Omit = omit,
337 created_at_lt: Union[str, datetime] | Omit = omit,
338 created_at_lte: Union[str, datetime] | Omit = omit,
339 deployment_id: str | Omit = omit,
340 include_archived: bool | Omit = omit,
341 limit: int | Omit = omit,
342 memory_store_id: str | Omit = omit,
343 order: Literal["asc", "desc"] | Omit = omit,
344 page: str | Omit = omit,
345 statuses: List[Literal["rescheduling", "running", "idle", "terminated"]] | Omit = omit,
346 betas: List[AnthropicBetaParam] | Omit = omit,
347 workspace_id: str | Omit = omit,
348 # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
349 # The extra values given here take precedence over values defined on the client or passed to this method.
350 extra_headers: Headers | None = None,
351 extra_query: Query | None = None,
352 extra_body: Body | None = None,
353 timeout: float | httpx2.Timeout | None | NotGiven = not_given,
354 ) -> SyncBidirectionalPageCursor[BetaManagedAgentsSession]:
355 """
356 List Sessions
357
358 Args:
359 agent_id: Filter sessions created with this agent ID.
360
361 agent_version: Filter by agent version. Only applies when `agent_id` is also set.
362
363 created_at_gt: Return sessions created after this time (exclusive).
364
365 created_at_gte: Return sessions created at or after this time (inclusive).
366
367 created_at_lt: Return sessions created before this time (exclusive).
368
369 created_at_lte: Return sessions created at or before this time (inclusive).
370
371 deployment_id: Filter sessions created by this deployment ID.
372
373 include_archived: When true, includes archived sessions. Default: false (exclude archived).
374
375 limit: Maximum number of results to return.
376
377 memory_store_id: Filter sessions whose resources contain a `memory_store` with this memory store
378 ID.
379
380 order: Sort direction for results, ordered by `created_at`. Defaults to `desc` (newest
381 first).
382
383 page: Opaque pagination cursor from a previous response.
384
385 statuses: Filter by session status. Repeat the parameter to match any of multiple
386 statuses.
387
388 betas: Optional header to specify the beta version(s) you want to use.
389
390 workspace_id: Optional header to select the Workspace for this request. The value is a
391 Workspace ID (for example, `wrkspc_011CZkZaBF1tNoB5wlCeusgy`).
392
393 Only needed for credentials that can act on more than one Workspace. A
394 credential that belongs to a specific Workspace may omit it; if sent, it must
395 match that Workspace.
396
397 extra_headers: Send extra headers
398
399 extra_query: Add additional query parameters to the request
400
401 extra_body: Add additional JSON properties to the request
402
403 timeout: Override the client-level default timeout for this request, in seconds
404 """
405 extra_headers = {
406 **strip_not_given(
407 {
408 "anthropic-beta": ",".join(chain((str(e) for e in betas), ["managed-agents-2026-04-01"]))
409 if is_given(betas)
410 else not_given,
411 "anthropic-workspace-id": workspace_id,
412 }
413 ),
414 **(extra_headers or {}),
415 }
416 extra_headers = {"anthropic-beta": "managed-agents-2026-04-01", **(extra_headers or {})}
417 return self._get_api_list(
418 "/v1/sessions?beta=true",
419 page=SyncBidirectionalPageCursor[BetaManagedAgentsSession],
420 options=make_request_options(
421 extra_headers=extra_headers,
422 extra_query=extra_query,
423 extra_body=extra_body,
424 timeout=timeout,
425 query={
426 "agent_id": agent_id,
427 "agent_version": agent_version,
428 "created_at[gt]": created_at_gt,
429 "created_at[gte]": created_at_gte,
430 "created_at[lt]": created_at_lt,
431 "created_at[lte]": created_at_lte,
432 "deployment_id": deployment_id,
433 "include_archived": include_archived,
434 "limit": limit,
435 "memory_store_id": memory_store_id,
436 "order": order,
437 "page": page,
438 "statuses": statuses,
439 },
440 ),
441 model=BetaManagedAgentsSession,
442 )
443
444 def delete(
445 self,
446 session_id: str,
447 *,
448 betas: List[AnthropicBetaParam] | Omit = omit,
449 workspace_id: str | Omit = omit,
450 # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
451 # The extra values given here take precedence over values defined on the client or passed to this method.
452 extra_headers: Headers | None = None,
453 extra_query: Query | None = None,
454 extra_body: Body | None = None,
455 timeout: float | httpx2.Timeout | None | NotGiven = not_given,
456 ) -> BetaManagedAgentsDeletedSession:
457 """
458 Delete Session
459
460 Args:
461 betas: Optional header to specify the beta version(s) you want to use.
462
463 workspace_id: Optional header to select the Workspace for this request. The value is a
464 Workspace ID (for example, `wrkspc_011CZkZaBF1tNoB5wlCeusgy`).
465
466 Only needed for credentials that can act on more than one Workspace. A
467 credential that belongs to a specific Workspace may omit it; if sent, it must
468 match that Workspace.
469
470 extra_headers: Send extra headers
471
472 extra_query: Add additional query parameters to the request
473
474 extra_body: Add additional JSON properties to the request
475
476 timeout: Override the client-level default timeout for this request, in seconds
477 """
478 if not session_id:
479 raise ValueError(f"Expected a non-empty value for `session_id` but received {session_id!r}")
480 extra_headers = {
481 **strip_not_given(
482 {
483 "anthropic-beta": ",".join(chain((str(e) for e in betas), ["managed-agents-2026-04-01"]))
484 if is_given(betas)
485 else not_given,
486 "anthropic-workspace-id": workspace_id,
487 }
488 ),
489 **(extra_headers or {}),
490 }
491 extra_headers = {"anthropic-beta": "managed-agents-2026-04-01", **(extra_headers or {})}
492 return self._delete(
493 path_template("/v1/sessions/{session_id}?beta=true", session_id=session_id),
494 options=make_request_options(
495 extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
496 ),
497 cast_to=BetaManagedAgentsDeletedSession,
498 )
499
500 def archive(
501 self,
502 session_id: str,
503 *,
504 betas: List[AnthropicBetaParam] | Omit = omit,
505 workspace_id: str | Omit = omit,
506 # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
507 # The extra values given here take precedence over values defined on the client or passed to this method.
508 extra_headers: Headers | None = None,
509 extra_query: Query | None = None,
510 extra_body: Body | None = None,
511 timeout: float | httpx2.Timeout | None | NotGiven = not_given,
512 ) -> BetaManagedAgentsSession:
513 """
514 Archive Session
515
516 Args:
517 betas: Optional header to specify the beta version(s) you want to use.
518
519 workspace_id: Optional header to select the Workspace for this request. The value is a
520 Workspace ID (for example, `wrkspc_011CZkZaBF1tNoB5wlCeusgy`).
521
522 Only needed for credentials that can act on more than one Workspace. A
523 credential that belongs to a specific Workspace may omit it; if sent, it must
524 match that Workspace.
525
526 extra_headers: Send extra headers
527
528 extra_query: Add additional query parameters to the request
529
530 extra_body: Add additional JSON properties to the request
531
532 timeout: Override the client-level default timeout for this request, in seconds
533 """
534 if not session_id:
535 raise ValueError(f"Expected a non-empty value for `session_id` but received {session_id!r}")
536 extra_headers = {
537 **strip_not_given(
538 {
539 "anthropic-beta": ",".join(chain((str(e) for e in betas), ["managed-agents-2026-04-01"]))
540 if is_given(betas)
541 else not_given,
542 "anthropic-workspace-id": workspace_id,
543 }
544 ),
545 **(extra_headers or {}),
546 }
547 extra_headers = {"anthropic-beta": "managed-agents-2026-04-01", **(extra_headers or {})}
548 return self._post(
549 path_template("/v1/sessions/{session_id}/archive?beta=true", session_id=session_id),
550 options=make_request_options(
551 extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
552 ),
553 cast_to=BetaManagedAgentsSession,
554 )
555
556
557 class AsyncSessions(AsyncAPIResource):
558 @cached_property
559 def events(self) -> AsyncEvents:
560 return AsyncEvents(self._client)
561
562 @cached_property
563 def resources(self) -> AsyncResources:
564 return AsyncResources(self._client)
565
566 @cached_property
567 def threads(self) -> AsyncThreads:
568 return AsyncThreads(self._client)
569
570 @cached_property
571 def with_raw_response(self) -> AsyncSessionsWithRawResponse:
572 """
573 This property can be used as a prefix for any HTTP method call to return
574 the raw response object instead of the parsed content.
575
576 For more information, see https://www.github.com/anthropics/anthropic-sdk-python#accessing-raw-response-data-eg-headers
577 """
578 return AsyncSessionsWithRawResponse(self)
579
580 @cached_property
581 def with_streaming_response(self) -> AsyncSessionsWithStreamingResponse:
582 """
583 An alternative to `.with_raw_response` that doesn't eagerly read the response body.
584
585 For more information, see https://www.github.com/anthropics/anthropic-sdk-python#with_streaming_response
586 """
587 return AsyncSessionsWithStreamingResponse(self)
588
589 async def create(
590 self,
591 *,
592 agent: session_create_params.Agent,
593 environment_id: str,
594 budget: BetaManagedAgentsBudgetLimitParam | Omit = omit,
595 initial_events: Iterable[session_create_params.InitialEvent] | Omit = omit,
596 metadata: Dict[str, str] | Omit = omit,
597 resources: Iterable[session_create_params.Resource] | Omit = omit,
598 title: Optional[str] | Omit = omit,
599 vault_ids: SequenceNotStr[str] | Omit = omit,
600 betas: List[AnthropicBetaParam] | Omit = omit,
601 workspace_id: str | Omit = omit,
602 # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
603 # The extra values given here take precedence over values defined on the client or passed to this method.
604 extra_headers: Headers | None = None,
605 extra_query: Query | None = None,
606 extra_body: Body | None = None,
607 timeout: float | httpx2.Timeout | None | NotGiven = not_given,
608 ) -> BetaManagedAgentsSession:
609 """Create Session
610
611 Args:
612 agent: Agent identifier.
613
614 Accepts the `agent` ID string, which pins the latest version
615 for the session, or an `agent` object with both id and version specified.
616
617 environment_id: ID of the `environment` defining the container configuration for this session.
618
619 budget: Enforced spend ceiling for the session. Omit to create an uncapped session.
620 Every model the session can run — the agent's model and each callable agent's
621 model — must have a public list price, or the request is rejected with reason
622 `model_not_budgetable`.
623
624 initial_events: Initial events to send to the `session` at creation, processed in order.
625 Supports `user.message` and `user.define_outcome` events. Maximum 50 events.
626
627 metadata: Arbitrary key-value metadata attached to the session. Maximum 16 pairs, keys up
628 to 64 chars, values up to 512 chars.
629
630 resources: Resources (e.g. repositories, files) to mount into the session's container.
631
632 title: Human-readable session title.
633
634 vault_ids: Vault IDs for stored credentials the agent can use during the session.
635
636 betas: Optional header to specify the beta version(s) you want to use.
637
638 workspace_id: Optional header to select the Workspace for this request. The value is a
639 Workspace ID (for example, `wrkspc_011CZkZaBF1tNoB5wlCeusgy`).
640
641 Only needed for credentials that can act on more than one Workspace. A
642 credential that belongs to a specific Workspace may omit it; if sent, it must
643 match that Workspace.
644
645 extra_headers: Send extra headers
646
647 extra_query: Add additional query parameters to the request
648
649 extra_body: Add additional JSON properties to the request
650
651 timeout: Override the client-level default timeout for this request, in seconds
652 """
653 extra_headers = {
654 **strip_not_given(
655 {
656 "anthropic-beta": ",".join(chain((str(e) for e in betas), ["managed-agents-2026-04-01"]))
657 if is_given(betas)
658 else not_given,
659 "anthropic-workspace-id": workspace_id,
660 }
661 ),
662 **(extra_headers or {}),
663 }
664 extra_headers = {"anthropic-beta": "managed-agents-2026-04-01", **(extra_headers or {})}
665 return await self._post(
666 "/v1/sessions?beta=true",
667 body={
668 "agent": agent,
669 "environment_id": environment_id,
670 "budget": budget,
671 "initial_events": initial_events,
672 "metadata": metadata,
673 "resources": resources,
674 "title": title,
675 "vault_ids": vault_ids,
676 },
677 options=make_request_options(
678 extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
679 ),
680 cast_to=BetaManagedAgentsSession,
681 )
682
683 async def retrieve(
684 self,
685 session_id: str,
686 *,
687 betas: List[AnthropicBetaParam] | Omit = omit,
688 workspace_id: str | Omit = omit,
689 # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
690 # The extra values given here take precedence over values defined on the client or passed to this method.
691 extra_headers: Headers | None = None,
692 extra_query: Query | None = None,
693 extra_body: Body | None = None,
694 timeout: float | httpx2.Timeout | None | NotGiven = not_given,
695 ) -> BetaManagedAgentsSession:
696 """
697 Get Session
698
699 Args:
700 betas: Optional header to specify the beta version(s) you want to use.
701
702 workspace_id: Optional header to select the Workspace for this request. The value is a
703 Workspace ID (for example, `wrkspc_011CZkZaBF1tNoB5wlCeusgy`).
704
705 Only needed for credentials that can act on more than one Workspace. A
706 credential that belongs to a specific Workspace may omit it; if sent, it must
707 match that Workspace.
708
709 extra_headers: Send extra headers
710
711 extra_query: Add additional query parameters to the request
712
713 extra_body: Add additional JSON properties to the request
714
715 timeout: Override the client-level default timeout for this request, in seconds
716 """
717 if not session_id:
718 raise ValueError(f"Expected a non-empty value for `session_id` but received {session_id!r}")
719 extra_headers = {
720 **strip_not_given(
721 {
722 "anthropic-beta": ",".join(chain((str(e) for e in betas), ["managed-agents-2026-04-01"]))
723 if is_given(betas)
724 else not_given,
725 "anthropic-workspace-id": workspace_id,
726 }
727 ),
728 **(extra_headers or {}),
729 }
730 extra_headers = {"anthropic-beta": "managed-agents-2026-04-01", **(extra_headers or {})}
731 return await self._get(
732 path_template("/v1/sessions/{session_id}?beta=true", session_id=session_id),
733 options=make_request_options(
734 extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
735 ),
736 cast_to=BetaManagedAgentsSession,
737 )
738
739 async def update(
740 self,
741 session_id: str,
742 *,
743 agent: BetaManagedAgentsSessionAgentUpdateParam | Omit = omit,
744 budget: Optional[BetaManagedAgentsBudgetLimitParam] | Omit = omit,
745 metadata: Optional[Dict[str, Optional[str]]] | Omit = omit,
746 title: Optional[str] | Omit = omit,
747 vault_ids: SequenceNotStr[str] | Omit = omit,
748 betas: List[AnthropicBetaParam] | Omit = omit,
749 workspace_id: str | Omit = omit,
750 # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
751 # The extra values given here take precedence over values defined on the client or passed to this method.
752 extra_headers: Headers | None = None,
753 extra_query: Query | None = None,
754 extra_body: Body | None = None,
755 timeout: float | httpx2.Timeout | None | NotGiven = not_given,
756 ) -> BetaManagedAgentsSession:
757 """Update Session
758
759 Args:
760 agent: Agent configuration update.
761
762 Only `tools` and `mcp_servers` are updatable
763 mid-session. Only valid for sessions created from an agent or deployment
764 reference. The session must not be running.
765
766 budget: Enforced spend ceiling for the session. Set an object to replace the budget of a
767 session that was created with one, or `null` to remove it; omit to preserve. A
768 budget cannot be added to a session created without one (rejected with reason
769 `budget_create_only`), and a removed budget cannot be re-added. Allowed in any
770 non-terminated status. Lowering `max_list_cost` to at or below the session's
771 consumed list cost is rejected with reason `budget_not_raised`, and every model
772 the session can run must have a public list price or the request is rejected
773 with reason `model_not_budgetable`.
774
775 metadata: Metadata patch. Set a key to a string to upsert it, or to null to delete it.
776 Omit the field to preserve.
777
778 title: Human-readable session title.
779
780 vault_ids: Vault IDs (`vlt_*`) to attach to the session. Not yet supported; requests
781 setting this field are rejected. Reserved for future use.
782
783 betas: Optional header to specify the beta version(s) you want to use.
784
785 workspace_id: Optional header to select the Workspace for this request. The value is a
786 Workspace ID (for example, `wrkspc_011CZkZaBF1tNoB5wlCeusgy`).
787
788 Only needed for credentials that can act on more than one Workspace. A
789 credential that belongs to a specific Workspace may omit it; if sent, it must
790 match that Workspace.
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 session_id:
801 raise ValueError(f"Expected a non-empty value for `session_id` but received {session_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 "anthropic-workspace-id": workspace_id,
809 }
810 ),
811 **(extra_headers or {}),
812 }
813 extra_headers = {"anthropic-beta": "managed-agents-2026-04-01", **(extra_headers or {})}
814 return await self._post(
815 path_template("/v1/sessions/{session_id}?beta=true", session_id=session_id),
816 body={
817 "agent": agent,
818 "budget": budget,
819 "metadata": metadata,
820 "title": title,
821 "vault_ids": vault_ids,
822 },
823 options=make_request_options(
824 extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
825 ),
826 cast_to=BetaManagedAgentsSession,
827 )
828
829 def list(
830 self,
831 *,
832 agent_id: str | Omit = omit,
833 agent_version: int | Omit = omit,
834 created_at_gt: Union[str, datetime] | Omit = omit,
835 created_at_gte: Union[str, datetime] | Omit = omit,
836 created_at_lt: Union[str, datetime] | Omit = omit,
837 created_at_lte: Union[str, datetime] | Omit = omit,
838 deployment_id: str | Omit = omit,
839 include_archived: bool | Omit = omit,
840 limit: int | Omit = omit,
841 memory_store_id: str | Omit = omit,
842 order: Literal["asc", "desc"] | Omit = omit,
843 page: str | Omit = omit,
844 statuses: List[Literal["rescheduling", "running", "idle", "terminated"]] | Omit = omit,
845 betas: List[AnthropicBetaParam] | Omit = omit,
846 workspace_id: str | Omit = omit,
847 # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
848 # The extra values given here take precedence over values defined on the client or passed to this method.
849 extra_headers: Headers | None = None,
850 extra_query: Query | None = None,
851 extra_body: Body | None = None,
852 timeout: float | httpx2.Timeout | None | NotGiven = not_given,
853 ) -> AsyncPaginator[BetaManagedAgentsSession, AsyncBidirectionalPageCursor[BetaManagedAgentsSession]]:
854 """
855 List Sessions
856
857 Args:
858 agent_id: Filter sessions created with this agent ID.
859
860 agent_version: Filter by agent version. Only applies when `agent_id` is also set.
861
862 created_at_gt: Return sessions created after this time (exclusive).
863
864 created_at_gte: Return sessions created at or after this time (inclusive).
865
866 created_at_lt: Return sessions created before this time (exclusive).
867
868 created_at_lte: Return sessions created at or before this time (inclusive).
869
870 deployment_id: Filter sessions created by this deployment ID.
871
872 include_archived: When true, includes archived sessions. Default: false (exclude archived).
873
874 limit: Maximum number of results to return.
875
876 memory_store_id: Filter sessions whose resources contain a `memory_store` with this memory store
877 ID.
878
879 order: Sort direction for results, ordered by `created_at`. Defaults to `desc` (newest
880 first).
881
882 page: Opaque pagination cursor from a previous response.
883
884 statuses: Filter by session status. Repeat the parameter to match any of multiple
885 statuses.
886
887 betas: Optional header to specify the beta version(s) you want to use.
888
889 workspace_id: Optional header to select the Workspace for this request. The value is a
890 Workspace ID (for example, `wrkspc_011CZkZaBF1tNoB5wlCeusgy`).
891
892 Only needed for credentials that can act on more than one Workspace. A
893 credential that belongs to a specific Workspace may omit it; if sent, it must
894 match that Workspace.
895
896 extra_headers: Send extra headers
897
898 extra_query: Add additional query parameters to the request
899
900 extra_body: Add additional JSON properties to the request
901
902 timeout: Override the client-level default timeout for this request, in seconds
903 """
904 extra_headers = {
905 **strip_not_given(
906 {
907 "anthropic-beta": ",".join(chain((str(e) for e in betas), ["managed-agents-2026-04-01"]))
908 if is_given(betas)
909 else not_given,
910 "anthropic-workspace-id": workspace_id,
911 }
912 ),
913 **(extra_headers or {}),
914 }
915 extra_headers = {"anthropic-beta": "managed-agents-2026-04-01", **(extra_headers or {})}
916 return self._get_api_list(
917 "/v1/sessions?beta=true",
918 page=AsyncBidirectionalPageCursor[BetaManagedAgentsSession],
919 options=make_request_options(
920 extra_headers=extra_headers,
921 extra_query=extra_query,
922 extra_body=extra_body,
923 timeout=timeout,
924 query={
925 "agent_id": agent_id,
926 "agent_version": agent_version,
927 "created_at[gt]": created_at_gt,
928 "created_at[gte]": created_at_gte,
929 "created_at[lt]": created_at_lt,
930 "created_at[lte]": created_at_lte,
931 "deployment_id": deployment_id,
932 "include_archived": include_archived,
933 "limit": limit,
934 "memory_store_id": memory_store_id,
935 "order": order,
936 "page": page,
937 "statuses": statuses,
938 },
939 ),
940 model=BetaManagedAgentsSession,
941 )
942
943 async def delete(
944 self,
945 session_id: str,
946 *,
947 betas: List[AnthropicBetaParam] | Omit = omit,
948 workspace_id: str | Omit = omit,
949 # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
950 # The extra values given here take precedence over values defined on the client or passed to this method.
951 extra_headers: Headers | None = None,
952 extra_query: Query | None = None,
953 extra_body: Body | None = None,
954 timeout: float | httpx2.Timeout | None | NotGiven = not_given,
955 ) -> BetaManagedAgentsDeletedSession:
956 """
957 Delete Session
958
959 Args:
960 betas: Optional header to specify the beta version(s) you want to use.
961
962 workspace_id: Optional header to select the Workspace for this request. The value is a
963 Workspace ID (for example, `wrkspc_011CZkZaBF1tNoB5wlCeusgy`).
964
965 Only needed for credentials that can act on more than one Workspace. A
966 credential that belongs to a specific Workspace may omit it; if sent, it must
967 match that Workspace.
968
969 extra_headers: Send extra headers
970
971 extra_query: Add additional query parameters to the request
972
973 extra_body: Add additional JSON properties to the request
974
975 timeout: Override the client-level default timeout for this request, in seconds
976 """
977 if not session_id:
978 raise ValueError(f"Expected a non-empty value for `session_id` but received {session_id!r}")
979 extra_headers = {
980 **strip_not_given(
981 {
982 "anthropic-beta": ",".join(chain((str(e) for e in betas), ["managed-agents-2026-04-01"]))
983 if is_given(betas)
984 else not_given,
985 "anthropic-workspace-id": workspace_id,
986 }
987 ),
988 **(extra_headers or {}),
989 }
990 extra_headers = {"anthropic-beta": "managed-agents-2026-04-01", **(extra_headers or {})}
991 return await self._delete(
992 path_template("/v1/sessions/{session_id}?beta=true", session_id=session_id),
993 options=make_request_options(
994 extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
995 ),
996 cast_to=BetaManagedAgentsDeletedSession,
997 )
998
999 async def archive(
1000 self,
1001 session_id: str,
1002 *,
1003 betas: List[AnthropicBetaParam] | Omit = omit,
1004 workspace_id: str | Omit = omit,
1005 # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
1006 # The extra values given here take precedence over values defined on the client or passed to this method.
1007 extra_headers: Headers | None = None,
1008 extra_query: Query | None = None,
1009 extra_body: Body | None = None,
1010 timeout: float | httpx2.Timeout | None | NotGiven = not_given,
1011 ) -> BetaManagedAgentsSession:
1012 """
1013 Archive Session
1014
1015 Args:
1016 betas: Optional header to specify the beta version(s) you want to use.
1017
1018 workspace_id: Optional header to select the Workspace for this request. The value is a
1019 Workspace ID (for example, `wrkspc_011CZkZaBF1tNoB5wlCeusgy`).
1020
1021 Only needed for credentials that can act on more than one Workspace. A
1022 credential that belongs to a specific Workspace may omit it; if sent, it must
1023 match that Workspace.
1024
1025 extra_headers: Send extra headers
1026
1027 extra_query: Add additional query parameters to the request
1028
1029 extra_body: Add additional JSON properties to the request
1030
1031 timeout: Override the client-level default timeout for this request, in seconds
1032 """
1033 if not session_id:
1034 raise ValueError(f"Expected a non-empty value for `session_id` but received {session_id!r}")
1035 extra_headers = {
1036 **strip_not_given(
1037 {
1038 "anthropic-beta": ",".join(chain((str(e) for e in betas), ["managed-agents-2026-04-01"]))
1039 if is_given(betas)
1040 else not_given,
1041 "anthropic-workspace-id": workspace_id,
1042 }
1043 ),
1044 **(extra_headers or {}),
1045 }
1046 extra_headers = {"anthropic-beta": "managed-agents-2026-04-01", **(extra_headers or {})}
1047 return await self._post(
1048 path_template("/v1/sessions/{session_id}/archive?beta=true", session_id=session_id),
1049 options=make_request_options(
1050 extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
1051 ),
1052 cast_to=BetaManagedAgentsSession,
1053 )
1054
1055
1056 class SessionsWithRawResponse:
1057 def __init__(self, sessions: Sessions) -> None:
1058 self._sessions = sessions
1059
1060 self.create = to_raw_response_wrapper(
1061 sessions.create,
1062 )
1063 self.retrieve = to_raw_response_wrapper(
1064 sessions.retrieve,
1065 )
1066 self.update = to_raw_response_wrapper(
1067 sessions.update,
1068 )
1069 self.list = to_raw_response_wrapper(
1070 sessions.list,
1071 )
1072 self.delete = to_raw_response_wrapper(
1073 sessions.delete,
1074 )
1075 self.archive = to_raw_response_wrapper(
1076 sessions.archive,
1077 )
1078
1079 @cached_property
1080 def events(self) -> EventsWithRawResponse:
1081 return EventsWithRawResponse(self._sessions.events)
1082
1083 @cached_property
1084 def resources(self) -> ResourcesWithRawResponse:
1085 return ResourcesWithRawResponse(self._sessions.resources)
1086
1087 @cached_property
1088 def threads(self) -> ThreadsWithRawResponse:
1089 return ThreadsWithRawResponse(self._sessions.threads)
1090
1091
1092 class AsyncSessionsWithRawResponse:
1093 def __init__(self, sessions: AsyncSessions) -> None:
1094 self._sessions = sessions
1095
1096 self.create = async_to_raw_response_wrapper(
1097 sessions.create,
1098 )
1099 self.retrieve = async_to_raw_response_wrapper(
1100 sessions.retrieve,
1101 )
1102 self.update = async_to_raw_response_wrapper(
1103 sessions.update,
1104 )
1105 self.list = async_to_raw_response_wrapper(
1106 sessions.list,
1107 )
1108 self.delete = async_to_raw_response_wrapper(
1109 sessions.delete,
1110 )
1111 self.archive = async_to_raw_response_wrapper(
1112 sessions.archive,
1113 )
1114
1115 @cached_property
1116 def events(self) -> AsyncEventsWithRawResponse:
1117 return AsyncEventsWithRawResponse(self._sessions.events)
1118
1119 @cached_property
1120 def resources(self) -> AsyncResourcesWithRawResponse:
1121 return AsyncResourcesWithRawResponse(self._sessions.resources)
1122
1123 @cached_property
1124 def threads(self) -> AsyncThreadsWithRawResponse:
1125 return AsyncThreadsWithRawResponse(self._sessions.threads)
1126
1127
1128 class SessionsWithStreamingResponse:
1129 def __init__(self, sessions: Sessions) -> None:
1130 self._sessions = sessions
1131
1132 self.create = to_streamed_response_wrapper(
1133 sessions.create,
1134 )
1135 self.retrieve = to_streamed_response_wrapper(
1136 sessions.retrieve,
1137 )
1138 self.update = to_streamed_response_wrapper(
1139 sessions.update,
1140 )
1141 self.list = to_streamed_response_wrapper(
1142 sessions.list,
1143 )
1144 self.delete = to_streamed_response_wrapper(
1145 sessions.delete,
1146 )
1147 self.archive = to_streamed_response_wrapper(
1148 sessions.archive,
1149 )
1150
1151 @cached_property
1152 def events(self) -> EventsWithStreamingResponse:
1153 return EventsWithStreamingResponse(self._sessions.events)
1154
1155 @cached_property
1156 def resources(self) -> ResourcesWithStreamingResponse:
1157 return ResourcesWithStreamingResponse(self._sessions.resources)
1158
1159 @cached_property
1160 def threads(self) -> ThreadsWithStreamingResponse:
1161 return ThreadsWithStreamingResponse(self._sessions.threads)
1162
1163
1164 class AsyncSessionsWithStreamingResponse:
1165 def __init__(self, sessions: AsyncSessions) -> None:
1166 self._sessions = sessions
1167
1168 self.create = async_to_streamed_response_wrapper(
1169 sessions.create,
1170 )
1171 self.retrieve = async_to_streamed_response_wrapper(
1172 sessions.retrieve,
1173 )
1174 self.update = async_to_streamed_response_wrapper(
1175 sessions.update,
1176 )
1177 self.list = async_to_streamed_response_wrapper(
1178 sessions.list,
1179 )
1180 self.delete = async_to_streamed_response_wrapper(
1181 sessions.delete,
1182 )
1183 self.archive = async_to_streamed_response_wrapper(
1184 sessions.archive,
1185 )
1186
1187 @cached_property
1188 def events(self) -> AsyncEventsWithStreamingResponse:
1189 return AsyncEventsWithStreamingResponse(self._sessions.events)
1190
1191 @cached_property
1192 def resources(self) -> AsyncResourcesWithStreamingResponse:
1193 return AsyncResourcesWithStreamingResponse(self._sessions.resources)
1194
1195 @cached_property
1196 def threads(self) -> AsyncThreadsWithStreamingResponse:
1197 return AsyncThreadsWithStreamingResponse(self._sessions.threads)