From 930b1e2d169a291415007f2897fec5a410ecf993 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Sat, 9 May 2026 02:18:16 +0000 Subject: [PATCH 1/6] fix(client): add missing f-string prefix in file type error message --- src/runloop_api_client/_files.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/runloop_api_client/_files.py b/src/runloop_api_client/_files.py index 7e9eeeb10..1a013e434 100644 --- a/src/runloop_api_client/_files.py +++ b/src/runloop_api_client/_files.py @@ -99,7 +99,7 @@ async def async_to_httpx_files(files: RequestFiles | None) -> HttpxRequestFiles elif is_sequence_t(files): files = [(key, await _async_transform_file(file)) for key, file in files] else: - raise TypeError("Unexpected file type input {type(files)}, expected mapping or sequence") + raise TypeError(f"Unexpected file type input {type(files)}, expected mapping or sequence") return files From ba0b5dc873a47073c453b168fe4d966754cccc0e Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Mon, 11 May 2026 21:56:22 +0000 Subject: [PATCH 2/6] feat(metadata): add object metadata viewing, discovery, and validation (#9124) --- .stats.yml | 4 ++-- src/runloop_api_client/types/object_view.py | 5 ++++- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/.stats.yml b/.stats.yml index 20e30a2d9..5a7e0f817 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,4 +1,4 @@ configured_endpoints: 116 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/runloop-ai/runloop-6cf4d9a6afac92d72787088b3aefa941f5240ee522d9e98e1160eea2e29f87f4.yml -openapi_spec_hash: e07fc8349cf507b083830b4e2b0caca0 +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/runloop-ai/runloop-ed882d001bcf991e0081d3bde40bdad5e0083cef74f181964d5f9f76b6ceb3c5.yml +openapi_spec_hash: 78673375a4e58f7b4cea847ce2686b0e config_hash: 436c8d4e665915db22b5d98fe58382c1 diff --git a/src/runloop_api_client/types/object_view.py b/src/runloop_api_client/types/object_view.py index d4ced655f..6823e2b36 100644 --- a/src/runloop_api_client/types/object_view.py +++ b/src/runloop_api_client/types/object_view.py @@ -1,6 +1,6 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -from typing import Optional +from typing import Dict, Optional from typing_extensions import Literal from .._models import BaseModel @@ -29,6 +29,9 @@ class ObjectView(BaseModel): delete_after_time_ms: Optional[int] = None """The time after which the Object will be deleted in milliseconds since epoch.""" + metadata: Optional[Dict[str, str]] = None + """User defined metadata to attach to the Object for organization.""" + size_bytes: Optional[int] = None """The size of the Object content in bytes (null until uploaded).""" From ac1cb2264b8e39da8aa65d8fdcd4595bce55def6 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 12 May 2026 00:37:30 +0000 Subject: [PATCH 3/6] fix: update openapi.stainless.yaml for PTY server methods (#9218) --- .stats.yml | 6 +- api.md | 15 + src/runloop_api_client/_client.py | 38 ++ src/runloop_api_client/resources/__init__.py | 14 + .../resources/devboxes/devboxes.py | 101 +++++ src/runloop_api_client/resources/pty.py | 418 ++++++++++++++++++ src/runloop_api_client/types/__init__.py | 5 + .../types/pty_connect_params.py | 23 + .../types/pty_connect_view.py | 27 ++ .../types/pty_control_params.py | 17 + .../types/pty_control_result_view.py | 13 + .../types/pty_tunnel_view.py | 21 + tests/api_resources/test_devboxes.py | 77 ++++ tests/api_resources/test_pty.py | 216 +++++++++ 14 files changed, 988 insertions(+), 3 deletions(-) create mode 100644 src/runloop_api_client/resources/pty.py create mode 100644 src/runloop_api_client/types/pty_connect_params.py create mode 100644 src/runloop_api_client/types/pty_connect_view.py create mode 100644 src/runloop_api_client/types/pty_control_params.py create mode 100644 src/runloop_api_client/types/pty_control_result_view.py create mode 100644 src/runloop_api_client/types/pty_tunnel_view.py create mode 100644 tests/api_resources/test_pty.py diff --git a/.stats.yml b/.stats.yml index 5a7e0f817..e3de40026 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,4 +1,4 @@ -configured_endpoints: 116 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/runloop-ai/runloop-ed882d001bcf991e0081d3bde40bdad5e0083cef74f181964d5f9f76b6ceb3c5.yml +configured_endpoints: 119 +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/runloop-ai/runloop-40b78fbce4172c1fdab1559718cc9a7ba6b47402ee0bcb8dbefa582448958384.yml openapi_spec_hash: 78673375a4e58f7b4cea847ce2686b0e -config_hash: 436c8d4e665915db22b5d98fe58382c1 +config_hash: 07d725fff578f22e8cb52e3c588f24c6 diff --git a/api.md b/api.md index 555f0c4f8..22db26e92 100644 --- a/api.md +++ b/api.md @@ -198,6 +198,7 @@ from runloop_api_client.types import ( DevboxSnapshotListView, DevboxSnapshotView, DevboxView, + PtyTunnelView, TunnelView, DevboxCreateSSHKeyResponse, DevboxReadFileContentsResponse, @@ -211,6 +212,7 @@ Methods: - client.devboxes.retrieve(id) -> DevboxView - client.devboxes.update(id, \*\*params) -> DevboxView - client.devboxes.list(\*\*params) -> SyncDevboxesCursorIDPage[DevboxView] +- client.devboxes.create_pty_tunnel(id) -> PtyTunnelView - client.devboxes.create_ssh_key(id) -> DevboxCreateSSHKeyResponse - client.devboxes.delete_disk_snapshot(id) -> object - client.devboxes.download_file(id, \*\*params) -> BinaryAPIResponse @@ -278,6 +280,19 @@ Methods: - client.devboxes.executions.stream_stderr_updates(execution_id, \*, devbox_id, \*\*params) -> ExecutionUpdateChunk - client.devboxes.executions.stream_stdout_updates(execution_id, \*, devbox_id, \*\*params) -> ExecutionUpdateChunk +# Pty + +Types: + +```python +from runloop_api_client.types import PtyConnectView, PtyControlParameters, PtyControlResultView +``` + +Methods: + +- client.pty.connect(session_name, \*\*params) -> PtyConnectView +- client.pty.control(session_name, \*\*params) -> PtyControlResultView + # Scenarios Types: diff --git a/src/runloop_api_client/_client.py b/src/runloop_api_client/_client.py index 3d032dfd6..9e422721e 100644 --- a/src/runloop_api_client/_client.py +++ b/src/runloop_api_client/_client.py @@ -36,6 +36,7 @@ if TYPE_CHECKING: from .resources import ( + pty, axons, agents, apikeys, @@ -52,6 +53,7 @@ restricted_keys, network_policies, ) + from .resources.pty import PtyResource, AsyncPtyResource from .resources.agents import AgentsResource, AsyncAgentsResource from .resources.apikeys import ApikeysResource, AsyncApikeysResource from .resources.objects import ObjectsResource, AsyncObjectsResource @@ -184,6 +186,12 @@ def devboxes(self) -> DevboxesResource: return DevboxesResource(self) + @cached_property + def pty(self) -> PtyResource: + from .resources.pty import PtyResource + + return PtyResource(self) + @cached_property def scenarios(self) -> ScenariosResource: from .resources.scenarios import ScenariosResource @@ -466,6 +474,12 @@ def devboxes(self) -> AsyncDevboxesResource: return AsyncDevboxesResource(self) + @cached_property + def pty(self) -> AsyncPtyResource: + from .resources.pty import AsyncPtyResource + + return AsyncPtyResource(self) + @cached_property def scenarios(self) -> AsyncScenariosResource: from .resources.scenarios import AsyncScenariosResource @@ -683,6 +697,12 @@ def devboxes(self) -> devboxes.DevboxesResourceWithRawResponse: return DevboxesResourceWithRawResponse(self._client.devboxes) + @cached_property + def pty(self) -> pty.PtyResourceWithRawResponse: + from .resources.pty import PtyResourceWithRawResponse + + return PtyResourceWithRawResponse(self._client.pty) + @cached_property def scenarios(self) -> scenarios.ScenariosResourceWithRawResponse: from .resources.scenarios import ScenariosResourceWithRawResponse @@ -780,6 +800,12 @@ def devboxes(self) -> devboxes.AsyncDevboxesResourceWithRawResponse: return AsyncDevboxesResourceWithRawResponse(self._client.devboxes) + @cached_property + def pty(self) -> pty.AsyncPtyResourceWithRawResponse: + from .resources.pty import AsyncPtyResourceWithRawResponse + + return AsyncPtyResourceWithRawResponse(self._client.pty) + @cached_property def scenarios(self) -> scenarios.AsyncScenariosResourceWithRawResponse: from .resources.scenarios import AsyncScenariosResourceWithRawResponse @@ -877,6 +903,12 @@ def devboxes(self) -> devboxes.DevboxesResourceWithStreamingResponse: return DevboxesResourceWithStreamingResponse(self._client.devboxes) + @cached_property + def pty(self) -> pty.PtyResourceWithStreamingResponse: + from .resources.pty import PtyResourceWithStreamingResponse + + return PtyResourceWithStreamingResponse(self._client.pty) + @cached_property def scenarios(self) -> scenarios.ScenariosResourceWithStreamingResponse: from .resources.scenarios import ScenariosResourceWithStreamingResponse @@ -974,6 +1006,12 @@ def devboxes(self) -> devboxes.AsyncDevboxesResourceWithStreamingResponse: return AsyncDevboxesResourceWithStreamingResponse(self._client.devboxes) + @cached_property + def pty(self) -> pty.AsyncPtyResourceWithStreamingResponse: + from .resources.pty import AsyncPtyResourceWithStreamingResponse + + return AsyncPtyResourceWithStreamingResponse(self._client.pty) + @cached_property def scenarios(self) -> scenarios.AsyncScenariosResourceWithStreamingResponse: from .resources.scenarios import AsyncScenariosResourceWithStreamingResponse diff --git a/src/runloop_api_client/resources/__init__.py b/src/runloop_api_client/resources/__init__.py index dd27ba9e4..e7442ab06 100644 --- a/src/runloop_api_client/resources/__init__.py +++ b/src/runloop_api_client/resources/__init__.py @@ -1,5 +1,13 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +from .pty import ( + PtyResource, + AsyncPtyResource, + PtyResourceWithRawResponse, + AsyncPtyResourceWithRawResponse, + PtyResourceWithStreamingResponse, + AsyncPtyResourceWithStreamingResponse, +) from .axons import ( AxonsResource, AsyncAxonsResource, @@ -164,6 +172,12 @@ "AsyncDevboxesResourceWithRawResponse", "DevboxesResourceWithStreamingResponse", "AsyncDevboxesResourceWithStreamingResponse", + "PtyResource", + "AsyncPtyResource", + "PtyResourceWithRawResponse", + "AsyncPtyResourceWithRawResponse", + "PtyResourceWithStreamingResponse", + "AsyncPtyResourceWithStreamingResponse", "ScenariosResource", "AsyncScenariosResource", "ScenariosResourceWithRawResponse", diff --git a/src/runloop_api_client/resources/devboxes/devboxes.py b/src/runloop_api_client/resources/devboxes/devboxes.py index 888369e98..7948b97d2 100644 --- a/src/runloop_api_client/resources/devboxes/devboxes.py +++ b/src/runloop_api_client/resources/devboxes/devboxes.py @@ -86,6 +86,7 @@ from ...types.devbox_view import DevboxView from ...types.tunnel_view import TunnelView from ...lib.wait_for_status import wait_for_status, async_wait_for_status +from ...types.pty_tunnel_view import PtyTunnelView from ...types.shared_params.mount import Mount from ...types.devbox_snapshot_view import DevboxSnapshotView from ...types.shared.launch_parameters import LaunchParameters as SharedLaunchParameters @@ -582,6 +583,50 @@ def list( model=DevboxView, ) + def create_pty_tunnel( + self, + id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + idempotency_key: str | None = None, + ) -> PtyTunnelView: + """Create an ephemeral authenticated tunnel for terminal access to a running + Devbox. + + This tunnel is not persisted on the Devbox and is generated fresh on + each request. The returned auth_token must be passed as a Bearer token in the + Authorization header. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + + idempotency_key: Specify a custom idempotency key for this request + """ + if not id: + raise ValueError(f"Expected a non-empty value for `id` but received {id!r}") + return self._post( + path_template("/v1/devboxes/{id}/create_pty_tunnel", id=id), + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + idempotency_key=idempotency_key, + ), + cast_to=PtyTunnelView, + ) + def create_ssh_key( self, id: str, @@ -2200,6 +2245,50 @@ def list( model=DevboxView, ) + async def create_pty_tunnel( + self, + id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + idempotency_key: str | None = None, + ) -> PtyTunnelView: + """Create an ephemeral authenticated tunnel for terminal access to a running + Devbox. + + This tunnel is not persisted on the Devbox and is generated fresh on + each request. The returned auth_token must be passed as a Bearer token in the + Authorization header. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + + idempotency_key: Specify a custom idempotency key for this request + """ + if not id: + raise ValueError(f"Expected a non-empty value for `id` but received {id!r}") + return await self._post( + path_template("/v1/devboxes/{id}/create_pty_tunnel", id=id), + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + idempotency_key=idempotency_key, + ), + cast_to=PtyTunnelView, + ) + async def create_ssh_key( self, id: str, @@ -3375,6 +3464,9 @@ def __init__(self, devboxes: DevboxesResource) -> None: self.list = to_raw_response_wrapper( devboxes.list, ) + self.create_pty_tunnel = to_raw_response_wrapper( + devboxes.create_pty_tunnel, + ) self.create_ssh_key = to_raw_response_wrapper( devboxes.create_ssh_key, ) @@ -3468,6 +3560,9 @@ def __init__(self, devboxes: AsyncDevboxesResource) -> None: self.list = async_to_raw_response_wrapper( devboxes.list, ) + self.create_pty_tunnel = async_to_raw_response_wrapper( + devboxes.create_pty_tunnel, + ) self.create_ssh_key = async_to_raw_response_wrapper( devboxes.create_ssh_key, ) @@ -3561,6 +3656,9 @@ def __init__(self, devboxes: DevboxesResource) -> None: self.list = to_streamed_response_wrapper( devboxes.list, ) + self.create_pty_tunnel = to_streamed_response_wrapper( + devboxes.create_pty_tunnel, + ) self.create_ssh_key = to_streamed_response_wrapper( devboxes.create_ssh_key, ) @@ -3654,6 +3752,9 @@ def __init__(self, devboxes: AsyncDevboxesResource) -> None: self.list = async_to_streamed_response_wrapper( devboxes.list, ) + self.create_pty_tunnel = async_to_streamed_response_wrapper( + devboxes.create_pty_tunnel, + ) self.create_ssh_key = async_to_streamed_response_wrapper( devboxes.create_ssh_key, ) diff --git a/src/runloop_api_client/resources/pty.py b/src/runloop_api_client/resources/pty.py new file mode 100644 index 000000000..927d9604e --- /dev/null +++ b/src/runloop_api_client/resources/pty.py @@ -0,0 +1,418 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal + +import httpx + +from ..types import pty_connect_params, pty_control_params +from .._types import Body, Omit, Query, Headers, NotGiven, omit, not_given +from .._utils import path_template, maybe_transform, async_maybe_transform +from .._compat import cached_property +from .._resource import SyncAPIResource, AsyncAPIResource +from .._response import ( + to_raw_response_wrapper, + to_streamed_response_wrapper, + async_to_raw_response_wrapper, + async_to_streamed_response_wrapper, +) +from .._base_client import make_request_options +from ..types.pty_connect_view import PtyConnectView +from ..types.pty_control_result_view import PtyControlResultView + +__all__ = ["PtyResource", "AsyncPtyResource"] + + +class PtyResource(SyncAPIResource): + @cached_property + def with_raw_response(self) -> PtyResourceWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/runloopai/api-client-python#accessing-raw-response-data-eg-headers + """ + return PtyResourceWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> PtyResourceWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/runloopai/api-client-python#with_streaming_response + """ + return PtyResourceWithStreamingResponse(self) + + def connect( + self, + session_name: str, + *, + cols: str | Omit = omit, + rows: str | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> PtyConnectView: + """ + Looks up the PTY session identified by the path session*name and either + reconnects to the existing session or creates it if it does not yet exist. The + session_name is a client-chosen session identifier, not an opaque server-issued + ID. It must be non-empty (1..=256 chars) and use only ASCII letters, digits, '-' + and '*'. A newly created PTY session starts an interactive bash shell on the + Devbox. Optional cols and rows query parameters apply an initial terminal size + before any I/O; they must both be present and in the range 1..=1000 to take + effect. The response returns a PtyConnectView containing connect_url (a + server-relative path to the WebSocket data plane), idle_ttl_seconds (how long + this session is retained after the last client disconnects), and the resulting + cols/rows. The interactive byte stream itself is intentionally not modeled in + OpenAPI; see the controller-level documentation for the WebSocket close-code + conventions. The single-attach contract is enforced when a client opens the + WebSocket data plane, not on this bootstrap call: bootstrap always succeeds for + a valid session_name, even if another client is currently attached. Rejection of + a second concurrent attach happens at WebSocket upgrade time. If the active + client disconnects, the session is preserved for the idle TTL so a later connect + using the same session_name resumes the same shell. After the TTL expires, after + an explicit close control action, or after the underlying Devbox lifecycle + replaces the PTY process (such as through suspend/resume), a later request with + the same session_name creates a fresh PTY session without the previous shell + state. + + Documentation note: this operation is published from mux strictly as an OpenAPI + contract stub for the PTY service control plane. It is not evidence that mux + itself serves the interactive PTY transport. + + Args: + cols: Optional initial terminal width in character cells (1..=1000). Defaults to 80 + when omitted. Applied only if both cols and rows are provided; otherwise + ignored. + + rows: Optional initial terminal height in character cells (1..=1000). Defaults to 24 + when omitted. Applied only if both cols and rows are provided; otherwise + ignored. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not session_name: + raise ValueError(f"Expected a non-empty value for `session_name` but received {session_name!r}") + return self._get( + path_template("/pty/{session_name}", session_name=session_name), + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform( + { + "cols": cols, + "rows": rows, + }, + pty_connect_params.PtyConnectParams, + ), + ), + cast_to=PtyConnectView, + ) + + def control( + self, + session_name: str, + *, + action: Literal["resize", "signal", "close"] | Omit = omit, + cols: int | Omit = omit, + rows: int | Omit = omit, + signal: str | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + idempotency_key: str | None = None, + ) -> PtyControlResultView: + """Applies a PTY control operation to an existing session. + + The action field selects + the operation; the other fields in PtyControlParameters are interpreted only + when they are relevant to the chosen action. + + resize: cols and rows are required and must each be in 1..=1000. A 0 or + out-of-range value returns 400. The new winsize is applied to the PTY master and + the kernel delivers SIGWINCH to the foreground process group. + + signal: signal is the POSIX signal name (for example 'SIGTERM', 'SIGHUP', + 'SIGINT', 'SIGUSR1'). Unknown signal names return 400. The signal is delivered + to the slave's foreground process group via killpg(2). If the shell has already + exited and there is no foreground process group, returns 400. + + close: terminates the session. Sends SIGHUP to the foreground process group + (best-effort; ignored if the shell has already exited) and drops the session + from the server's session cache. A subsequent connect with the same session_name + will create a fresh PTY session. + + Documentation note: this operation is published from mux strictly as an OpenAPI + contract stub for the PTY service control plane. It is not evidence that mux + itself serves the interactive PTY transport. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + + idempotency_key: Specify a custom idempotency key for this request + """ + if not session_name: + raise ValueError(f"Expected a non-empty value for `session_name` but received {session_name!r}") + return self._post( + path_template("/pty/{session_name}/control", session_name=session_name), + body=maybe_transform( + { + "action": action, + "cols": cols, + "rows": rows, + "signal": signal, + }, + pty_control_params.PtyControlParams, + ), + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + idempotency_key=idempotency_key, + ), + cast_to=PtyControlResultView, + ) + + +class AsyncPtyResource(AsyncAPIResource): + @cached_property + def with_raw_response(self) -> AsyncPtyResourceWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/runloopai/api-client-python#accessing-raw-response-data-eg-headers + """ + return AsyncPtyResourceWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> AsyncPtyResourceWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/runloopai/api-client-python#with_streaming_response + """ + return AsyncPtyResourceWithStreamingResponse(self) + + async def connect( + self, + session_name: str, + *, + cols: str | Omit = omit, + rows: str | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> PtyConnectView: + """ + Looks up the PTY session identified by the path session*name and either + reconnects to the existing session or creates it if it does not yet exist. The + session_name is a client-chosen session identifier, not an opaque server-issued + ID. It must be non-empty (1..=256 chars) and use only ASCII letters, digits, '-' + and '*'. A newly created PTY session starts an interactive bash shell on the + Devbox. Optional cols and rows query parameters apply an initial terminal size + before any I/O; they must both be present and in the range 1..=1000 to take + effect. The response returns a PtyConnectView containing connect_url (a + server-relative path to the WebSocket data plane), idle_ttl_seconds (how long + this session is retained after the last client disconnects), and the resulting + cols/rows. The interactive byte stream itself is intentionally not modeled in + OpenAPI; see the controller-level documentation for the WebSocket close-code + conventions. The single-attach contract is enforced when a client opens the + WebSocket data plane, not on this bootstrap call: bootstrap always succeeds for + a valid session_name, even if another client is currently attached. Rejection of + a second concurrent attach happens at WebSocket upgrade time. If the active + client disconnects, the session is preserved for the idle TTL so a later connect + using the same session_name resumes the same shell. After the TTL expires, after + an explicit close control action, or after the underlying Devbox lifecycle + replaces the PTY process (such as through suspend/resume), a later request with + the same session_name creates a fresh PTY session without the previous shell + state. + + Documentation note: this operation is published from mux strictly as an OpenAPI + contract stub for the PTY service control plane. It is not evidence that mux + itself serves the interactive PTY transport. + + Args: + cols: Optional initial terminal width in character cells (1..=1000). Defaults to 80 + when omitted. Applied only if both cols and rows are provided; otherwise + ignored. + + rows: Optional initial terminal height in character cells (1..=1000). Defaults to 24 + when omitted. Applied only if both cols and rows are provided; otherwise + ignored. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not session_name: + raise ValueError(f"Expected a non-empty value for `session_name` but received {session_name!r}") + return await self._get( + path_template("/pty/{session_name}", session_name=session_name), + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=await async_maybe_transform( + { + "cols": cols, + "rows": rows, + }, + pty_connect_params.PtyConnectParams, + ), + ), + cast_to=PtyConnectView, + ) + + async def control( + self, + session_name: str, + *, + action: Literal["resize", "signal", "close"] | Omit = omit, + cols: int | Omit = omit, + rows: int | Omit = omit, + signal: str | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + idempotency_key: str | None = None, + ) -> PtyControlResultView: + """Applies a PTY control operation to an existing session. + + The action field selects + the operation; the other fields in PtyControlParameters are interpreted only + when they are relevant to the chosen action. + + resize: cols and rows are required and must each be in 1..=1000. A 0 or + out-of-range value returns 400. The new winsize is applied to the PTY master and + the kernel delivers SIGWINCH to the foreground process group. + + signal: signal is the POSIX signal name (for example 'SIGTERM', 'SIGHUP', + 'SIGINT', 'SIGUSR1'). Unknown signal names return 400. The signal is delivered + to the slave's foreground process group via killpg(2). If the shell has already + exited and there is no foreground process group, returns 400. + + close: terminates the session. Sends SIGHUP to the foreground process group + (best-effort; ignored if the shell has already exited) and drops the session + from the server's session cache. A subsequent connect with the same session_name + will create a fresh PTY session. + + Documentation note: this operation is published from mux strictly as an OpenAPI + contract stub for the PTY service control plane. It is not evidence that mux + itself serves the interactive PTY transport. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + + idempotency_key: Specify a custom idempotency key for this request + """ + if not session_name: + raise ValueError(f"Expected a non-empty value for `session_name` but received {session_name!r}") + return await self._post( + path_template("/pty/{session_name}/control", session_name=session_name), + body=await async_maybe_transform( + { + "action": action, + "cols": cols, + "rows": rows, + "signal": signal, + }, + pty_control_params.PtyControlParams, + ), + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + idempotency_key=idempotency_key, + ), + cast_to=PtyControlResultView, + ) + + +class PtyResourceWithRawResponse: + def __init__(self, pty: PtyResource) -> None: + self._pty = pty + + self.connect = to_raw_response_wrapper( + pty.connect, + ) + self.control = to_raw_response_wrapper( + pty.control, + ) + + +class AsyncPtyResourceWithRawResponse: + def __init__(self, pty: AsyncPtyResource) -> None: + self._pty = pty + + self.connect = async_to_raw_response_wrapper( + pty.connect, + ) + self.control = async_to_raw_response_wrapper( + pty.control, + ) + + +class PtyResourceWithStreamingResponse: + def __init__(self, pty: PtyResource) -> None: + self._pty = pty + + self.connect = to_streamed_response_wrapper( + pty.connect, + ) + self.control = to_streamed_response_wrapper( + pty.control, + ) + + +class AsyncPtyResourceWithStreamingResponse: + def __init__(self, pty: AsyncPtyResource) -> None: + self._pty = pty + + self.connect = async_to_streamed_response_wrapper( + pty.connect, + ) + self.control = async_to_streamed_response_wrapper( + pty.control, + ) diff --git a/src/runloop_api_client/types/__init__.py b/src/runloop_api_client/types/__init__.py index 01130880d..b28ef2790 100644 --- a/src/runloop_api_client/types/__init__.py +++ b/src/runloop_api_client/types/__init__.py @@ -27,9 +27,11 @@ from .agent_list_view import AgentListView as AgentListView from .axon_event_view import AxonEventView as AxonEventView from .mcp_config_view import McpConfigView as McpConfigView +from .pty_tunnel_view import PtyTunnelView as PtyTunnelView from .axon_list_params import AxonListParams as AxonListParams from .devbox_list_view import DevboxListView as DevboxListView from .object_list_view import ObjectListView as ObjectListView +from .pty_connect_view import PtyConnectView as PtyConnectView from .scope_entry_view import ScopeEntryView as ScopeEntryView from .scoring_contract import ScoringContract as ScoringContract from .scoring_function import ScoringFunction as ScoringFunction @@ -41,6 +43,8 @@ from .benchmark_run_view import BenchmarkRunView as BenchmarkRunView from .devbox_list_params import DevboxListParams as DevboxListParams from .object_list_params import ObjectListParams as ObjectListParams +from .pty_connect_params import PtyConnectParams as PtyConnectParams +from .pty_control_params import PtyControlParams as PtyControlParams from .secret_list_params import SecretListParams as SecretListParams from .agent_create_params import AgentCreateParams as AgentCreateParams from .axon_publish_params import AxonPublishParams as AxonPublishParams @@ -80,6 +84,7 @@ from .benchmark_update_params import BenchmarkUpdateParams as BenchmarkUpdateParams from .blueprint_create_params import BlueprintCreateParams as BlueprintCreateParams from .inspection_source_param import InspectionSourceParam as InspectionSourceParam +from .pty_control_result_view import PtyControlResultView as PtyControlResultView from .agent_devbox_counts_view import AgentDevboxCountsView as AgentDevboxCountsView from .agent_list_public_params import AgentListPublicParams as AgentListPublicParams from .blueprint_preview_params import BlueprintPreviewParams as BlueprintPreviewParams diff --git a/src/runloop_api_client/types/pty_connect_params.py b/src/runloop_api_client/types/pty_connect_params.py new file mode 100644 index 000000000..5df1af0ed --- /dev/null +++ b/src/runloop_api_client/types/pty_connect_params.py @@ -0,0 +1,23 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import TypedDict + +__all__ = ["PtyConnectParams"] + + +class PtyConnectParams(TypedDict, total=False): + cols: str + """Optional initial terminal width in character cells (1..=1000). + + Defaults to 80 when omitted. Applied only if both cols and rows are provided; + otherwise ignored. + """ + + rows: str + """Optional initial terminal height in character cells (1..=1000). + + Defaults to 24 when omitted. Applied only if both cols and rows are provided; + otherwise ignored. + """ diff --git a/src/runloop_api_client/types/pty_connect_view.py b/src/runloop_api_client/types/pty_connect_view.py new file mode 100644 index 000000000..625c1fd4f --- /dev/null +++ b/src/runloop_api_client/types/pty_connect_view.py @@ -0,0 +1,27 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional + +from .._models import BaseModel + +__all__ = ["PtyConnectView"] + + +class PtyConnectView(BaseModel): + attached: bool + + created: bool + + cols: Optional[int] = None + + connect_url: Optional[str] = None + + idle_ttl_seconds: Optional[int] = None + + protocol_version: Optional[str] = None + + rows: Optional[int] = None + + session_name: Optional[str] = None + + status: Optional[str] = None diff --git a/src/runloop_api_client/types/pty_control_params.py b/src/runloop_api_client/types/pty_control_params.py new file mode 100644 index 000000000..8d6b3cf5a --- /dev/null +++ b/src/runloop_api_client/types/pty_control_params.py @@ -0,0 +1,17 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, TypedDict + +__all__ = ["PtyControlParams"] + + +class PtyControlParams(TypedDict, total=False): + action: Literal["resize", "signal", "close"] + + cols: int + + rows: int + + signal: str diff --git a/src/runloop_api_client/types/pty_control_result_view.py b/src/runloop_api_client/types/pty_control_result_view.py new file mode 100644 index 000000000..e72a0f6be --- /dev/null +++ b/src/runloop_api_client/types/pty_control_result_view.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional + +from .._models import BaseModel + +__all__ = ["PtyControlResultView"] + + +class PtyControlResultView(BaseModel): + session_name: Optional[str] = None + + status: Optional[str] = None diff --git a/src/runloop_api_client/types/pty_tunnel_view.py b/src/runloop_api_client/types/pty_tunnel_view.py new file mode 100644 index 000000000..3012798ba --- /dev/null +++ b/src/runloop_api_client/types/pty_tunnel_view.py @@ -0,0 +1,21 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from .._models import BaseModel + +__all__ = ["PtyTunnelView"] + + +class PtyTunnelView(BaseModel): + """An ephemeral PTY tunnel providing authenticated terminal access to a Devbox. + + These tunnels are not stored on the Devbox and are generated fresh on each request. Usage: https://{port}-{tunnel_key}.tunnel.runloop.ai with Authorization: Bearer {auth_token} + """ + + auth_token: str + """Bearer token for tunnel authentication. Always required for PTY tunnels.""" + + tunnel_key: str + """The encrypted tunnel key used to construct the tunnel URL. + + URL format: https://{port}-{tunnel_key}.tunnel.runloop.{domain} + """ diff --git a/tests/api_resources/test_devboxes.py b/tests/api_resources/test_devboxes.py index 920ff437a..97f51b915 100644 --- a/tests/api_resources/test_devboxes.py +++ b/tests/api_resources/test_devboxes.py @@ -15,6 +15,7 @@ from runloop_api_client.types import ( DevboxView, TunnelView, + PtyTunnelView, DevboxSnapshotView, DevboxResourceUsageView, DevboxExecutionDetailView, @@ -269,6 +270,44 @@ def test_streaming_response_list(self, client: Runloop) -> None: assert cast(Any, response.is_closed) is True + @parametrize + def test_method_create_pty_tunnel(self, client: Runloop) -> None: + devbox = client.devboxes.create_pty_tunnel( + "id", + ) + assert_matches_type(PtyTunnelView, devbox, path=["response"]) + + @parametrize + def test_raw_response_create_pty_tunnel(self, client: Runloop) -> None: + response = client.devboxes.with_raw_response.create_pty_tunnel( + "id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + devbox = response.parse() + assert_matches_type(PtyTunnelView, devbox, path=["response"]) + + @parametrize + def test_streaming_response_create_pty_tunnel(self, client: Runloop) -> None: + with client.devboxes.with_streaming_response.create_pty_tunnel( + "id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + devbox = response.parse() + assert_matches_type(PtyTunnelView, devbox, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + def test_path_params_create_pty_tunnel(self, client: Runloop) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `id` but received ''"): + client.devboxes.with_raw_response.create_pty_tunnel( + "", + ) + @parametrize def test_method_create_ssh_key(self, client: Runloop) -> None: devbox = client.devboxes.create_ssh_key( @@ -1896,6 +1935,44 @@ async def test_streaming_response_list(self, async_client: AsyncRunloop) -> None assert cast(Any, response.is_closed) is True + @parametrize + async def test_method_create_pty_tunnel(self, async_client: AsyncRunloop) -> None: + devbox = await async_client.devboxes.create_pty_tunnel( + "id", + ) + assert_matches_type(PtyTunnelView, devbox, path=["response"]) + + @parametrize + async def test_raw_response_create_pty_tunnel(self, async_client: AsyncRunloop) -> None: + response = await async_client.devboxes.with_raw_response.create_pty_tunnel( + "id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + devbox = await response.parse() + assert_matches_type(PtyTunnelView, devbox, path=["response"]) + + @parametrize + async def test_streaming_response_create_pty_tunnel(self, async_client: AsyncRunloop) -> None: + async with async_client.devboxes.with_streaming_response.create_pty_tunnel( + "id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + devbox = await response.parse() + assert_matches_type(PtyTunnelView, devbox, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + async def test_path_params_create_pty_tunnel(self, async_client: AsyncRunloop) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `id` but received ''"): + await async_client.devboxes.with_raw_response.create_pty_tunnel( + "", + ) + @parametrize async def test_method_create_ssh_key(self, async_client: AsyncRunloop) -> None: devbox = await async_client.devboxes.create_ssh_key( diff --git a/tests/api_resources/test_pty.py b/tests/api_resources/test_pty.py new file mode 100644 index 000000000..411bab45b --- /dev/null +++ b/tests/api_resources/test_pty.py @@ -0,0 +1,216 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +import os +from typing import Any, cast + +import pytest + +from tests.utils import assert_matches_type +from runloop_api_client import Runloop, AsyncRunloop +from runloop_api_client.types import PtyConnectView, PtyControlResultView + +base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010") + + +class TestPty: + parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"]) + + @parametrize + def test_method_connect(self, client: Runloop) -> None: + pty = client.pty.connect( + session_name="session_name", + ) + assert_matches_type(PtyConnectView, pty, path=["response"]) + + @parametrize + def test_method_connect_with_all_params(self, client: Runloop) -> None: + pty = client.pty.connect( + session_name="session_name", + cols="cols", + rows="rows", + ) + assert_matches_type(PtyConnectView, pty, path=["response"]) + + @parametrize + def test_raw_response_connect(self, client: Runloop) -> None: + response = client.pty.with_raw_response.connect( + session_name="session_name", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + pty = response.parse() + assert_matches_type(PtyConnectView, pty, path=["response"]) + + @parametrize + def test_streaming_response_connect(self, client: Runloop) -> None: + with client.pty.with_streaming_response.connect( + session_name="session_name", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + pty = response.parse() + assert_matches_type(PtyConnectView, pty, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + def test_path_params_connect(self, client: Runloop) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `session_name` but received ''"): + client.pty.with_raw_response.connect( + session_name="", + ) + + @parametrize + def test_method_control(self, client: Runloop) -> None: + pty = client.pty.control( + session_name="session_name", + ) + assert_matches_type(PtyControlResultView, pty, path=["response"]) + + @parametrize + def test_method_control_with_all_params(self, client: Runloop) -> None: + pty = client.pty.control( + session_name="session_name", + action="resize", + cols=0, + rows=0, + signal="signal", + ) + assert_matches_type(PtyControlResultView, pty, path=["response"]) + + @parametrize + def test_raw_response_control(self, client: Runloop) -> None: + response = client.pty.with_raw_response.control( + session_name="session_name", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + pty = response.parse() + assert_matches_type(PtyControlResultView, pty, path=["response"]) + + @parametrize + def test_streaming_response_control(self, client: Runloop) -> None: + with client.pty.with_streaming_response.control( + session_name="session_name", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + pty = response.parse() + assert_matches_type(PtyControlResultView, pty, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + def test_path_params_control(self, client: Runloop) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `session_name` but received ''"): + client.pty.with_raw_response.control( + session_name="", + ) + + +class TestAsyncPty: + parametrize = pytest.mark.parametrize( + "async_client", [False, True, {"http_client": "aiohttp"}], indirect=True, ids=["loose", "strict", "aiohttp"] + ) + + @parametrize + async def test_method_connect(self, async_client: AsyncRunloop) -> None: + pty = await async_client.pty.connect( + session_name="session_name", + ) + assert_matches_type(PtyConnectView, pty, path=["response"]) + + @parametrize + async def test_method_connect_with_all_params(self, async_client: AsyncRunloop) -> None: + pty = await async_client.pty.connect( + session_name="session_name", + cols="cols", + rows="rows", + ) + assert_matches_type(PtyConnectView, pty, path=["response"]) + + @parametrize + async def test_raw_response_connect(self, async_client: AsyncRunloop) -> None: + response = await async_client.pty.with_raw_response.connect( + session_name="session_name", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + pty = await response.parse() + assert_matches_type(PtyConnectView, pty, path=["response"]) + + @parametrize + async def test_streaming_response_connect(self, async_client: AsyncRunloop) -> None: + async with async_client.pty.with_streaming_response.connect( + session_name="session_name", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + pty = await response.parse() + assert_matches_type(PtyConnectView, pty, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + async def test_path_params_connect(self, async_client: AsyncRunloop) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `session_name` but received ''"): + await async_client.pty.with_raw_response.connect( + session_name="", + ) + + @parametrize + async def test_method_control(self, async_client: AsyncRunloop) -> None: + pty = await async_client.pty.control( + session_name="session_name", + ) + assert_matches_type(PtyControlResultView, pty, path=["response"]) + + @parametrize + async def test_method_control_with_all_params(self, async_client: AsyncRunloop) -> None: + pty = await async_client.pty.control( + session_name="session_name", + action="resize", + cols=0, + rows=0, + signal="signal", + ) + assert_matches_type(PtyControlResultView, pty, path=["response"]) + + @parametrize + async def test_raw_response_control(self, async_client: AsyncRunloop) -> None: + response = await async_client.pty.with_raw_response.control( + session_name="session_name", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + pty = await response.parse() + assert_matches_type(PtyControlResultView, pty, path=["response"]) + + @parametrize + async def test_streaming_response_control(self, async_client: AsyncRunloop) -> None: + async with async_client.pty.with_streaming_response.control( + session_name="session_name", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + pty = await response.parse() + assert_matches_type(PtyControlResultView, pty, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + async def test_path_params_control(self, async_client: AsyncRunloop) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `session_name` but received ''"): + await async_client.pty.with_raw_response.control( + session_name="", + ) From f089d05c5e00c2ba980d0afdea79ed026242a174 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 12 May 2026 02:15:09 +0000 Subject: [PATCH 4/6] feat(internal/types): support eagerly validating pydantic iterators --- src/runloop_api_client/_models.py | 80 +++++++++++++++++++++++++++++++ tests/test_models.py | 60 +++++++++++++++++++++-- 2 files changed, 137 insertions(+), 3 deletions(-) diff --git a/src/runloop_api_client/_models.py b/src/runloop_api_client/_models.py index 82709d693..eb006cde3 100644 --- a/src/runloop_api_client/_models.py +++ b/src/runloop_api_client/_models.py @@ -25,7 +25,9 @@ ClassVar, Protocol, Required, + Annotated, ParamSpec, + TypeAlias, TypedDict, TypeGuard, final, @@ -79,7 +81,15 @@ from ._constants import RAW_RESPONSE_HEADER if TYPE_CHECKING: + from pydantic import GetCoreSchemaHandler, ValidatorFunctionWrapHandler + from pydantic_core import CoreSchema, core_schema from pydantic_core.core_schema import ModelField, ModelSchema, LiteralSchema, ModelFieldsSchema +else: + try: + from pydantic_core import CoreSchema, core_schema + except ImportError: + CoreSchema = None + core_schema = None __all__ = ["BaseModel", "GenericModel"] @@ -396,6 +406,76 @@ def model_dump_json( ) +class _EagerIterable(list[_T], Generic[_T]): + """ + Accepts any Iterable[T] input (including generators), consumes it + eagerly, and validates all items upfront. + + Validation preserves the original container type where possible + (e.g. a set[T] stays a set[T]). Serialization (model_dump / JSON) + always emits a list — round-tripping through model_dump() will not + restore the original container type. + """ + + @classmethod + def __get_pydantic_core_schema__( + cls, + source_type: Any, + handler: GetCoreSchemaHandler, + ) -> CoreSchema: + (item_type,) = get_args(source_type) or (Any,) + item_schema: CoreSchema = handler.generate_schema(item_type) + list_of_items_schema: CoreSchema = core_schema.list_schema(item_schema) + + return core_schema.no_info_wrap_validator_function( + cls._validate, + list_of_items_schema, + serialization=core_schema.plain_serializer_function_ser_schema( + cls._serialize, + info_arg=False, + ), + ) + + @staticmethod + def _validate(v: Iterable[_T], handler: "ValidatorFunctionWrapHandler") -> Any: + original_type: type[Any] = type(v) + + # Normalize to list so list_schema can validate each item + if isinstance(v, list): + items: list[_T] = v + else: + try: + items = list(v) + except TypeError as e: + raise TypeError("Value is not iterable") from e + + # Validate items against the inner schema + validated: list[_T] = handler(items) + + # Reconstruct original container type + if original_type is list: + return validated + # str(list) produces the list's repr, not a string built from items, + # so skip reconstruction for str and its subclasses. + if issubclass(original_type, str): + return validated + try: + return original_type(validated) + except (TypeError, ValueError): + # If the type cannot be reconstructed, just return the validated list + return validated + + @staticmethod + def _serialize(v: Iterable[_T]) -> list[_T]: + """Always serialize as a list so Pydantic's JSON encoder is happy.""" + if isinstance(v, list): + return v + return list(v) + + +EagerIterable: TypeAlias = Annotated[Iterable[_T], _EagerIterable] + + def _construct_field(value: object, field: FieldInfo, key: str) -> object: if value is None: return field_get_default(field) diff --git a/tests/test_models.py b/tests/test_models.py index aac33d2e4..15b921693 100644 --- a/tests/test_models.py +++ b/tests/test_models.py @@ -1,7 +1,8 @@ import json -from typing import TYPE_CHECKING, Any, Dict, List, Union, Optional, cast +from typing import TYPE_CHECKING, Any, Dict, List, Union, Iterable, Optional, cast from datetime import datetime, timezone -from typing_extensions import Literal, Annotated, TypeAliasType +from collections import deque +from typing_extensions import Literal, Annotated, TypedDict, TypeAliasType import pytest import pydantic @@ -9,7 +10,7 @@ from runloop_api_client._utils import PropertyInfo from runloop_api_client._compat import PYDANTIC_V1, parse_obj, model_dump, model_json -from runloop_api_client._models import DISCRIMINATOR_CACHE, BaseModel, construct_type +from runloop_api_client._models import DISCRIMINATOR_CACHE, BaseModel, EagerIterable, construct_type class BasicModel(BaseModel): @@ -961,3 +962,56 @@ def __getattr__(self, attr: str) -> Item: ... assert model.a.prop == 1 assert isinstance(model.a, Item) assert model.other == "foo" + + +# NOTE: Workaround for Pydantic Iterable behavior. +# Iterable fields are replaced with a ValidatorIterator and may be consumed +# during serialization, which can cause subsequent dumps to return empty data. +# See: https://github.com/pydantic/pydantic/issues/9541 +@pytest.mark.parametrize( + "data, expected_validated", + [ + ([1, 2, 3], [1, 2, 3]), + ((1, 2, 3), (1, 2, 3)), + (set([1, 2, 3]), set([1, 2, 3])), + (iter([1, 2, 3]), [1, 2, 3]), + ([], []), + ((x for x in [1, 2, 3]), [1, 2, 3]), + (map(lambda x: x, [1, 2, 3]), [1, 2, 3]), + (frozenset([1, 2, 3]), frozenset([1, 2, 3])), + (deque([1, 2, 3]), deque([1, 2, 3])), + ], + ids=["list", "tuple", "set", "iterator", "empty", "generator", "map", "frozenset", "deque"], +) +@pytest.mark.skipif(PYDANTIC_V1, reason="this is only supported in pydantic v2") +def test_iterable_construction(data: Iterable[int], expected_validated: Iterable[int]) -> None: + class TypeWithIterable(TypedDict): + items: EagerIterable[int] + + class Model(BaseModel): + data: TypeWithIterable + + m = Model.model_validate({"data": {"items": data}}) + assert m.data["items"] == expected_validated + + # Verify repeated dumps don't lose data (the original bug) + assert m.model_dump()["data"]["items"] == list(expected_validated) + assert m.model_dump()["data"]["items"] == list(expected_validated) + + +@pytest.mark.skipif(PYDANTIC_V1, reason="this is only supported in pydantic v2") +def test_iterable_construction_str_falls_back_to_list() -> None: + # str is iterable (over chars), but str(list_of_chars) produces the list's repr + # rather than reconstructing a string from items. We special-case str to fall + # back to list instead of attempting reconstruction. + class TypeWithIterable(TypedDict): + items: EagerIterable[str] + + class Model(BaseModel): + data: TypeWithIterable + + m = Model.model_validate({"data": {"items": "hello"}}) + + # falls back to list of chars rather than calling str(["h", "e", "l", "l", "o"]) + assert m.data["items"] == ["h", "e", "l", "l", "o"] + assert m.model_dump()["data"]["items"] == ["h", "e", "l", "l", "o"] From 7ceb2bf09c3241a27892fbab2272d63ef76b1a8a Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 12 May 2026 19:28:10 +0000 Subject: [PATCH 5/6] fix: update types for pty control, use int instead of str (#9235) --- .stats.yml | 6 +++--- api.md | 2 +- src/runloop_api_client/resources/pty.py | 8 ++++---- src/runloop_api_client/types/pty_connect_params.py | 4 ++-- tests/api_resources/test_pty.py | 8 ++++---- 5 files changed, 14 insertions(+), 14 deletions(-) diff --git a/.stats.yml b/.stats.yml index e3de40026..75a9a5bb0 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,4 +1,4 @@ configured_endpoints: 119 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/runloop-ai/runloop-40b78fbce4172c1fdab1559718cc9a7ba6b47402ee0bcb8dbefa582448958384.yml -openapi_spec_hash: 78673375a4e58f7b4cea847ce2686b0e -config_hash: 07d725fff578f22e8cb52e3c588f24c6 +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/runloop-ai/runloop-6ec03cfc156036a0758aebc523b469f3007de431312c536c434efe795e1892e7.yml +openapi_spec_hash: 092761a0209e0950cfd8f262a981adb1 +config_hash: 06faf3176c48bf2b258730ce50809f0f diff --git a/api.md b/api.md index 22db26e92..2f48b034e 100644 --- a/api.md +++ b/api.md @@ -285,7 +285,7 @@ Methods: Types: ```python -from runloop_api_client.types import PtyConnectView, PtyControlParameters, PtyControlResultView +from runloop_api_client.types import PtyConnectView, PtyControlParams, PtyControlResultView ``` Methods: diff --git a/src/runloop_api_client/resources/pty.py b/src/runloop_api_client/resources/pty.py index 927d9604e..dc1a837b5 100644 --- a/src/runloop_api_client/resources/pty.py +++ b/src/runloop_api_client/resources/pty.py @@ -48,8 +48,8 @@ def connect( self, session_name: str, *, - cols: str | Omit = omit, - rows: str | Omit = omit, + cols: int | Omit = omit, + rows: int | Omit = omit, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -221,8 +221,8 @@ async def connect( self, session_name: str, *, - cols: str | Omit = omit, - rows: str | Omit = omit, + cols: int | Omit = omit, + rows: int | Omit = omit, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, diff --git a/src/runloop_api_client/types/pty_connect_params.py b/src/runloop_api_client/types/pty_connect_params.py index 5df1af0ed..17ba2a32b 100644 --- a/src/runloop_api_client/types/pty_connect_params.py +++ b/src/runloop_api_client/types/pty_connect_params.py @@ -8,14 +8,14 @@ class PtyConnectParams(TypedDict, total=False): - cols: str + cols: int """Optional initial terminal width in character cells (1..=1000). Defaults to 80 when omitted. Applied only if both cols and rows are provided; otherwise ignored. """ - rows: str + rows: int """Optional initial terminal height in character cells (1..=1000). Defaults to 24 when omitted. Applied only if both cols and rows are provided; diff --git a/tests/api_resources/test_pty.py b/tests/api_resources/test_pty.py index 411bab45b..76829ceb1 100644 --- a/tests/api_resources/test_pty.py +++ b/tests/api_resources/test_pty.py @@ -28,8 +28,8 @@ def test_method_connect(self, client: Runloop) -> None: def test_method_connect_with_all_params(self, client: Runloop) -> None: pty = client.pty.connect( session_name="session_name", - cols="cols", - rows="rows", + cols=0, + rows=0, ) assert_matches_type(PtyConnectView, pty, path=["response"]) @@ -130,8 +130,8 @@ async def test_method_connect(self, async_client: AsyncRunloop) -> None: async def test_method_connect_with_all_params(self, async_client: AsyncRunloop) -> None: pty = await async_client.pty.connect( session_name="session_name", - cols="cols", - rows="rows", + cols=0, + rows=0, ) assert_matches_type(PtyConnectView, pty, path=["response"]) From f5894dd3b66e295e96f3d7c6c7fe21672a1ef874 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Wed, 13 May 2026 18:23:25 +0000 Subject: [PATCH 6/6] release: 1.21.0 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 16 ++++++++++++++++ pyproject.toml | 2 +- src/runloop_api_client/_version.py | 2 +- 4 files changed, 19 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 3b5fc24d7..ba231b076 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.20.3" + ".": "1.21.0" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 19de81d83..07431324c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,21 @@ # Changelog +## 1.21.0 (2026-05-13) + +Full Changelog: [v1.20.3...v1.21.0](https://github.com/runloopai/api-client-python/compare/v1.20.3...v1.21.0) + +### Features + +* **internal/types:** support eagerly validating pydantic iterators ([f089d05](https://github.com/runloopai/api-client-python/commit/f089d05c5e00c2ba980d0afdea79ed026242a174)) +* **metadata:** add object metadata viewing, discovery, and validation ([#9124](https://github.com/runloopai/api-client-python/issues/9124)) ([ba0b5dc](https://github.com/runloopai/api-client-python/commit/ba0b5dc873a47073c453b168fe4d966754cccc0e)) + + +### Bug Fixes + +* **client:** add missing f-string prefix in file type error message ([930b1e2](https://github.com/runloopai/api-client-python/commit/930b1e2d169a291415007f2897fec5a410ecf993)) +* update openapi.stainless.yaml for PTY server methods ([#9218](https://github.com/runloopai/api-client-python/issues/9218)) ([ac1cb22](https://github.com/runloopai/api-client-python/commit/ac1cb2264b8e39da8aa65d8fdcd4595bce55def6)) +* update types for pty control, use int instead of str ([#9235](https://github.com/runloopai/api-client-python/issues/9235)) ([7ceb2bf](https://github.com/runloopai/api-client-python/commit/7ceb2bf09c3241a27892fbab2272d63ef76b1a8a)) + ## 1.20.3 (2026-05-08) Full Changelog: [v1.20.2...v1.20.3](https://github.com/runloopai/api-client-python/compare/v1.20.2...v1.20.3) diff --git a/pyproject.toml b/pyproject.toml index 1178d263e..c1f57fbd6 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "runloop_api_client" -version = "1.20.3" +version = "1.21.0" description = "The official Python library for the runloop API" dynamic = ["readme"] license = "MIT" diff --git a/src/runloop_api_client/_version.py b/src/runloop_api_client/_version.py index 62ae17d31..e94914292 100644 --- a/src/runloop_api_client/_version.py +++ b/src/runloop_api_client/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "runloop_api_client" -__version__ = "1.20.3" # x-release-please-version +__version__ = "1.21.0" # x-release-please-version