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