Skip to content

armgit / E2B

Public Imported from GitHub
0

Open-source, secure environment with real-world tools for enterprise-grade agents.

feat(python-sdk): migrate envd RPC to the official connectrpc client (#1558)

Mish Ushakov00253c39cc6c
diff --git a/.changeset/python-connectrpc-migration.md b/.changeset/python-connectrpc-migration.md
new file mode 100644
index 000000000..338cf2019
--- /dev/null
+++ b/.changeset/python-connectrpc-migration.md
@@ -0,0 +1,55 @@
+---
+"@e2b/python-sdk": minor
+---
+
+Migrate the sandbox RPC layer (commands, PTY, filesystem watch) from the
+vendored `e2b_connect` client to the official Connect RPC client for Python
+([`connectrpc`](https://pypi.org/project/connectrpc/)), whose HTTP transport
+is `pyqwest` (Rust reqwest/hyper), and switch the envd protobuf messages from
+Google's `protobuf` runtime to Buf's
+[`protobuf-py`](https://pypi.org/project/protobuf-py/).
+
+Closing a command or watch stream early now sends `RST_STREAM` to the server,
+so abandoned streams no longer leak on the shared HTTP/2 connection, and peer
+resets surface as typed errors instead of ambiguous EOFs. The REST API and
+file upload/download keep using `httpx`.
+
+Notes:
+
+- The SDK no longer depends on the `protobuf` package, removing a common
+ source of dependency conflicts with other libraries that pin it.
+- The `e2b_connect` module is no longer shipped with the package. Code that
+ imported it directly should use `connectrpc` (`ConnectError`, `Code`)
+ instead; SDK exception types (`SandboxException`, `TimeoutException`, ...)
+ are unchanged.
+- The generated `e2b.envd.*.*_pb2` modules were replaced by `protobuf-py`
+ equivalents (`e2b.envd.process.process_pb`,
+ `e2b.envd.filesystem.filesystem_pb`) with a different message API.
+- Connection retries for sandbox RPC calls (`E2B_CONNECTION_RETRIES`, default
+ 3) now retry only failures establishing the connection — before the request
+ could have reached envd — with exponential backoff. Unary RPCs are no
+ longer replayed when the connection drops mid-request, which could
+ re-execute a delivered call (e.g. re-send process input); such drops
+ surface as errors immediately, the way they always did for streaming calls.
+- The `proxy` option applies to sandbox RPC calls the same way it does to the
+ REST API and file transfer requests. URL strings, `httpx.URL`, and
+ `httpx.Proxy` values keep working (credentials in the URL or in
+ `httpx.Proxy(auth=...)`); `httpx.Proxy` custom headers and `ssl_context`
+ are not supported for RPC calls and raise `InvalidArgumentException`.
+- `CommandResult.error` (and `CommandHandle.error`) is now `None` when a
+ command finishes without an error, matching the declared `Optional[str]`
+ type and the JS SDK's `error?: string`. It used to be `""` on success —
+ code comparing `result.error == ""` or treating it as always-`str` should
+ check for `None`/falsiness instead.
+- For async streaming calls (`commands.run`/`connect`, PTY,
+ `files.watch_dir`), `request_timeout` now bounds opening the stream — the
+ wait until envd confirms with a start event, matching the JS SDK's
+ `requestTimeoutMs` — and raises `TimeoutException` when exceeded. The
+ running stream is bounded by the command/watch `timeout` (as before). In
+ the sync SDK there is no way to interrupt the blocking wait, so
+ `request_timeout` is not applied to opening the stream — both stream setup
+ and the running stream are bounded by `timeout` (unlimited when `0`).
+- `E2B_MAX_CONNECTIONS` no longer applies to sandbox RPC traffic: the new
+ transport bounds only idle connections per host (`E2B_KEEPALIVE_EXPIRY`,
+ `E2B_MAX_KEEPALIVE_CONNECTIONS`), not the total number of open
+ connections. It still applies to the REST API and file transfers.
diff --git a/.github/workflows/codegen_image_cache.yml b/.github/workflows/codegen_image_cache.yml
index 83e358443..23d108888 100644
--- a/.github/workflows/codegen_image_cache.yml
+++ b/.github/workflows/codegen_image_cache.yml
@@ -8,7 +8,6 @@ on:
branches: [main]
paths:
- 'codegen.Dockerfile'
- - 'packages/connect-python/**'
- '.github/workflows/codegen_image_cache.yml'
workflow_dispatch:
diff --git a/.github/workflows/sdk_tests.yml b/.github/workflows/sdk_tests.yml
index 5e191fa91..f342f5836 100644
--- a/.github/workflows/sdk_tests.yml
+++ b/.github/workflows/sdk_tests.yml
@@ -46,7 +46,6 @@ jobs:
- *shared
- '.github/workflows/python_sdk_tests.yml'
- 'packages/python-sdk/**/!(*.md)'
- - 'packages/connect-python/**/!(*.md)'
cli:
- *shared
- '.github/workflows/cli_tests.yml'
diff --git a/codegen.Dockerfile b/codegen.Dockerfile
index 72e6bea51..a0edd23c6 100644
--- a/codegen.Dockerfile
+++ b/codegen.Dockerfile
@@ -5,36 +5,23 @@ RUN go install github.com/bufbuild/buf/cmd/[email protected] && \
go install google.golang.org/protobuf/cmd/[email protected] && \
go install connectrpc.com/connect/cmd/[email protected]
-# Install our custom protoc plugin, connect-python
-COPY ./packages/connect-python /packages/connect-python
-RUN cd /packages/connect-python && make bin/protoc-gen-connect-python
-
FROM python:3.10
# Set working directory
WORKDIR /workspace
-ENV PROTOC_VERSION=26.1
-RUN ARCH=$(uname -m) && \
- case "$ARCH" in \
- x86_64) PROTOC_ARCH="x86_64" ;; \
- arm64|aarch64) PROTOC_ARCH="aarch_64" ;; \
- *) echo "Unsupported architecture: $ARCH" && exit 1 ;; \
- esac && \
- curl -LO https://github.com/protocolbuffers/protobuf/releases/download/v${PROTOC_VERSION}/protoc-${PROTOC_VERSION}-linux-${PROTOC_ARCH}.zip && \
- unzip -o protoc-${PROTOC_VERSION}-linux-${PROTOC_ARCH}.zip -d /usr/local && \
- rm protoc-${PROTOC_VERSION}-linux-${PROTOC_ARCH}.zip
-
# Copy installed Go deps from previous build step
COPY --from=0 /go /go
-# Add Go binary to PATH
+# Add Go binary to PATH
ENV PATH="/go/bin:${PATH}"
# Install Python deps (e2b-openapi-python-client is patched version to fix issue with explode)
# https://github.com/openapi-generators/openapi-python-client/pull/1296
-RUN pip install black==26.3.1 pyyaml==6.0.2 e2b-openapi-python-client==0.26.2 datamodel-code-generator==0.34.0
+# protoc-gen-py generates the Python envd protobuf-py messages and
+# protoc-gen-connectrpc the Connect stubs.
+RUN pip install black==26.3.1 pyyaml==6.0.2 e2b-openapi-python-client==0.26.2 datamodel-code-generator==0.34.0 protoc-gen-connectrpc==0.11.1 protoc-gen-py==0.1.1
# Install Node.js (pinned to match .tool-versions)
ENV NODE_VERSION=22.18.0
diff --git a/packages/connect-python/.gitignore b/packages/connect-python/.gitignore
deleted file mode 100644
index ba077a403..000000000
--- a/packages/connect-python/.gitignore
+++ /dev/null
@@ -1 +0,0 @@
-bin
diff --git a/packages/connect-python/LICENSE b/packages/connect-python/LICENSE
deleted file mode 100644
index 8b55ffaf2..000000000
--- a/packages/connect-python/LICENSE
+++ /dev/null
@@ -1,201 +0,0 @@
- Apache License
- Version 2.0, January 2004
- http://www.apache.org/licenses/
-
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
-
- 1. Definitions.
-
- "License" shall mean the terms and conditions for use, reproduction,
- and distribution as defined by Sections 1 through 9 of this document.
-
- "Licensor" shall mean the copyright owner or entity authorized by
- the copyright owner that is granting the License.
-
- "Legal Entity" shall mean the union of the acting entity and all
- other entities that control, are controlled by, or are under common
- control with that entity. For the purposes of this definition,
- "control" means (i) the power, direct or indirect, to cause the
- direction or management of such entity, whether by contract or
- otherwise, or (ii) ownership of fifty percent (50%) or more of the
- outstanding shares, or (iii) beneficial ownership of such entity.
-
- "You" (or "Your") shall mean an individual or Legal Entity
- exercising permissions granted by this License.
-
- "Source" form shall mean the preferred form for making modifications,
- including but not limited to software source code, documentation
- source, and configuration files.
-
- "Object" form shall mean any form resulting from mechanical
- transformation or translation of a Source form, including but
- not limited to compiled object code, generated documentation,
- and conversions to other media types.
-
- "Work" shall mean the work of authorship, whether in Source or
- Object form, made available under the License, as indicated by a
- copyright notice that is included in or attached to the work
- (an example is provided in the Appendix below).
-
- "Derivative Works" shall mean any work, whether in Source or Object
- form, that is based on (or derived from) the Work and for which the
- editorial revisions, annotations, elaborations, or other modifications
- represent, as a whole, an original work of authorship. For the purposes
- of this License, Derivative Works shall not include works that remain
- separable from, or merely link (or bind by name) to the interfaces of,
- the Work and Derivative Works thereof.
-
- "Contribution" shall mean any work of authorship, including
- the original version of the Work and any modifications or additions
- to that Work or Derivative Works thereof, that is intentionally
- submitted to Licensor for inclusion in the Work by the copyright owner
- or by an individual or Legal Entity authorized to submit on behalf of
- the copyright owner. For the purposes of this definition, "submitted"
- means any form of electronic, verbal, or written communication sent
- to the Licensor or its representatives, including but not limited to
- communication on electronic mailing lists, source code control systems,
- and issue tracking systems that are managed by, or on behalf of, the
- Licensor for the purpose of discussing and improving the Work, but
- excluding communication that is conspicuously marked or otherwise
- designated in writing by the copyright owner as "Not a Contribution."
-
- "Contributor" shall mean Licensor and any individual or Legal Entity
- on behalf of whom a Contribution has been received by Licensor and
- subsequently incorporated within the Work.
-
- 2. Grant of Copyright License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- copyright license to reproduce, prepare Derivative Works of,
- publicly display, publicly perform, sublicense, and distribute the
- Work and such Derivative Works in Source or Object form.
-
- 3. Grant of Patent License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- (except as stated in this section) patent license to make, have made,
- use, offer to sell, sell, import, and otherwise transfer the Work,
- where such license applies only to those patent claims licensable
- by such Contributor that are necessarily infringed by their
- Contribution(s) alone or by combination of their Contribution(s)
- with the Work to which such Contribution(s) was submitted. If You
- institute patent litigation against any entity (including a
- cross-claim or counterclaim in a lawsuit) alleging that the Work
- or a Contribution incorporated within the Work constitutes direct
- or contributory patent infringement, then any patent licenses
- granted to You under this License for that Work shall terminate
- as of the date such litigation is filed.
-
- 4. Redistribution. You may reproduce and distribute copies of the
- Work or Derivative Works thereof in any medium, with or without
- modifications, and in Source or Object form, provided that You
- meet the following conditions:
-
- (a) You must give any other recipients of the Work or
- Derivative Works a copy of this License; and
-
- (b) You must cause any modified files to carry prominent notices
- stating that You changed the files; and
-
- (c) You must retain, in the Source form of any Derivative Works
- that You distribute, all copyright, patent, trademark, and
- attribution notices from the Source form of the Work,
- excluding those notices that do not pertain to any part of
- the Derivative Works; and
-
- (d) If the Work includes a "NOTICE" text file as part of its
- distribution, then any Derivative Works that You distribute must
- include a readable copy of the attribution notices contained
- within such NOTICE file, excluding those notices that do not
- pertain to any part of the Derivative Works, in at least one
- of the following places: within a NOTICE text file distributed
- as part of the Derivative Works; within the Source form or
- documentation, if provided along with the Derivative Works; or,
- within a display generated by the Derivative Works, if and
- wherever such third-party notices normally appear. The contents
- of the NOTICE file are for informational purposes only and
- do not modify the License. You may add Your own attribution
- notices within Derivative Works that You distribute, alongside
- or as an addendum to the NOTICE text from the Work, provided
- that such additional attribution notices cannot be construed
- as modifying the License.
-
- You may add Your own copyright statement to Your modifications and
- may provide additional or different license terms and conditions
- for use, reproduction, or distribution of Your modifications, or
- for any such Derivative Works as a whole, provided Your use,
- reproduction, and distribution of the Work otherwise complies with
- the conditions stated in this License.
-
- 5. Submission of Contributions. Unless You explicitly state otherwise,
- any Contribution intentionally submitted for inclusion in the Work
- by You to the Licensor shall be under the terms and conditions of
- this License, without any additional terms or conditions.
- Notwithstanding the above, nothing herein shall supersede or modify
- the terms of any separate license agreement you may have executed
- with Licensor regarding such Contributions.
-
- 6. Trademarks. This License does not grant permission to use the trade
- names, trademarks, service marks, or product names of the Licensor,
- except as required for reasonable and customary use in describing the
- origin of the Work and reproducing the content of the NOTICE file.
-
- 7. Disclaimer of Warranty. Unless required by applicable law or
- agreed to in writing, Licensor provides the Work (and each
- Contributor provides its Contributions) on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- implied, including, without limitation, any warranties or conditions
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
- PARTICULAR PURPOSE. You are solely responsible for determining the
- appropriateness of using or redistributing the Work and assume any
- risks associated with Your exercise of permissions under this License.
-
- 8. Limitation of Liability. In no event and under no legal theory,
- whether in tort (including negligence), contract, or otherwise,
- unless required by applicable law (such as deliberate and grossly
- negligent acts) or agreed to in writing, shall any Contributor be
- liable to You for damages, including any direct, indirect, special,
- incidental, or consequential damages of any character arising as a
- result of this License or out of the use or inability to use the
- Work (including but not limited to damages for loss of goodwill,
- work stoppage, computer failure or malfunction, or any and all
- other commercial damages or losses), even if such Contributor
- has been advised of the possibility of such damages.
-
- 9. Accepting Warranty or Additional Liability. While redistributing
- the Work or Derivative Works thereof, You may choose to offer,
- and charge a fee for, acceptance of support, warranty, indemnity,
- or other liability obligations and/or rights consistent with this
- License. However, in accepting such obligations, You may act only
- on Your own behalf and on Your sole responsibility, not on behalf
- of any other Contributor, and only if You agree to indemnify,
- defend, and hold each Contributor harmless for any liability
- incurred by, or claims asserted against, such Contributor by reason
- of your accepting any such warranty or additional liability.
-
- END OF TERMS AND CONDITIONS
-
- APPENDIX: How to apply the Apache License to your work.
-
- To apply the Apache License to your work, attach the following
- boilerplate notice, with the fields enclosed by brackets "[]"
- replaced with your own identifying information. (Don't include
- the brackets!) The text should be enclosed in the appropriate
- comment syntax for the file format. We also recommend that a
- file or class name and description of purpose be included on the
- same "printed page" as the copyright notice for easier
- identification within third-party archives.
-
- Copyright 2021-2024 The Connect Authors
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
diff --git a/packages/connect-python/Makefile b/packages/connect-python/Makefile
deleted file mode 100644
index 678288629..000000000
--- a/packages/connect-python/Makefile
+++ /dev/null
@@ -1,29 +0,0 @@
-PY = python -m
-
-plugin = protoc-gen-connect-python
-
-dev:
- $(PY) pip install -r requirements-dev.txt
-
-fmt:
- $(PY) ruff format src
-
-lint:
- $(PY) ruff check src
-
-clean:
- rm -f bin/protoc-gen-connect-python
- rm -rf dist
-
-upload: clean
- $(PY) build
- $(PY) twine upload --repository=connect-python dist/*
-
-
-bin/$(plugin): $(wildcard cmd/$(plugin)/*.go) pyproject.toml Makefile
- go install -ldflags "-w -s" ./cmd/$(plugin)
-
-.PHONY: dev fmt lint upload clean build
-
-build:
- make bin/protoc-gen-connect-python
diff --git a/packages/connect-python/README.md b/packages/connect-python/README.md
deleted file mode 100644
index b84611dd5..000000000
--- a/packages/connect-python/README.md
+++ /dev/null
@@ -1,7 +0,0 @@
-🚧 Currently pending [an open RFC to be moved into the Connect RPC org](https://github.com/connectrpc/connectrpc.com/pull/71). Please show support. 🚧
-
----
-
-# connect-python
-
-Python client implementation for the [Connect](https://connect.build) RPC protocol.
diff --git a/packages/connect-python/cmd/protoc-gen-connect-python/main.go b/packages/connect-python/cmd/protoc-gen-connect-python/main.go
deleted file mode 100644
index aa92ce62c..000000000
--- a/packages/connect-python/cmd/protoc-gen-connect-python/main.go
+++ /dev/null
@@ -1,367 +0,0 @@
-package main
-
-import (
- "fmt"
- "io"
- "os"
- "path/filepath"
- "regexp"
- "sort"
- "strings"
-
- log "golang.org/x/exp/slog"
- "google.golang.org/protobuf/proto"
- descriptor "google.golang.org/protobuf/types/descriptorpb"
- "google.golang.org/protobuf/types/pluginpb"
-)
-
-const pluginVersion = "0.1.0.dev2"
-
-func init() {
- ll := log.New(log.NewTextHandler(os.Stderr, &log.HandlerOptions{
- Level: log.LevelDebug,
- ReplaceAttr: func(groups []string, a log.Attr) log.Attr {
- if a.Key == log.TimeKey && len(groups) == 0 {
- return log.Attr{}
- }
- return a
- },
- }))
- log.SetDefault(ll.With(log.Int("pid", os.Getpid())))
-}
-
-func main() {
- if len(os.Args) == 2 && os.Args[1] == "--version" {
- fmt.Fprintln(os.Stdout, pluginVersion)
- os.Exit(0)
- }
-
- f := func(plugin *Plugin) error {
- for _, f := range plugin.filesToGenerate {
- generate(plugin, f)
- }
- return nil
- }
- if err := run(f); err != nil {
- fmt.Fprintf(os.Stderr, "%s: %v\n", filepath.Base(os.Args[0]), err)
- os.Exit(1)
- }
-}
-
-func run(f func(*Plugin) error) error {
- in, err := io.ReadAll(os.Stdin)
- if err != nil {
- return err
- }
- req := &pluginpb.CodeGeneratorRequest{}
- if err := proto.Unmarshal(in, req); err != nil {
- return err
- }
- gen, err := newPlugin(req)
- if err != nil {
- return err
- }
- if err := f(gen); err != nil {
- gen.Error(err)
- }
- resp := gen.Response()
- out, err := proto.Marshal(resp)
- if err != nil {
- return err
- }
- _, err = os.Stdout.Write(out)
- return err
-}
-
-func newPlugin(req *pluginpb.CodeGeneratorRequest) (*Plugin, error) {
- gen := &Plugin{
- request: req,
- filesByPackage: make(map[string]*descriptor.FileDescriptorProto),
- filesByPath: make(map[string]*descriptor.FileDescriptorProto),
- messagesByType: make(map[string]*descriptor.DescriptorProto),
- }
-
- for _, f := range gen.request.ProtoFile {
- name := f.GetName()
-
- pkg := f.GetPackage()
- log.Debug("ProtoFile",
- log.String("name", name),
- log.String("pkg", pkg),
- )
- // if _, ok := gen.filesByPackage[pkg]; ok {
- // return nil, fmt.Errorf("duplicate package: %q", name)
- // }
- gen.filesByPackage[pkg] = f
- if _, ok := gen.filesByPath[name]; ok {
- return nil, fmt.Errorf("duplicate file name: %q", name)
- }
- gen.filesByPath[name] = f
- for _, msg := range f.GetMessageType() {
- msgKey := f.GetPackage() + "." + msg.GetName()
- if _, ok := gen.messagesByType[msgKey]; ok {
- return nil, fmt.Errorf("duplicate message: %q", msgKey)
- }
- gen.messagesByType[msgKey] = msg
- log.Debug("MessageType",
- log.String("name", msgKey),
- )
- }
- gen.files = append(gen.files, f)
- }
-
- for _, name := range req.FileToGenerate {
- if f, ok := gen.filesByPath[name]; ok {
- log.Debug("FileToGenerate",
- log.String("name", name),
- log.Any("deps", f.Dependency),
- log.Int("services", len(f.Service)),
- )
- if len(f.Service) > 0 {
- gen.filesToGenerate = append(gen.filesToGenerate, f)
- }
- } else {
- return nil, fmt.Errorf("missing file: %q", name)
- }
- }
-
- return gen, nil
-}
-
-type Plugin struct {
- request *pluginpb.CodeGeneratorRequest
-
- files []*descriptor.FileDescriptorProto
- filesByPackage map[string]*descriptor.FileDescriptorProto
- filesByPath map[string]*descriptor.FileDescriptorProto
- messagesByType map[string]*descriptor.DescriptorProto
- filesToGenerate []*descriptor.FileDescriptorProto
-
- generatedFiles []*pluginpb.CodeGeneratorResponse_File
-
- err error
-}
-
-func (gen *Plugin) Response() *pluginpb.CodeGeneratorResponse {
- resp := &pluginpb.CodeGeneratorResponse{}
- if gen.err != nil {
- resp.Error = Ptr(gen.err.Error())
- return resp
- }
- resp.File = gen.generatedFiles
- return resp
-}
-
-func (gen *Plugin) Error(err error) {
- if gen.err == nil {
- gen.err = err
- }
-}
-
-func Ptr[T any](v T) *T {
- return &v
-}
-
-func print(buf *strings.Builder, tpl string, args ...interface{}) {
- buf.WriteString(fmt.Sprintf(tpl, args...))
- buf.WriteByte('\n')
-}
-
-func getPackage(path string) string {
- return strings.ReplaceAll(filepath.Dir(path), "/", ".")
-}
-
-func getModule(path string) string {
- path = filepath.Base(path)
- ext := filepath.Ext(path)
- return strings.TrimSuffix(path, ext)
-}
-
-func getProtoModule(path string) string {
- return getModule(path) + "_pb2"
-}
-
-func getConnectModule(path string) string {
- return getModule(path) + "_connect"
-}
-
-func getProtoModuleAlias(path string) string {
- path = getPackage(path) + "." + getProtoModule(path)
- path = strings.ReplaceAll(path, "_", "__")
- path = strings.ReplaceAll(path, ".", "_dot_")
- return path
-}
-
-func getServiceName(svc *descriptor.ServiceDescriptorProto) string {
- return svc.GetName() + "Name"
-}
-
-func getServiceClient(svc *descriptor.ServiceDescriptorProto) string {
- return svc.GetName() + "Client"
-}
-
-func getServiceBasePath(file *descriptor.FileDescriptorProto, svc *descriptor.ServiceDescriptorProto) string {
- return file.GetPackage() + "." + svc.GetName()
-}
-
-func getMethodProperty(m *descriptor.MethodDescriptorProto) string {
- return "_" + toSnakeCase(m.GetName())
-}
-
-func getMethodType(m *descriptor.MethodDescriptorProto) string {
- switch {
- case m.GetClientStreaming() && m.GetServerStreaming():
- return "bidi_stream"
- case m.GetClientStreaming():
- return "client_stream"
- case m.GetServerStreaming():
- return "server_stream"
- default:
- return "unary"
- }
-}
-
-func splitPackageType(path string) (string, string) {
- lastDot := strings.LastIndexByte(path, '.')
- return path[:lastDot], path[lastDot+1:]
-}
-
-func resolveMessageFromMethod(gen *Plugin, m *descriptor.MethodDescriptorProto) (string, string) {
- fullyQualifiedName := m.GetOutputType()[1:] // strip prefixed "."
- pkgName, msgName := splitPackageType(fullyQualifiedName)
- filename := gen.filesByPackage[pkgName].GetName()
- return filename, msgName
-}
-
-func resolveInputFromMethod(gen *Plugin, m *descriptor.MethodDescriptorProto) (string, string) {
- fullyQualifiedName := m.GetInputType()[1:] // strip prefixed "."
- pkgName, msgName := splitPackageType(fullyQualifiedName)
- filename := gen.filesByPackage[pkgName].GetName()
- return filename, msgName
-}
-
-func getResponseType(gen *Plugin, m *descriptor.MethodDescriptorProto) string {
- filename, msgName := resolveMessageFromMethod(gen, m)
-
- log.Debug("ResponseType",
- log.String("msg", msgName),
- log.String("import", filename),
- log.String("alias", getProtoModuleAlias(filename)),
- )
- return getProtoModuleAlias(filename) + "." + msgName
-}
-
-func getRequestType(gen *Plugin, m *descriptor.MethodDescriptorProto) string {
- filename, msgName := resolveInputFromMethod(gen, m)
-
- log.Debug("RequestType",
- log.String("msg", msgName),
- log.String("import", filename),
- log.String("alias", getProtoModuleAlias(filename)),
- )
- return getProtoModuleAlias(filename) + "." + msgName
-}
-
-var (
- matchFirstCap = regexp.MustCompile("(.)([A-Z][a-z]+)")
- matchAllCap = regexp.MustCompile("([a-z0-9])([A-Z])")
-)
-
-func toSnakeCase(str string) string {
- snake := matchFirstCap.ReplaceAllString(str, "${1}_${2}")
- snake = matchAllCap.ReplaceAllString(snake, "${1}_${2}")
- return strings.ToLower(snake)
-}
-
-func generate(gen *Plugin, file *descriptor.FileDescriptorProto) {
- filename := file.GetName()
-
- dir := filepath.Dir(filename)
- pkgName := getPackage(filename)
- modName := getModule(filename)
-
- log.Debug("Generate",
- log.String("name", filename),
- log.String("pkg", pkgName),
- log.String("mod", modName),
- )
-
- b := new(strings.Builder)
-
- depsUniq := make(map[string]struct{})
- for _, svc := range file.Service {
- for _, method := range svc.Method {
- filename, _ := resolveMessageFromMethod(gen, method)
- depsUniq[filename] = struct{}{}
- }
- }
-
- deps := make([]string, 0, len(depsUniq))
- for dep := range depsUniq {
- deps = append(deps, dep)
- }
- sort.Strings(deps)
-
- print(b, "# Code generated by protoc-gen-connect-python %s, DO NOT EDIT.", pluginVersion)
-
- print(b, "from typing import Any, Generator, Coroutine, AsyncGenerator, Optional")
- print(b, "from httpcore import ConnectionPool, AsyncConnectionPool")
- print(b, "")
-
- print(b, "import e2b_connect as connect")
- if len(deps) > 0 {
- print(b, "")
- for _, dep := range deps {
- print(b, "from %s import %s as %s", getPackage(dep), getProtoModule(dep), getProtoModuleAlias(dep))
- }
- }
- print(b, "")
-
- for _, svc := range file.Service {
- print(b, `%s = "%s"`, getServiceName(svc), getServiceBasePath(file, svc))
- }
-
- for _, svc := range file.Service {
- print(b, "")
- print(b, "")
- print(b, `class %s:`, getServiceClient(svc))
- print(b, " def __init__(self, base_url: str, *, pool: Optional[ConnectionPool] = None, async_pool: Optional[AsyncConnectionPool] = None, compressor=None, json=False, **opts):")
- if len(svc.Method) == 0 {
- print(b, " pass")
- continue
- }
- for _, method := range svc.Method {
- print(b, " self.%s = connect.Client(", getMethodProperty(method))
- print(b, " pool=pool,")
- print(b, " async_pool=async_pool,")
- print(b, ` url=f"{base_url}/{%s}/%s",`, getServiceName(svc), method.GetName())
- print(b, ` response_type=%s,`, getResponseType(gen, method))
- print(b, ` compressor=compressor,`)
- print(b, ` json=json,`)
- print(b, ` **opts`)
- print(b, " )")
- }
- for _, method := range svc.Method {
- print(b, "")
-
- if method.GetServerStreaming() {
- print(b, " def %s(self, req: %s , **opts) -> Generator[%s, Any, None]:", toSnakeCase(method.GetName()), getRequestType(gen, method), getResponseType(gen, method))
- print(b, " return self.%s.call_%s(req, **opts)", getMethodProperty(method), getMethodType(method))
- print(b, "")
- print(b, " def a%s(self, req: %s , **opts) -> AsyncGenerator[%s, Any]:", toSnakeCase(method.GetName()), getRequestType(gen, method), getResponseType(gen, method))
- print(b, " return self.%s.acall_%s(req, **opts)", getMethodProperty(method), getMethodType(method))
- } else {
- print(b, " def %s(self, req: %s, **opts) -> %s:", toSnakeCase(method.GetName()), getRequestType(gen, method), getResponseType(gen, method))
- print(b, " return self.%s.call_%s(req, **opts)", getMethodProperty(method), getMethodType(method))
- print(b, "")
- print(b, " def a%s(self, req: %s, **opts) -> Coroutine[Any, Any, %s]:", toSnakeCase(method.GetName()), getRequestType(gen, method), getResponseType(gen, method))
- print(b, " return self.%s.acall_%s(req, **opts)", getMethodProperty(method), getMethodType(method))
- }
- }
- }
-
- gen.generatedFiles = append(gen.generatedFiles, &pluginpb.CodeGeneratorResponse_File{
- Name: Ptr(filepath.Join(dir, getConnectModule(filename)+".py")),
- Content: Ptr(b.String()),
- })
-}
diff --git a/packages/connect-python/go.mod b/packages/connect-python/go.mod
deleted file mode 100644
index b08c67793..000000000
--- a/packages/connect-python/go.mod
+++ /dev/null
@@ -1,8 +0,0 @@
-module go.withmatt.com/connect-python
-
-go 1.22
-
-require (
- golang.org/x/exp v0.0.0-20240416160154-fe59bbe5cc7f
- google.golang.org/protobuf v1.33.0
-)
diff --git a/packages/connect-python/go.sum b/packages/connect-python/go.sum
deleted file mode 100644
index 5e5f35203..000000000
--- a/packages/connect-python/go.sum
+++ /dev/null
@@ -1,6 +0,0 @@
-github.com/google/go-cmp v0.5.8 h1:e6P7q2lk1O+qJJb4BtCQXlK8vWEO8V1ZeuEdJNOqZyg=
-github.com/google/go-cmp v0.5.8/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
-golang.org/x/exp v0.0.0-20240416160154-fe59bbe5cc7f h1:99ci1mjWVBWwJiEKYY6jWa4d2nTQVIEhZIptnrVb1XY=
-golang.org/x/exp v0.0.0-20240416160154-fe59bbe5cc7f/go.mod h1:/lliqkxwWAhPjf5oSOIJup2XcqJaw8RGS6k3TGEc7GI=
-google.golang.org/protobuf v1.33.0 h1:uNO2rsAINq/JlFpSdYEKIZ0uKD/R9cpdv0T+yoGwGmI=
-google.golang.org/protobuf v1.33.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=
diff --git a/packages/connect-python/pyproject.toml b/packages/connect-python/pyproject.toml
deleted file mode 100644
index 5e10909b1..000000000
--- a/packages/connect-python/pyproject.toml
+++ /dev/null
@@ -1,35 +0,0 @@
-[project]
-name = "connect-python"
-version = "0.1.0.dev2"
-authors = [{ email = "[email protected]" }]
-description = "Client implementation for the Connect RPC protocol"
-readme = "README.md"
-requires-python = ">=3.12"
-classifiers = [
- "Programming Language :: Python :: 3",
- "License :: OSI Approved :: Apache Software License",
- "Operating System :: OS Independent",
-]
-dependencies = [
- "protobuf",
- "httpcore",
-]
-
-[tool.hatch.build]
-include = [
- "/src",
-]
-
-[tool.hatch.build.targets.wheel]
-packages = ["src/connect"]
-
-[project.urls]
-"Homepage" = "https://github.com/mattrobenolt/connect-python"
-"Bug Tracker" = "https://github.com/mattrobenolt/connect-python/issues"
-
-[project.optional-dependencies]
-http2 = ["h2"]
-
-[build-system]
-requires = ["hatchling"]
-build-backend = "hatchling.build"
diff --git a/packages/connect-python/requirements-dev.txt b/packages/connect-python/requirements-dev.txt
deleted file mode 100644
index 3b7a0daee..000000000
--- a/packages/connect-python/requirements-dev.txt
+++ /dev/null
@@ -1,5 +0,0 @@
--e .[http2]
-
-ruff
-build
-twine
diff --git a/packages/python-sdk/Makefile b/packages/python-sdk/Makefile
index 3fc3e72bf..1cc9f0701 100644
--- a/packages/python-sdk/Makefile
+++ b/packages/python-sdk/Makefile
@@ -15,11 +15,9 @@ generate-volume-api:
rm -rf e2b/volume/api
ruff format .
+# Requires `buf` and the codegen dependency group (`make init`), which
+# provides the `protoc-gen-connectrpc` plugin.
generate-envd:
- if [ ! -f "/go/bin/protoc-gen-connect-python" ]; then \
- $(MAKE) -C $(ROOT_DIR)/packages/connect-python build; \
- fi
-
cd $(ROOT_DIR)/spec/envd && pwd && buf generate --template buf-python.gen.yaml
./scripts/fix-python-pb.sh
diff --git a/packages/python-sdk/e2b/api/__init__.py b/packages/python-sdk/e2b/api/__init__.py
index c0867c41e..15ef836bf 100644
--- a/packages/python-sdk/e2b/api/__init__.py
+++ b/packages/python-sdk/e2b/api/__init__.py
@@ -63,12 +63,12 @@ def make_async_logging_event_hooks(log: Optional[logging.Logger]) -> dict:
limits = Limits(
- max_keepalive_connections=int(os.getenv("E2B_MAX_KEEPALIVE_CONNECTIONS", "20")),
- max_connections=int(os.getenv("E2B_MAX_CONNECTIONS", "2000")),
- keepalive_expiry=int(os.getenv("E2B_KEEPALIVE_EXPIRY", "300")),
+ max_keepalive_connections=int(os.getenv("E2B_MAX_KEEPALIVE_CONNECTIONS") or "20"),
+ max_connections=int(os.getenv("E2B_MAX_CONNECTIONS") or "2000"),
+ keepalive_expiry=int(os.getenv("E2B_KEEPALIVE_EXPIRY") or "300"),
)
-connection_retries = int(os.getenv("E2B_CONNECTION_RETRIES", "3"))
+connection_retries = int(os.getenv("E2B_CONNECTION_RETRIES") or "3")
@dataclass
diff --git a/packages/python-sdk/e2b/envd/__init__.py b/packages/python-sdk/e2b/envd/__init__.py
new file mode 100644
index 000000000..9d48db4f9
--- /dev/null
+++ b/packages/python-sdk/e2b/envd/__init__.py
@@ -0,0 +1 @@
+from __future__ import annotations
diff --git a/packages/python-sdk/e2b/envd/client_async/__init__.py b/packages/python-sdk/e2b/envd/client_async/__init__.py
new file mode 100644
index 000000000..b1597ea20
--- /dev/null
+++ b/packages/python-sdk/e2b/envd/client_async/__init__.py
@@ -0,0 +1,177 @@
+"""Async envd RPC clients: shared pyqwest transports and client factory."""
+
+import asyncio
+import threading
+from typing import (
+ Any,
+ AsyncGenerator,
+ AsyncIterator,
+ Callable,
+ Optional,
+ TypeVar,
+ Union,
+ cast,
+)
+
+from connectrpc.code import Code
+from connectrpc.errors import ConnectError
+from pyqwest import Client, HTTPTransport, Request, Response, Transport
+from pyqwest.middleware.retry import RetryTransport
+
+from e2b.api import connection_retries
+from e2b.connection_config import ConnectionConfig
+from e2b.envd.client_shared import (
+ ENVD_JSON_CODEC,
+ ENVD_RPC_COMPRESSION,
+ plain_http_error,
+ pool_idle_timeout,
+ pool_max_idle_per_host,
+ proxy_to_url,
+ should_retry_connection,
+)
+from e2b.envd.interceptors import build_interceptors
+from e2b.exceptions import TimeoutException
+
+RES = TypeVar("RES")
+TClient = TypeVar("TClient")
+
+_transport_lock = threading.Lock()
+# One transport (= one connection pool) per proxy; None is the direct pool.
+_transports: dict[Optional[str], "PlainHTTPErrorTransport"] = {}
+
+
+class PlainHTTPErrorTransport:
+ """Raise plain (non-Connect-encoded) HTTP error responses — e.g. an edge
+ proxy answering for envd — as ``ConnectError``; see
+ :func:`e2b.envd.client_shared.plain_http_error` for the mapping and
+ rationale."""
+
+ def __init__(self, inner: Transport):
+ self._inner = inner
+
+ async def execute(self, request: Request) -> Response:
+ response = await self._inner.execute(request)
+ if response.status < 400:
+ return response
+ body = bytearray()
+ async for chunk in response.content:
+ body.extend(chunk)
+ data = bytes(body)
+ error = plain_http_error(
+ response.status, response.headers.get("content-type", ""), data
+ )
+ if error is None:
+ # Valid Connect error: hand back to connectrpc, body restored.
+ return Response(
+ status=response.status,
+ headers=response.headers,
+ content=data,
+ )
+ raise error
+
+
+class ConnectionRetryTransport(RetryTransport):
+ """Retry only failures establishing the connection; see
+ :func:`e2b.envd.client_shared.should_retry_connection` for the policy
+ rationale."""
+
+ def should_retry_response(
+ self, request: Request, response: Union[Response, Exception]
+ ) -> bool:
+ return should_retry_connection(response)
+
+
+def get_transport(proxy_url: Optional[str]) -> "PlainHTTPErrorTransport":
+ with _transport_lock:
+ transport = _transports.get(proxy_url)
+ if transport is None:
+ # connectrpc arms the per-call deadline around the transport, so
+ # retry backoff counts against the request timeout. The plain-
+ # error normalization sits outside the retries so it converts
+ # the settled response once.
+ transport = PlainHTTPErrorTransport(
+ ConnectionRetryTransport(
+ HTTPTransport(
+ tls_include_system_certs=True,
+ proxy=proxy_url,
+ pool_idle_timeout=pool_idle_timeout,
+ pool_max_idle_per_host=pool_max_idle_per_host,
+ ),
+ max_retries=connection_retries,
+ )
+ )
+ _transports[proxy_url] = transport
+ return transport
+
+
+def create_rpc_client(
+ client_cls: Callable[..., TClient],
+ base_url: str,
+ config: ConnectionConfig,
+) -> TClient:
+ """Build a generated async connectrpc client (e.g. ``ProcessClient``)
+ wired with the shared pyqwest transport (which retries failed connects,
+ see :class:`ConnectionRetryTransport`), the envd JSON codec, and the
+ SDK's default-header and logging interceptors. Compression is disabled
+ (see ``ENVD_RPC_COMPRESSION``).
+ """
+ http_client = Client(get_transport(proxy_to_url(config.proxy)))
+ return client_cls(
+ base_url,
+ codec=ENVD_JSON_CODEC,
+ interceptors=build_interceptors(config, base_url),
+ http_client=http_client,
+ **ENVD_RPC_COMPRESSION,
+ )
+
+
+def as_stream(events: AsyncIterator[RES]) -> AsyncGenerator[RES, Any]:
+ """The generated stubs type server streams as ``AsyncIterator``, but
+ connectrpc returns real async generators — the SDK relies on ``aclose()``
+ to cancel a stream early (hyper then resets the HTTP/2 stream)."""
+ return cast("AsyncGenerator[RES, Any]", events)
+
+
+def _request_timeout_exception(request_timeout: float) -> TimeoutException:
+ return TimeoutException(
+ f"Request timed out: the stream didn't open within 'request_timeout' "
+ f"({request_timeout} seconds). You can pass the request timeout value "
+ "as an option when making the request. Use '0' to disable it."
+ )
+
+
+async def first_event(
+ events: AsyncGenerator[RES, Any], request_timeout: Optional[float]
+) -> RES:
+ """Wait for the event that opens a server stream (start/connect/watch),
+ bounding the wait — connection setup, request write, and envd sending the
+ event — by ``request_timeout``. This mirrors the JS SDK's
+ ``requestTimeoutMs`` timer on streaming calls, which is disarmed once the
+ stream is open; the rest of the stream is bounded only by the call's
+ ``timeout_ms``. On timeout the caller's ``aclose()`` finds the stream
+ already torn down (hyper resets the HTTP/2 stream when the cancellation
+ unwinds connectrpc's response scope).
+ """
+ if not request_timeout:
+ return await events.__anext__()
+ try:
+ return await asyncio.wait_for(events.__anext__(), request_timeout)
+ except (asyncio.TimeoutError, TimeoutError) as e:
+ raise _request_timeout_exception(request_timeout) from e
+ except ConnectError as e:
+ # wait_for's expiry cancels the __anext__ task, but connectrpc
+ # converts the delivered CancelledError into ConnectError(CANCELED)
+ # before wait_for can turn it into TimeoutError. A caller cancelling
+ # the surrounding task surfaces identically, so tell the two apart by
+ # the pending-cancellation count: wait_for uncancels its own expiry,
+ # an external cancel stays pending. (Python 3.10 has no cancelling(),
+ # but its wait_for re-raises external cancels before this point, so
+ # reaching here without it means the timer expired.)
+ cancelling = getattr(asyncio.current_task(), "cancelling", None)
+ if (
+ e.code is Code.CANCELED
+ and isinstance(e.__cause__, asyncio.CancelledError)
+ and (cancelling is None or cancelling() == 0)
+ ):
+ raise _request_timeout_exception(request_timeout) from e
+ raise
diff --git a/packages/python-sdk/e2b/envd/client_shared.py b/packages/python-sdk/e2b/envd/client_shared.py
new file mode 100644
index 000000000..3ed99a9ec
--- /dev/null
+++ b/packages/python-sdk/e2b/envd/client_shared.py
@@ -0,0 +1,205 @@
+"""envd RPC client plumbing shared by the sync and async flavors.
+
+The envd RPC clients (process, filesystem) run on `connectrpc`, whose HTTP
+layer is `pyqwest` (Rust reqwest/hyper). This is a separate stack from the
+`httpx` transports in `e2b.api`, which keep serving the REST API and the
+multipart file transfer endpoints. Unlike the previous httpcore-based
+transport, hyper sends RST_STREAM when a server stream is closed early, so
+abandoned command/watch streams don't leak on the shared HTTP/2 connection.
+
+The flavor-specific transports and client factories live in
+:mod:`e2b.envd.client_sync` and :mod:`e2b.envd.client_async`, mirroring the
+`e2b.api.client_sync`/`client_async` layout. This module exists because
+`e2b/envd/__init__.py`, the natural home by that analogy, is owned by the
+protobuf codegen (`make generate-envd`).
+"""
+
+import json
+import os
+from typing import Optional, TypedDict, TypeVar
+
+import httpx
+from connectrpc.code import Code
+from connectrpc.errors import ConnectError
+from protobuf import Message
+
+from e2b.exceptions import InvalidArgumentException
+
+# Mirror the httpx pool tuning in `e2b.api.limits` with pyqwest's equivalents.
+# `pool_max_idle_per_host` is per host rather than httpx's global idle cap,
+# which suits envd traffic — each sandbox is its own host.
+pool_idle_timeout = float(os.getenv("E2B_KEEPALIVE_EXPIRY") or "300")
+pool_max_idle_per_host = int(os.getenv("E2B_MAX_KEEPALIVE_CONNECTIONS") or "20")
+
+_MESSAGE = TypeVar("_MESSAGE", bound=Message)
+
+
+class _ProtoJSONCodec:
+ """JSON codec matching the JS SDK's `useBinaryFormat: false`.
+
+ connectrpc's default codec is binary protobuf, which would silently
+ change the wire format the SDK has always used; its built-in JSON codec
+ fails hard on unknown fields, which would break an older SDK against a
+ newer envd that added response fields. This codec is the built-in JSON
+ codec plus `ignore_unknown_fields`.
+ """
+
+ def name(self) -> str:
+ return "json"
+
+ def encode(self, message: Message) -> bytes:
+ return message.to_json().encode("utf-8")
+
+ def decode(self, data, message_class: type[_MESSAGE]) -> _MESSAGE:
+ try:
+ return message_class.from_json(data, ignore_unknown_fields=True)
+ except Exception as e:
+ # A raw error would hit connectrpc's catch-all and become
+ # ConnectError(UNAVAILABLE) — a misleading sandbox-timeout in
+ # rpc.py. Codec-raised ConnectErrors pass through unchanged;
+ # INTERNAL maps to a plain SandboxException.
+ raise ConnectError(
+ Code.INTERNAL,
+ f"envd sent a response that could not be decoded as "
+ f"{message_class.__name__}: {e}",
+ ) from e
+
+
+ENVD_JSON_CODEC = _ProtoJSONCodec()
+
+# How the vendored client mapped plain (non-Connect-encoded) HTTP error
+# responses — e.g. an edge proxy answering for envd — to codes (#806).
+# Statuses without an entry map to UNKNOWN, as before.
+PLAIN_HTTP_ERROR_CODES: dict[int, Code] = {
+ 400: Code.INVALID_ARGUMENT,
+ 401: Code.UNAUTHENTICATED,
+ 403: Code.PERMISSION_DENIED,
+ 404: Code.NOT_FOUND,
+ 409: Code.ALREADY_EXISTS,
+ 413: Code.RESOURCE_EXHAUSTED,
+ 429: Code.RESOURCE_EXHAUSTED,
+ 499: Code.CANCELED,
+ 500: Code.INTERNAL,
+ 501: Code.UNIMPLEMENTED,
+ 502: Code.UNAVAILABLE,
+ 503: Code.UNAVAILABLE,
+ 504: Code.DEADLINE_EXCEEDED,
+ 505: Code.UNIMPLEMENTED,
+}
+
+
+def plain_http_error(
+ status: int, content_type: str, body: bytes
+) -> Optional[ConnectError]:
+ """The ``ConnectError`` for a plain (non-Connect-encoded) HTTP error
+ response, or ``None`` for a valid Connect error (per spec, a JSON body
+ with a string ``code``) that connectrpc must parse itself. Anything else
+ is a proxy or gateway answering instead of envd, mapped like the vendored
+ client: an int ``code`` counts as the HTTP status, everything else falls
+ back to the response status. Called only for error statuses, with the
+ body already drained.
+
+ The flavor ``PlainHTTPErrorTransport``s raise this before connectrpc
+ collapses plain error responses into Connect-spec codes with synthesized
+ reason phrases (404 → UNIMPLEMENTED "Not Found"): ``kill``/``exists``/
+ ``make_dir`` branch on NOT_FOUND/ALREADY_EXISTS and user code relies on
+ RateLimitException to back off. connectrpc re-raises a ``ConnectError``
+ from the transport unchanged — the path its own protocol errors take.
+ A gateway's ``{"code": 429}`` or plain-JSON error page gets the vendored
+ mapping too. Becomes unnecessary once connectrpc preserves the status on
+ the errors it builds (https://github.com/connectrpc/connect-py/issues/306).
+ """
+ message: Optional[str] = None
+ if content_type.split(";", 1)[0].strip().lower() == "application/json":
+ try:
+ parsed = json.loads(body)
+ except ValueError:
+ parsed = None
+ code_value = parsed.get("code") if isinstance(parsed, dict) else None
+ if isinstance(code_value, str):
+ try:
+ Code(code_value)
+ except ValueError:
+ pass
+ else:
+ return None
+ if isinstance(code_value, int) and not isinstance(code_value, bool):
+ status = code_value
+ if isinstance(parsed, dict) and isinstance(parsed.get("message"), str):
+ message = parsed["message"]
+ code = PLAIN_HTTP_ERROR_CODES.get(status, Code.UNKNOWN)
+ return ConnectError(
+ code, message or body.decode("utf-8", "replace") or f"HTTP {status}"
+ )
+
+
+def should_retry_connection(response: object) -> bool:
+ """Whether a transport result is a retryable connection-establishment
+ failure — the shared policy of the flavor ``ConnectionRetryTransport``s.
+
+ pyqwest raises the builtin ``ConnectionError`` only before the request
+ was written, so retrying exactly these failures can never replay a
+ request envd may have received — which could re-run a command or
+ re-deliver events — for unary and streaming RPCs alike. Anything later
+ (``WriteError``/``ReadError``/``StreamError``, error responses) surfaces
+ to the caller; the retry middleware's default policy would otherwise also
+ retry I/O errors and 429/5xx responses for idempotent methods. This
+ replaces httpcore's transport ``retries`` from the previous stack and
+ deliberately drops the vendored client's retry on connections dropped
+ mid-request, which could re-execute a delivered unary RPC like
+ ``SendInput``.
+ """
+ return isinstance(response, ConnectionError)
+
+
+class _RPCCompression(TypedDict):
+ send_compression: None
+ accept_compression: "tuple[()]"
+
+
+# Compression is disabled in both directions, matching every previous stack:
+# the vendored client never compressed and the JS SDK's connect-web transport
+# has no compression support — connectrpc's default would silently start
+# gzipping every request body. envd RPC payloads are tiny JSON (the large
+# file-transfer payloads go over httpx with their own gzip option), and
+# envd's handling of compressed streaming bodies is unresolved. The empty
+# accept resolves to identity-only, so responses stay uncompressed too.
+ENVD_RPC_COMPRESSION: _RPCCompression = {
+ "send_compression": None,
+ "accept_compression": (),
+}
+
+
+def proxy_to_url(proxy: object) -> Optional[str]:
+ """Narrow the ``proxy`` connection option to the proxy URL string pyqwest
+ transports take (scheme http, https, socks5, or socks5h, credentials in
+ the URL userinfo). ``httpx.URL`` and ``httpx.Proxy`` — which the REST
+ client accepts and the vendored envd client used to — are converted when
+ they reduce to such a URL; ``httpx.Proxy`` extras that don't (custom
+ headers, an ssl_context) are rejected rather than silently dropped.
+ """
+ if proxy is None:
+ return None
+ if isinstance(proxy, str):
+ return proxy
+ if isinstance(proxy, httpx.URL):
+ return str(proxy)
+ if isinstance(proxy, httpx.Proxy):
+ if proxy.headers:
+ raise InvalidArgumentException(
+ "Sandbox RPC calls don't support httpx.Proxy custom headers; "
+ "pass credentials in the proxy URL instead, "
+ 'e.g. proxy="http://user:pass@localhost:8030"'
+ )
+ if proxy.ssl_context is not None:
+ raise InvalidArgumentException(
+ "Sandbox RPC calls don't support httpx.Proxy ssl_context"
+ )
+ url = proxy.url
+ if proxy.auth is not None:
+ url = url.copy_with(username=proxy.auth[0], password=proxy.auth[1])
+ return str(url)
+ raise InvalidArgumentException(
+ "Sandbox RPC calls support only URL-string proxies, "
+ 'e.g. proxy="http://user:pass@localhost:8030"'
+ )
diff --git a/packages/python-sdk/e2b/envd/client_sync/__init__.py b/packages/python-sdk/e2b/envd/client_sync/__init__.py
new file mode 100644
index 000000000..7ceaf980e
--- /dev/null
+++ b/packages/python-sdk/e2b/envd/client_sync/__init__.py
@@ -0,0 +1,126 @@
+"""Sync envd RPC clients: shared pyqwest transports and client factory."""
+
+import threading
+from typing import Any, Callable, Generator, Iterator, Optional, TypeVar, Union, cast
+
+from pyqwest import (
+ SyncClient,
+ SyncHTTPTransport,
+ SyncRequest,
+ SyncResponse,
+ SyncTransport,
+)
+from pyqwest.middleware.retry import SyncRetryTransport
+
+from e2b.api import connection_retries
+from e2b.connection_config import ConnectionConfig
+from e2b.envd.client_shared import (
+ ENVD_JSON_CODEC,
+ ENVD_RPC_COMPRESSION,
+ plain_http_error,
+ pool_idle_timeout,
+ pool_max_idle_per_host,
+ proxy_to_url,
+ should_retry_connection,
+)
+from e2b.envd.interceptors import build_interceptors
+
+RES = TypeVar("RES")
+TClient = TypeVar("TClient")
+
+_transport_lock = threading.Lock()
+# One transport (= one connection pool) per proxy; None is the direct pool.
+_transports: dict[Optional[str], "PlainHTTPErrorTransport"] = {}
+
+
+class PlainHTTPErrorTransport:
+ """Raise plain (non-Connect-encoded) HTTP error responses — e.g. an edge
+ proxy answering for envd — as ``ConnectError``; see
+ :func:`e2b.envd.client_shared.plain_http_error` for the mapping and
+ rationale."""
+
+ def __init__(self, inner: SyncTransport):
+ self._inner = inner
+
+ def execute_sync(self, request: SyncRequest) -> SyncResponse:
+ response = self._inner.execute_sync(request)
+ if response.status < 400:
+ return response
+ body = bytearray()
+ for chunk in response.content:
+ body.extend(chunk)
+ data = bytes(body)
+ error = plain_http_error(
+ response.status, response.headers.get("content-type", ""), data
+ )
+ if error is None:
+ # Valid Connect error: hand back to connectrpc, body restored.
+ return SyncResponse(
+ status=response.status,
+ headers=response.headers,
+ content=data,
+ )
+ raise error
+
+
+class ConnectionRetryTransport(SyncRetryTransport):
+ """Retry only failures establishing the connection; see
+ :func:`e2b.envd.client_shared.should_retry_connection` for the policy
+ rationale."""
+
+ def should_retry_response(
+ self, request: SyncRequest, response: Union[SyncResponse, Exception]
+ ) -> bool:
+ return should_retry_connection(response)
+
+
+def get_transport(proxy_url: Optional[str]) -> "PlainHTTPErrorTransport":
+ with _transport_lock:
+ transport = _transports.get(proxy_url)
+ if transport is None:
+ # connectrpc arms the per-call deadline around the transport, so
+ # retry backoff counts against the request timeout. The plain-
+ # error normalization sits outside the retries so it converts
+ # the settled response once.
+ transport = PlainHTTPErrorTransport(
+ ConnectionRetryTransport(
+ SyncHTTPTransport(
+ tls_include_system_certs=True,
+ proxy=proxy_url,
+ pool_idle_timeout=pool_idle_timeout,
+ pool_max_idle_per_host=pool_max_idle_per_host,
+ ),
+ max_retries=connection_retries,
+ )
+ )
+ _transports[proxy_url] = transport
+ return transport
+
+
+def create_rpc_client(
+ client_cls: Callable[..., TClient],
+ base_url: str,
+ config: ConnectionConfig,
+) -> TClient:
+ """Build a generated sync connectrpc client (e.g. ``ProcessClientSync``)
+ wired with the shared pyqwest transport (which retries failed connects,
+ see :class:`ConnectionRetryTransport`), the envd JSON codec, and the
+ SDK's default-header and logging interceptors. Compression is disabled
+ (see ``ENVD_RPC_COMPRESSION``). The client is stateless per call and its
+ transport is process-global, so one instance serves all threads.
+ """
+ http_client = SyncClient(get_transport(proxy_to_url(config.proxy)))
+ return client_cls(
+ base_url,
+ codec=ENVD_JSON_CODEC,
+ interceptors=build_interceptors(config, base_url),
+ http_client=http_client,
+ **ENVD_RPC_COMPRESSION,
+ )
+
+
+def as_stream(events: Iterator[RES]) -> Generator[RES, Any, None]:
+ """The generated stubs type server streams as ``Iterator``, but connectrpc
+ returns real generators — the SDK relies on ``close()`` to cancel a stream
+ early (hyper then resets the HTTP/2 stream)."""
+ return cast("Generator[RES, Any, None]", events)
diff --git a/packages/python-sdk/e2b/envd/filesystem/__init__.py b/packages/python-sdk/e2b/envd/filesystem/__init__.py
new file mode 100644
index 000000000..9d48db4f9
--- /dev/null
+++ b/packages/python-sdk/e2b/envd/filesystem/__init__.py
@@ -0,0 +1 @@
+from __future__ import annotations
diff --git a/packages/python-sdk/e2b/envd/filesystem/filesystem_connect.py b/packages/python-sdk/e2b/envd/filesystem/filesystem_connect.py
index e995585e8..3fe1d827e 100644
--- a/packages/python-sdk/e2b/envd/filesystem/filesystem_connect.py
+++ b/packages/python-sdk/e2b/envd/filesystem/filesystem_connect.py
@@ -1,193 +1,668 @@
-# Code generated by protoc-gen-connect-python 0.1.0.dev2, DO NOT EDIT.
-from typing import Any, Generator, Coroutine, AsyncGenerator, Optional
-from httpcore import ConnectionPool, AsyncConnectionPool
+# Generated from filesystem/filesystem.proto. DO NOT EDIT.
+# Generated by protoc-gen-connectrpc-py v0.11.1 with parameter "".
+# ruff: noqa: PGH004
+# ruff: noqa
+# fmt: off
-import e2b_connect as connect
+from __future__ import annotations
-from e2b.envd.filesystem import filesystem_pb2 as filesystem_dot_filesystem__pb2
+from typing import Protocol, TYPE_CHECKING
-FilesystemName = "filesystem.Filesystem"
+from connectrpc.client import ConnectClient, ConnectClientSync
+from connectrpc.code import Code
+from connectrpc.errors import ConnectError
+from connectrpc.method import IdempotencyLevel, MethodInfo
+from connectrpc.server import ConnectASGIApplication, ConnectWSGIApplication, Endpoint, EndpointSync
+from .filesystem_pb import CreateWatcherRequest, CreateWatcherResponse, GetWatcherEventsRequest, GetWatcherEventsResponse, ListDirRequest, ListDirResponse, MakeDirRequest, MakeDirResponse, MoveRequest, MoveResponse, RemoveRequest, RemoveResponse, RemoveWatcherRequest, RemoveWatcherResponse, StatRequest, StatResponse, WatchDirRequest, WatchDirResponse
-class FilesystemClient:
+if TYPE_CHECKING:
+ from collections.abc import AsyncGenerator, AsyncIterator, Iterable, Iterator, Mapping
+
+ from connectrpc.codec import Codec
+ from connectrpc.compression import Compression
+ from connectrpc.interceptor import Interceptor, InterceptorSync
+ from connectrpc.request import Headers, RequestContext
+
+
+class Filesystem(Protocol):
+ async def stat(self, request: StatRequest, ctx: RequestContext[StatRequest, StatResponse]) -> StatResponse:
+ raise ConnectError(Code.UNIMPLEMENTED, 'Not implemented')
+
+ async def make_dir(self, request: MakeDirRequest, ctx: RequestContext[MakeDirRequest, MakeDirResponse]) -> MakeDirResponse:
+ raise ConnectError(Code.UNIMPLEMENTED, 'Not implemented')
+
+ async def move(self, request: MoveRequest, ctx: RequestContext[MoveRequest, MoveResponse]) -> MoveResponse:
+ raise ConnectError(Code.UNIMPLEMENTED, 'Not implemented')
+
+ async def list_dir(self, request: ListDirRequest, ctx: RequestContext[ListDirRequest, ListDirResponse]) -> ListDirResponse:
+ raise ConnectError(Code.UNIMPLEMENTED, 'Not implemented')
+
+ async def remove(self, request: RemoveRequest, ctx: RequestContext[RemoveRequest, RemoveResponse]) -> RemoveResponse:
+ raise ConnectError(Code.UNIMPLEMENTED, 'Not implemented')
+
+ def watch_dir(self, request: WatchDirRequest, ctx: RequestContext[WatchDirRequest, WatchDirResponse]) -> AsyncIterator[WatchDirResponse]:
+ raise ConnectError(Code.UNIMPLEMENTED, 'Not implemented')
+
+ async def create_watcher(self, request: CreateWatcherRequest, ctx: RequestContext[CreateWatcherRequest, CreateWatcherResponse]) -> CreateWatcherResponse:
+ raise ConnectError(Code.UNIMPLEMENTED, 'Not implemented')
+
+ async def get_watcher_events(self, request: GetWatcherEventsRequest, ctx: RequestContext[GetWatcherEventsRequest, GetWatcherEventsResponse]) -> GetWatcherEventsResponse:
+ raise ConnectError(Code.UNIMPLEMENTED, 'Not implemented')
+
+ async def remove_watcher(self, request: RemoveWatcherRequest, ctx: RequestContext[RemoveWatcherRequest, RemoveWatcherResponse]) -> RemoveWatcherResponse:
+ raise ConnectError(Code.UNIMPLEMENTED, 'Not implemented')
+
+
+class FilesystemASGIApplication(ConnectASGIApplication[Filesystem]):
def __init__(
self,
- base_url: str,
- *,
- pool: Optional[ConnectionPool] = None,
- async_pool: Optional[AsyncConnectionPool] = None,
- compressor=None,
- json=False,
- **opts,
- ):
- self._stat = connect.Client(
- pool=pool,
- async_pool=async_pool,
- url=f"{base_url}/{FilesystemName}/Stat",
- response_type=filesystem_dot_filesystem__pb2.StatResponse,
- compressor=compressor,
- json=json,
- **opts,
- )
- self._make_dir = connect.Client(
- pool=pool,
- async_pool=async_pool,
- url=f"{base_url}/{FilesystemName}/MakeDir",
- response_type=filesystem_dot_filesystem__pb2.MakeDirResponse,
- compressor=compressor,
- json=json,
- **opts,
- )
- self._move = connect.Client(
- pool=pool,
- async_pool=async_pool,
- url=f"{base_url}/{FilesystemName}/Move",
- response_type=filesystem_dot_filesystem__pb2.MoveResponse,
- compressor=compressor,
- json=json,
- **opts,
- )
- self._list_dir = connect.Client(
- pool=pool,
- async_pool=async_pool,
- url=f"{base_url}/{FilesystemName}/ListDir",
- response_type=filesystem_dot_filesystem__pb2.ListDirResponse,
- compressor=compressor,
- json=json,
- **opts,
- )
- self._remove = connect.Client(
- pool=pool,
- async_pool=async_pool,
- url=f"{base_url}/{FilesystemName}/Remove",
- response_type=filesystem_dot_filesystem__pb2.RemoveResponse,
- compressor=compressor,
- json=json,
- **opts,
- )
- self._watch_dir = connect.Client(
- pool=pool,
- async_pool=async_pool,
- url=f"{base_url}/{FilesystemName}/WatchDir",
- response_type=filesystem_dot_filesystem__pb2.WatchDirResponse,
- compressor=compressor,
- json=json,
- **opts,
- )
- self._create_watcher = connect.Client(
- pool=pool,
- async_pool=async_pool,
- url=f"{base_url}/{FilesystemName}/CreateWatcher",
- response_type=filesystem_dot_filesystem__pb2.CreateWatcherResponse,
- compressor=compressor,
- json=json,
- **opts,
- )
- self._get_watcher_events = connect.Client(
- pool=pool,
- async_pool=async_pool,
- url=f"{base_url}/{FilesystemName}/GetWatcherEvents",
- response_type=filesystem_dot_filesystem__pb2.GetWatcherEventsResponse,
- compressor=compressor,
- json=json,
- **opts,
- )
- self._remove_watcher = connect.Client(
- pool=pool,
- async_pool=async_pool,
- url=f"{base_url}/{FilesystemName}/RemoveWatcher",
- response_type=filesystem_dot_filesystem__pb2.RemoveWatcherResponse,
- compressor=compressor,
- json=json,
- **opts,
+ service: Filesystem | AsyncGenerator[Filesystem],
+ *,
+ interceptors: Iterable[Interceptor] = (),
+ read_max_bytes: int | None = None,
+ compressions: Iterable[Compression] | None = None,
+ codecs: Iterable[Codec] | None = None,
+ ) -> None:
+ super().__init__(
+ service=service,
+ endpoints=lambda svc: {
+ "/filesystem.Filesystem/Stat": Endpoint.unary(
+ method=MethodInfo(
+ name="Stat",
+ service_name="filesystem.Filesystem",
+ input=StatRequest,
+ output=StatResponse,
+ idempotency_level=IdempotencyLevel.UNKNOWN,
+ ),
+ function=svc.stat,
+ ),
+ "/filesystem.Filesystem/MakeDir": Endpoint.unary(
+ method=MethodInfo(
+ name="MakeDir",
+ service_name="filesystem.Filesystem",
+ input=MakeDirRequest,
+ output=MakeDirResponse,
+ idempotency_level=IdempotencyLevel.UNKNOWN,
+ ),
+ function=svc.make_dir,
+ ),
+ "/filesystem.Filesystem/Move": Endpoint.unary(
+ method=MethodInfo(
+ name="Move",
+ service_name="filesystem.Filesystem",
+ input=MoveRequest,
+ output=MoveResponse,
+ idempotency_level=IdempotencyLevel.UNKNOWN,
+ ),
+ function=svc.move,
+ ),
+ "/filesystem.Filesystem/ListDir": Endpoint.unary(
+ method=MethodInfo(
+ name="ListDir",
+ service_name="filesystem.Filesystem",
+ input=ListDirRequest,
+ output=ListDirResponse,
+ idempotency_level=IdempotencyLevel.UNKNOWN,
+ ),
+ function=svc.list_dir,
+ ),
+ "/filesystem.Filesystem/Remove": Endpoint.unary(
+ method=MethodInfo(
+ name="Remove",
+ service_name="filesystem.Filesystem",
+ input=RemoveRequest,
+ output=RemoveResponse,
+ idempotency_level=IdempotencyLevel.UNKNOWN,
+ ),
+ function=svc.remove,
+ ),
+ "/filesystem.Filesystem/WatchDir": Endpoint.server_stream(
+ method=MethodInfo(
+ name="WatchDir",
+ service_name="filesystem.Filesystem",
+ input=WatchDirRequest,
+ output=WatchDirResponse,
+ idempotency_level=IdempotencyLevel.UNKNOWN,
+ ),
+ function=svc.watch_dir,
+ ),
+ "/filesystem.Filesystem/CreateWatcher": Endpoint.unary(
+ method=MethodInfo(
+ name="CreateWatcher",
+ service_name="filesystem.Filesystem",
+ input=CreateWatcherRequest,
+ output=CreateWatcherResponse,
+ idempotency_level=IdempotencyLevel.UNKNOWN,
+ ),
+ function=svc.create_watcher,
+ ),
+ "/filesystem.Filesystem/GetWatcherEvents": Endpoint.unary(
+ method=MethodInfo(
+ name="GetWatcherEvents",
+ service_name="filesystem.Filesystem",
+ input=GetWatcherEventsRequest,
+ output=GetWatcherEventsResponse,
+ idempotency_level=IdempotencyLevel.UNKNOWN,
+ ),
+ function=svc.get_watcher_events,
+ ),
+ "/filesystem.Filesystem/RemoveWatcher": Endpoint.unary(
+ method=MethodInfo(
+ name="RemoveWatcher",
+ service_name="filesystem.Filesystem",
+ input=RemoveWatcherRequest,
+ output=RemoveWatcherResponse,
+ idempotency_level=IdempotencyLevel.UNKNOWN,
+ ),
+ function=svc.remove_watcher,
+ ),
+ },
+ interceptors=interceptors,
+ read_max_bytes=read_max_bytes,
+ compressions=compressions,
+ codecs=codecs,
)
- def stat(
- self, req: filesystem_dot_filesystem__pb2.StatRequest, **opts
- ) -> filesystem_dot_filesystem__pb2.StatResponse:
- return self._stat.call_unary(req, **opts)
+ @property
+ def path(self) -> str:
+ """Returns the URL path to mount the application to when serving multiple applications."""
+ return "/filesystem.Filesystem"
- def astat(
- self, req: filesystem_dot_filesystem__pb2.StatRequest, **opts
- ) -> Coroutine[Any, Any, filesystem_dot_filesystem__pb2.StatResponse]:
- return self._stat.acall_unary(req, **opts)
- def make_dir(
- self, req: filesystem_dot_filesystem__pb2.MakeDirRequest, **opts
- ) -> filesystem_dot_filesystem__pb2.MakeDirResponse:
- return self._make_dir.call_unary(req, **opts)
+class FilesystemClient(ConnectClient):
+ async def stat(
+ self,
+ request: StatRequest,
+ *,
+ headers: Headers | Mapping[str, str] | None = None,
+ timeout_ms: int | None = None,
+ ) -> StatResponse:
+ return await self.execute_unary(
+ request=request,
+ method=MethodInfo(
+ name="Stat",
+ service_name="filesystem.Filesystem",
+ input=StatRequest,
+ output=StatResponse,
+ idempotency_level=IdempotencyLevel.UNKNOWN,
+ ),
+ headers=headers,
+ timeout_ms=timeout_ms,
+ )
- def amake_dir(
- self, req: filesystem_dot_filesystem__pb2.MakeDirRequest, **opts
- ) -> Coroutine[Any, Any, filesystem_dot_filesystem__pb2.MakeDirResponse]:
- return self._make_dir.acall_unary(req, **opts)
+ async def make_dir(
+ self,
+ request: MakeDirRequest,
+ *,
+ headers: Headers | Mapping[str, str] | None = None,
+ timeout_ms: int | None = None,
+ ) -> MakeDirResponse:
+ return await self.execute_unary(
+ request=request,
+ method=MethodInfo(
+ name="MakeDir",
+ service_name="filesystem.Filesystem",
+ input=MakeDirRequest,
+ output=MakeDirResponse,
+ idempotency_level=IdempotencyLevel.UNKNOWN,
+ ),
+ headers=headers,
+ timeout_ms=timeout_ms,
+ )
- def move(
- self, req: filesystem_dot_filesystem__pb2.MoveRequest, **opts
- ) -> filesystem_dot_filesystem__pb2.MoveResponse:
- return self._move.call_unary(req, **opts)
+ async def move(
+ self,
+ request: MoveRequest,
+ *,
+ headers: Headers | Mapping[str, str] | None = None,
+ timeout_ms: int | None = None,
+ ) -> MoveResponse:
+ return await self.execute_unary(
+ request=request,
+ method=MethodInfo(
+ name="Move",
+ service_name="filesystem.Filesystem",
+ input=MoveRequest,
+ output=MoveResponse,
+ idempotency_level=IdempotencyLevel.UNKNOWN,
+ ),
+ headers=headers,
+ timeout_ms=timeout_ms,
+ )
- def amove(
- self, req: filesystem_dot_filesystem__pb2.MoveRequest, **opts
- ) -> Coroutine[Any, Any, filesystem_dot_filesystem__pb2.MoveResponse]:
- return self._move.acall_unary(req, **opts)
+ async def list_dir(
+ self,
+ request: ListDirRequest,
+ *,
+ headers: Headers | Mapping[str, str] | None = None,
+ timeout_ms: int | None = None,
+ ) -> ListDirResponse:
+ return await self.execute_unary(
+ request=request,
+ method=MethodInfo(
+ name="ListDir",
+ service_name="filesystem.Filesystem",
+ input=ListDirRequest,
+ output=ListDirResponse,
+ idempotency_level=IdempotencyLevel.UNKNOWN,
+ ),
+ headers=headers,
+ timeout_ms=timeout_ms,
+ )
- def list_dir(
- self, req: filesystem_dot_filesystem__pb2.ListDirRequest, **opts
- ) -> filesystem_dot_filesystem__pb2.ListDirResponse:
- return self._list_dir.call_unary(req, **opts)
+ async def remove(
+ self,
+ request: RemoveRequest,
+ *,
+ headers: Headers | Mapping[str, str] | None = None,
+ timeout_ms: int | None = None,
+ ) -> RemoveResponse:
+ return await self.execute_unary(
+ request=request,
+ method=MethodInfo(
+ name="Remove",
+ service_name="filesystem.Filesystem",
+ input=RemoveRequest,
+ output=RemoveResponse,
+ idempotency_level=IdempotencyLevel.UNKNOWN,
+ ),
+ headers=headers,
+ timeout_ms=timeout_ms,
+ )
- def alist_dir(
- self, req: filesystem_dot_filesystem__pb2.ListDirRequest, **opts
- ) -> Coroutine[Any, Any, filesystem_dot_filesystem__pb2.ListDirResponse]:
- return self._list_dir.acall_unary(req, **opts)
+ def watch_dir(
+ self,
+ request: WatchDirRequest,
+ *,
+ headers: Headers | Mapping[str, str] | None = None,
+ timeout_ms: int | None = None,
+ ) -> AsyncIterator[WatchDirResponse]:
+ return self.execute_server_stream(
+ request=request,
+ method=MethodInfo(
+ name="WatchDir",
+ service_name="filesystem.Filesystem",
+ input=WatchDirRequest,
+ output=WatchDirResponse,
+ idempotency_level=IdempotencyLevel.UNKNOWN,
+ ),
+ headers=headers,
+ timeout_ms=timeout_ms,
+ )
- def remove(
- self, req: filesystem_dot_filesystem__pb2.RemoveRequest, **opts
- ) -> filesystem_dot_filesystem__pb2.RemoveResponse:
- return self._remove.call_unary(req, **opts)
+ async def create_watcher(
+ self,
+ request: CreateWatcherRequest,
+ *,
+ headers: Headers | Mapping[str, str] | None = None,
+ timeout_ms: int | None = None,
+ ) -> CreateWatcherResponse:
+ return await self.execute_unary(
+ request=request,
+ method=MethodInfo(
+ name="CreateWatcher",
+ service_name="filesystem.Filesystem",
+ input=CreateWatcherRequest,
+ output=CreateWatcherResponse,
+ idempotency_level=IdempotencyLevel.UNKNOWN,
+ ),
+ headers=headers,
+ timeout_ms=timeout_ms,
+ )
- def aremove(
- self, req: filesystem_dot_filesystem__pb2.RemoveRequest, **opts
- ) -> Coroutine[Any, Any, filesystem_dot_filesystem__pb2.RemoveResponse]:
- return self._remove.acall_unary(req, **opts)
+ async def get_watcher_events(
+ self,
+ request: GetWatcherEventsRequest,
+ *,
+ headers: Headers | Mapping[str, str] | None = None,
+ timeout_ms: int | None = None,
+ ) -> GetWatcherEventsResponse:
+ return await self.execute_unary(
+ request=request,
+ method=MethodInfo(
+ name="GetWatcherEvents",
+ service_name="filesystem.Filesystem",
+ input=GetWatcherEventsRequest,
+ output=GetWatcherEventsResponse,
+ idempotency_level=IdempotencyLevel.UNKNOWN,
+ ),
+ headers=headers,
+ timeout_ms=timeout_ms,
+ )
- def watch_dir(
- self, req: filesystem_dot_filesystem__pb2.WatchDirRequest, **opts
- ) -> Generator[filesystem_dot_filesystem__pb2.WatchDirResponse, Any, None]:
- return self._watch_dir.call_server_stream(req, **opts)
+ async def remove_watcher(
+ self,
+ request: RemoveWatcherRequest,
+ *,
+ headers: Headers | Mapping[str, str] | None = None,
+ timeout_ms: int | None = None,
+ ) -> RemoveWatcherResponse:
+ return await self.execute_unary(
+ request=request,
+ method=MethodInfo(
+ name="RemoveWatcher",
+ service_name="filesystem.Filesystem",
+ input=RemoveWatcherRequest,
+ output=RemoveWatcherResponse,
+ idempotency_level=IdempotencyLevel.UNKNOWN,
+ ),
+ headers=headers,
+ timeout_ms=timeout_ms,
+ )
- def awatch_dir(
- self, req: filesystem_dot_filesystem__pb2.WatchDirRequest, **opts
- ) -> AsyncGenerator[filesystem_dot_filesystem__pb2.WatchDirResponse, Any]:
- return self._watch_dir.acall_server_stream(req, **opts)
+class FilesystemSync(Protocol):
+ def stat(self, request: StatRequest, ctx: RequestContext[StatRequest, StatResponse]) -> StatResponse:
+ raise ConnectError(Code.UNIMPLEMENTED, 'Not implemented')
- def create_watcher(
- self, req: filesystem_dot_filesystem__pb2.CreateWatcherRequest, **opts
- ) -> filesystem_dot_filesystem__pb2.CreateWatcherResponse:
- return self._create_watcher.call_unary(req, **opts)
+ def make_dir(self, request: MakeDirRequest, ctx: RequestContext[MakeDirRequest, MakeDirResponse]) -> MakeDirResponse:
+ raise ConnectError(Code.UNIMPLEMENTED, 'Not implemented')
- def acreate_watcher(
- self, req: filesystem_dot_filesystem__pb2.CreateWatcherRequest, **opts
- ) -> Coroutine[Any, Any, filesystem_dot_filesystem__pb2.CreateWatcherResponse]:
- return self._create_watcher.acall_unary(req, **opts)
+ def move(self, request: MoveRequest, ctx: RequestContext[MoveRequest, MoveResponse]) -> MoveResponse:
+ raise ConnectError(Code.UNIMPLEMENTED, 'Not implemented')
- def get_watcher_events(
- self, req: filesystem_dot_filesystem__pb2.GetWatcherEventsRequest, **opts
- ) -> filesystem_dot_filesystem__pb2.GetWatcherEventsResponse:
- return self._get_watcher_events.call_unary(req, **opts)
+ def list_dir(self, request: ListDirRequest, ctx: RequestContext[ListDirRequest, ListDirResponse]) -> ListDirResponse:
+ raise ConnectError(Code.UNIMPLEMENTED, 'Not implemented')
+
+ def remove(self, request: RemoveRequest, ctx: RequestContext[RemoveRequest, RemoveResponse]) -> RemoveResponse:
+ raise ConnectError(Code.UNIMPLEMENTED, 'Not implemented')
+
+ def watch_dir(self, request: WatchDirRequest, ctx: RequestContext[WatchDirRequest, WatchDirResponse]) -> Iterator[WatchDirResponse]:
+ raise ConnectError(Code.UNIMPLEMENTED, 'Not implemented')
+
+ def create_watcher(self, request: CreateWatcherRequest, ctx: RequestContext[CreateWatcherRequest, CreateWatcherResponse]) -> CreateWatcherResponse:
+ raise ConnectError(Code.UNIMPLEMENTED, 'Not implemented')
+
+ def get_watcher_events(self, request: GetWatcherEventsRequest, ctx: RequestContext[GetWatcherEventsRequest, GetWatcherEventsResponse]) -> GetWatcherEventsResponse:
+ raise ConnectError(Code.UNIMPLEMENTED, 'Not implemented')
+
+ def remove_watcher(self, request: RemoveWatcherRequest, ctx: RequestContext[RemoveWatcherRequest, RemoveWatcherResponse]) -> RemoveWatcherResponse:
+ raise ConnectError(Code.UNIMPLEMENTED, 'Not implemented')
+
+
+class FilesystemWSGIApplication(ConnectWSGIApplication):
+ def __init__(
+ self,
+ service: FilesystemSync,
+ interceptors: Iterable[InterceptorSync] = (),
+ read_max_bytes: int | None = None,
+ compressions: Iterable[Compression] | None = None,
+ codecs: Iterable[Codec] | None = None,
+ ) -> None:
+ super().__init__(
+ endpoints={
+ "/filesystem.Filesystem/Stat": EndpointSync.unary(
+ method=MethodInfo(
+ name="Stat",
+ service_name="filesystem.Filesystem",
+ input=StatRequest,
+ output=StatResponse,
+ idempotency_level=IdempotencyLevel.UNKNOWN,
+ ),
+ function=service.stat,
+ ),
+ "/filesystem.Filesystem/MakeDir": EndpointSync.unary(
+ method=MethodInfo(
+ name="MakeDir",
+ service_name="filesystem.Filesystem",
+ input=MakeDirRequest,
+ output=MakeDirResponse,
+ idempotency_level=IdempotencyLevel.UNKNOWN,
+ ),
+ function=service.make_dir,
+ ),
+ "/filesystem.Filesystem/Move": EndpointSync.unary(
+ method=MethodInfo(
+ name="Move",
+ service_name="filesystem.Filesystem",
+ input=MoveRequest,
+ output=MoveResponse,
+ idempotency_level=IdempotencyLevel.UNKNOWN,
+ ),
+ function=service.move,
+ ),
+ "/filesystem.Filesystem/ListDir": EndpointSync.unary(
+ method=MethodInfo(
+ name="ListDir",
+ service_name="filesystem.Filesystem",
+ input=ListDirRequest,
+ output=ListDirResponse,
+ idempotency_level=IdempotencyLevel.UNKNOWN,
+ ),
+ function=service.list_dir,
+ ),
+ "/filesystem.Filesystem/Remove": EndpointSync.unary(
+ method=MethodInfo(
+ name="Remove",
+ service_name="filesystem.Filesystem",
+ input=RemoveRequest,
+ output=RemoveResponse,
+ idempotency_level=IdempotencyLevel.UNKNOWN,
+ ),
+ function=service.remove,
+ ),
+ "/filesystem.Filesystem/WatchDir": EndpointSync.server_stream(
+ method=MethodInfo(
+ name="WatchDir",
+ service_name="filesystem.Filesystem",
+ input=WatchDirRequest,
+ output=WatchDirResponse,
+ idempotency_level=IdempotencyLevel.UNKNOWN,
+ ),
+ function=service.watch_dir,
+ ),
+ "/filesystem.Filesystem/CreateWatcher": EndpointSync.unary(
+ method=MethodInfo(
+ name="CreateWatcher",
+ service_name="filesystem.Filesystem",
+ input=CreateWatcherRequest,
+ output=CreateWatcherResponse,
+ idempotency_level=IdempotencyLevel.UNKNOWN,
+ ),
+ function=service.create_watcher,
+ ),
+ "/filesystem.Filesystem/GetWatcherEvents": EndpointSync.unary(
+ method=MethodInfo(
+ name="GetWatcherEvents",
+ service_name="filesystem.Filesystem",
+ input=GetWatcherEventsRequest,
+ output=GetWatcherEventsResponse,
+ idempotency_level=IdempotencyLevel.UNKNOWN,
+ ),
+ function=service.get_watcher_events,
+ ),
+ "/filesystem.Filesystem/RemoveWatcher": EndpointSync.unary(
+ method=MethodInfo(
+ name="RemoveWatcher",
+ service_name="filesystem.Filesystem",
+ input=RemoveWatcherRequest,
+ output=RemoveWatcherResponse,
+ idempotency_level=IdempotencyLevel.UNKNOWN,
+ ),
+ function=service.remove_watcher,
+ ),
+ },
+ interceptors=interceptors,
+ read_max_bytes=read_max_bytes,
+ compressions=compressions,
+ codecs=codecs,
+ )
- def aget_watcher_events(
- self, req: filesystem_dot_filesystem__pb2.GetWatcherEventsRequest, **opts
- ) -> Coroutine[Any, Any, filesystem_dot_filesystem__pb2.GetWatcherEventsResponse]:
- return self._get_watcher_events.acall_unary(req, **opts)
+ @property
+ def path(self) -> str:
+ """Returns the URL path to mount the application to when serving multiple applications."""
+ return "/filesystem.Filesystem"
+
+class FilesystemClientSync(ConnectClientSync):
+ def stat(
+ self,
+ request: StatRequest,
+ *,
+ headers: Headers | Mapping[str, str] | None = None,
+ timeout_ms: int | None = None,
+ ) -> StatResponse:
+ return self.execute_unary(
+ request=request,
+ method=MethodInfo(
+ name="Stat",
+ service_name="filesystem.Filesystem",
+ input=StatRequest,
+ output=StatResponse,
+ idempotency_level=IdempotencyLevel.UNKNOWN,
+ ),
+ headers=headers,
+ timeout_ms=timeout_ms,
+ )
+ def make_dir(
+ self,
+ request: MakeDirRequest,
+ *,
+ headers: Headers | Mapping[str, str] | None = None,
+ timeout_ms: int | None = None,
+ ) -> MakeDirResponse:
+ return self.execute_unary(
+ request=request,
+ method=MethodInfo(
+ name="MakeDir",
+ service_name="filesystem.Filesystem",
+ input=MakeDirRequest,
+ output=MakeDirResponse,
+ idempotency_level=IdempotencyLevel.UNKNOWN,
+ ),
+ headers=headers,
+ timeout_ms=timeout_ms,
+ )
+ def move(
+ self,
+ request: MoveRequest,
+ *,
+ headers: Headers | Mapping[str, str] | None = None,
+ timeout_ms: int | None = None,
+ ) -> MoveResponse:
+ return self.execute_unary(
+ request=request,
+ method=MethodInfo(
+ name="Move",
+ service_name="filesystem.Filesystem",
+ input=MoveRequest,
+ output=MoveResponse,
+ idempotency_level=IdempotencyLevel.UNKNOWN,
+ ),
+ headers=headers,
+ timeout_ms=timeout_ms,
+ )
+ def list_dir(
+ self,
+ request: ListDirRequest,
+ *,
+ headers: Headers | Mapping[str, str] | None = None,
+ timeout_ms: int | None = None,
+ ) -> ListDirResponse:
+ return self.execute_unary(
+ request=request,
+ method=MethodInfo(
+ name="ListDir",
+ service_name="filesystem.Filesystem",
+ input=ListDirRequest,
+ output=ListDirResponse,
+ idempotency_level=IdempotencyLevel.UNKNOWN,
+ ),
+ headers=headers,
+ timeout_ms=timeout_ms,
+ )
+ def remove(
+ self,
+ request: RemoveRequest,
+ *,
+ headers: Headers | Mapping[str, str] | None = None,
+ timeout_ms: int | None = None,
+ ) -> RemoveResponse:
+ return self.execute_unary(
+ request=request,
+ method=MethodInfo(
+ name="Remove",
+ service_name="filesystem.Filesystem",
+ input=RemoveRequest,
+ output=RemoveResponse,
+ idempotency_level=IdempotencyLevel.UNKNOWN,
+ ),
+ headers=headers,
+ timeout_ms=timeout_ms,
+ )
+ def watch_dir(
+ self,
+ request: WatchDirRequest,
+ *,
+ headers: Headers | Mapping[str, str] | None = None,
+ timeout_ms: int | None = None,
+ ) -> Iterator[WatchDirResponse]:
+ return self.execute_server_stream(
+ request=request,
+ method=MethodInfo(
+ name="WatchDir",
+ service_name="filesystem.Filesystem",
+ input=WatchDirRequest,
+ output=WatchDirResponse,
+ idempotency_level=IdempotencyLevel.UNKNOWN,
+ ),
+ headers=headers,
+ timeout_ms=timeout_ms,
+ )
+ def create_watcher(
+ self,
+ request: CreateWatcherRequest,
+ *,
+ headers: Headers | Mapping[str, str] | None = None,
+ timeout_ms: int | None = None,
+ ) -> CreateWatcherResponse:
+ return self.execute_unary(
+ request=request,
+ method=MethodInfo(
+ name="CreateWatcher",
+ service_name="filesystem.Filesystem",
+ input=CreateWatcherRequest,
+ output=CreateWatcherResponse,
+ idempotency_level=IdempotencyLevel.UNKNOWN,
+ ),
+ headers=headers,
+ timeout_ms=timeout_ms,
+ )
+ def get_watcher_events(
+ self,
+ request: GetWatcherEventsRequest,
+ *,
+ headers: Headers | Mapping[str, str] | None = None,
+ timeout_ms: int | None = None,
+ ) -> GetWatcherEventsResponse:
+ return self.execute_unary(
+ request=request,
+ method=MethodInfo(
+ name="GetWatcherEvents",
+ service_name="filesystem.Filesystem",
+ input=GetWatcherEventsRequest,
+ output=GetWatcherEventsResponse,
+ idempotency_level=IdempotencyLevel.UNKNOWN,
+ ),
+ headers=headers,
+ timeout_ms=timeout_ms,
+ )
def remove_watcher(
- self, req: filesystem_dot_filesystem__pb2.RemoveWatcherRequest, **opts
- ) -> filesystem_dot_filesystem__pb2.RemoveWatcherResponse:
- return self._remove_watcher.call_unary(req, **opts)
-
- def aremove_watcher(
- self, req: filesystem_dot_filesystem__pb2.RemoveWatcherRequest, **opts
- ) -> Coroutine[Any, Any, filesystem_dot_filesystem__pb2.RemoveWatcherResponse]:
- return self._remove_watcher.acall_unary(req, **opts)
+ self,
+ request: RemoveWatcherRequest,
+ *,
+ headers: Headers | Mapping[str, str] | None = None,
+ timeout_ms: int | None = None,
+ ) -> RemoveWatcherResponse:
+ return self.execute_unary(
+ request=request,
+ method=MethodInfo(
+ name="RemoveWatcher",
+ service_name="filesystem.Filesystem",
+ input=RemoveWatcherRequest,
+ output=RemoveWatcherResponse,
+ idempotency_level=IdempotencyLevel.UNKNOWN,
+ ),
+ headers=headers,
+ timeout_ms=timeout_ms,
+ )
diff --git a/packages/python-sdk/e2b/envd/filesystem/filesystem_pb.py b/packages/python-sdk/e2b/envd/filesystem/filesystem_pb.py
new file mode 100644
index 000000000..5cac7bfa9
--- /dev/null
+++ b/packages/python-sdk/e2b/envd/filesystem/filesystem_pb.py
@@ -0,0 +1,838 @@
+# Generated from filesystem/filesystem.proto. DO NOT EDIT.
+# Generated by protoc-gen-py v0.1.1 with parameter "".
+# ruff: noqa: PGH004
+# ruff: noqa
+# fmt: off
+
+from __future__ import annotations
+
+from typing import Literal, NoReturn, TYPE_CHECKING, TypeAlias
+
+from protobuf import Enum, Message
+from protobuf._codegen import file_desc
+from protobuf.wkt import timestamp_pb
+
+if TYPE_CHECKING:
+ from protobuf import DescFile, Oneof
+ from protobuf.wkt import Timestamp
+
+
+_MoveRequestFields: TypeAlias = Literal["source", "destination"]
+
+class MoveRequest(Message[_MoveRequestFields]):
+ """
+ ```proto
+ message filesystem.MoveRequest
+ ```
+
+ Attributes:
+ source:
+ ```proto
+ string source = 1;
+ ```
+ destination:
+ ```proto
+ string destination = 2;
+ ```
+ """
+
+ __slots__ = ("source", "destination")
+
+ if TYPE_CHECKING:
+
+ def __init__(
+ self,
+ *,
+ source: str = "",
+ destination: str = "",
+ ) -> None:
+ pass
+
+ source: str
+ destination: str
+
+_MoveResponseFields: TypeAlias = Literal["entry"]
+
+class MoveResponse(Message[_MoveResponseFields]):
+ """
+ ```proto
+ message filesystem.MoveResponse
+ ```
+
+ Attributes:
+ entry:
+ ```proto
+ optional filesystem.EntryInfo entry = 1;
+ ```
+ """
+
+ __slots__ = ("entry",)
+
+ if TYPE_CHECKING:
+
+ def __init__(
+ self,
+ *,
+ entry: EntryInfo | None = None,
+ ) -> None:
+ pass
+
+ entry: EntryInfo | None
+
+_MakeDirRequestFields: TypeAlias = Literal["path"]
+
+class MakeDirRequest(Message[_MakeDirRequestFields]):
+ """
+ ```proto
+ message filesystem.MakeDirRequest
+ ```
+
+ Attributes:
+ path:
+ ```proto
+ string path = 1;
+ ```
+ """
+
+ __slots__ = ("path",)
+
+ if TYPE_CHECKING:
+
+ def __init__(
+ self,
+ *,
+ path: str = "",
+ ) -> None:
+ pass
+
+ path: str
+
+_MakeDirResponseFields: TypeAlias = Literal["entry"]
+
+class MakeDirResponse(Message[_MakeDirResponseFields]):
+ """
+ ```proto
+ message filesystem.MakeDirResponse
+ ```
+
+ Attributes:
+ entry:
+ ```proto
+ optional filesystem.EntryInfo entry = 1;
+ ```
+ """
+
+ __slots__ = ("entry",)
+
+ if TYPE_CHECKING:
+
+ def __init__(
+ self,
+ *,
+ entry: EntryInfo | None = None,
+ ) -> None:
+ pass
+
+ entry: EntryInfo | None
+
+_RemoveRequestFields: TypeAlias = Literal["path"]
+
+class RemoveRequest(Message[_RemoveRequestFields]):
+ """
+ ```proto
+ message filesystem.RemoveRequest
+ ```
+
+ Attributes:
+ path:
+ ```proto
+ string path = 1;
+ ```
+ """
+
+ __slots__ = ("path",)
+
+ if TYPE_CHECKING:
+
+ def __init__(
+ self,
+ *,
+ path: str = "",
+ ) -> None:
+ pass
+
+ path: str
+
+_RemoveResponseFields: TypeAlias = NoReturn
+
+class RemoveResponse(Message[_RemoveResponseFields]):
+ """
+ ```proto
+ message filesystem.RemoveResponse
+ ```
+ """
+
+ __slots__ = ()
+
+ if TYPE_CHECKING:
+
+ def __init__(
+ self,
+ ) -> None:
+ pass
+
+_StatRequestFields: TypeAlias = Literal["path"]
+
+class StatRequest(Message[_StatRequestFields]):
+ """
+ ```proto
+ message filesystem.StatRequest
+ ```
+
+ Attributes:
+ path:
+ ```proto
+ string path = 1;
+ ```
+ """
+
+ __slots__ = ("path",)
+
+ if TYPE_CHECKING:
+
+ def __init__(
+ self,
+ *,
+ path: str = "",
+ ) -> None:
+ pass
+
+ path: str
+
+_StatResponseFields: TypeAlias = Literal["entry"]
+
+class StatResponse(Message[_StatResponseFields]):
+ """
+ ```proto
+ message filesystem.StatResponse
+ ```
+
+ Attributes:
+ entry:
+ ```proto
+ optional filesystem.EntryInfo entry = 1;
+ ```
+ """
+
+ __slots__ = ("entry",)
+
+ if TYPE_CHECKING:
+
+ def __init__(
+ self,
+ *,
+ entry: EntryInfo | None = None,
+ ) -> None:
+ pass
+
+ entry: EntryInfo | None
+
+_EntryInfoFields: TypeAlias = Literal["name", "type", "path", "size", "mode", "permissions", "owner", "group", "modified_time", "symlink_target", "metadata"]
+
+class EntryInfo(Message[_EntryInfoFields]):
+ """
+ ```proto
+ message filesystem.EntryInfo
+ ```
+
+ Attributes:
+ name:
+ ```proto
+ string name = 1;
+ ```
+ type:
+ ```proto
+ filesystem.FileType type = 2;
+ ```
+ path:
+ ```proto
+ string path = 3;
+ ```
+ size:
+ ```proto
+ int64 size = 4;
+ ```
+ mode:
+ ```proto
+ uint32 mode = 5;
+ ```
+ permissions:
+ ```proto
+ string permissions = 6;
+ ```
+ owner:
+ ```proto
+ string owner = 7;
+ ```
+ group:
+ ```proto
+ string group = 8;
+ ```
+ modified_time:
+ ```proto
+ optional google.protobuf.Timestamp modified_time = 9;
+ ```
+ symlink_target:
+ If the entry is a symlink, this field contains the target of the symlink.
+
+ ```proto
+ optional string symlink_target = 10;
+ ```
+ metadata:
+ User-defined metadata stored as extended attributes (xattrs) on the file.
+ Keys live under the `user.e2b.` xattr namespace; the prefix is stripped here.
+ Plain `user.*` xattrs written by other tooling are not reflected.
+
+ ```proto
+ map<string, string> metadata = 11;
+ ```
+ """
+
+ __slots__ = ("name", "type", "path", "size", "mode", "permissions", "owner", "group", "modified_time", "symlink_target", "metadata")
+
+ if TYPE_CHECKING:
+
+ def __init__(
+ self,
+ *,
+ name: str = "",
+ type: FileType | None = None,
+ path: str = "",
+ size: int = 0,
+ mode: int = 0,
+ permissions: str = "",
+ owner: str = "",
+ group: str = "",
+ modified_time: Timestamp | None = None,
+ symlink_target: str | None = None,
+ metadata: dict[str, str] | None = None,
+ ) -> None:
+ pass
+
+ name: str
+ type: FileType
+ path: str
+ size: int
+ mode: int
+ permissions: str
+ owner: str
+ group: str
+ modified_time: Timestamp | None
+ symlink_target: str
+ metadata: dict[str, str]
+
+_ListDirRequestFields: TypeAlias = Literal["path", "depth"]
+
+class ListDirRequest(Message[_ListDirRequestFields]):
+ """
+ ```proto
+ message filesystem.ListDirRequest
+ ```
+
+ Attributes:
+ path:
+ ```proto
+ string path = 1;
+ ```
+ depth:
+ ```proto
+ uint32 depth = 2;
+ ```
+ """
+
+ __slots__ = ("path", "depth")
+
+ if TYPE_CHECKING:
+
+ def __init__(
+ self,
+ *,
+ path: str = "",
+ depth: int = 0,
+ ) -> None:
+ pass
+
+ path: str
+ depth: int
+
+_ListDirResponseFields: TypeAlias = Literal["entries"]
+
+class ListDirResponse(Message[_ListDirResponseFields]):
+ """
+ ```proto
+ message filesystem.ListDirResponse
+ ```
+
+ Attributes:
+ entries:
+ ```proto
+ repeated filesystem.EntryInfo entries = 1;
+ ```
+ """
+
+ __slots__ = ("entries",)
+
+ if TYPE_CHECKING:
+
+ def __init__(
+ self,
+ *,
+ entries: list[EntryInfo] | None = None,
+ ) -> None:
+ pass
+
+ entries: list[EntryInfo]
+
+_WatchDirRequestFields: TypeAlias = Literal["path", "recursive", "include_entry", "allow_network_mounts"]
+
+class WatchDirRequest(Message[_WatchDirRequestFields]):
+ """
+ ```proto
+ message filesystem.WatchDirRequest
+ ```
+
+ Attributes:
+ path:
+ ```proto
+ string path = 1;
+ ```
+ recursive:
+ ```proto
+ bool recursive = 2;
+ ```
+ include_entry:
+ If true, each FilesystemEvent includes the EntryInfo of the affected entry, when available.
+
+ ```proto
+ bool include_entry = 3;
+ ```
+ allow_network_mounts:
+ If true, allows watching paths on network filesystem mounts (NFS, CIFS, SMB, FUSE).
+ Events on network mounts may be unreliable or not delivered at all.
+
+ ```proto
+ bool allow_network_mounts = 4;
+ ```
+ """
+
+ __slots__ = ("path", "recursive", "include_entry", "allow_network_mounts")
+
+ if TYPE_CHECKING:
+
+ def __init__(
+ self,
+ *,
+ path: str = "",
+ recursive: bool = False,
+ include_entry: bool = False,
+ allow_network_mounts: bool = False,
+ ) -> None:
+ pass
+
+ path: str
+ recursive: bool
+ include_entry: bool
+ allow_network_mounts: bool
+
+_FilesystemEventFields: TypeAlias = Literal["name", "type", "entry"]
+
+class FilesystemEvent(Message[_FilesystemEventFields]):
+ """
+ ```proto
+ message filesystem.FilesystemEvent
+ ```
+
+ Attributes:
+ name:
+ ```proto
+ string name = 1;
+ ```
+ type:
+ ```proto
+ filesystem.EventType type = 2;
+ ```
+ entry:
+ Info of the entry that triggered the event. Only populated when include_entry
+ was requested and the entry could be stat-ed (e.g. not set for remove/rename-away
+ events, where the entry no longer exists at this path).
+
+ ```proto
+ optional filesystem.EntryInfo entry = 3;
+ ```
+ """
+
+ __slots__ = ("name", "type", "entry")
+
+ if TYPE_CHECKING:
+
+ def __init__(
+ self,
+ *,
+ name: str = "",
+ type: EventType | None = None,
+ entry: EntryInfo | None = None,
+ ) -> None:
+ pass
+
+ name: str
+ type: EventType
+ entry: EntryInfo | None
+
+_WatchDirResponseFields: TypeAlias = Literal["start", "filesystem", "keepalive"]
+
+class WatchDirResponse(Message[_WatchDirResponseFields]):
+ """
+ ```proto
+ message filesystem.WatchDirResponse
+ ```
+
+ Attributes:
+ event:
+ ```proto
+ oneof event
+ ```
+ """
+
+ __slots__ = ("event",)
+
+ if TYPE_CHECKING:
+
+ def __init__(
+ self,
+ *,
+ event: Oneof[Literal["start"], WatchDirResponse.StartEvent] | Oneof[Literal["filesystem"], FilesystemEvent] | Oneof[Literal["keepalive"], WatchDirResponse.KeepAlive] | None = None,
+ ) -> None:
+ pass
+
+ event: Oneof[Literal["start"], WatchDirResponse.StartEvent] | Oneof[Literal["filesystem"], FilesystemEvent] | Oneof[Literal["keepalive"], WatchDirResponse.KeepAlive] | None
+
+ _StartEventFields: TypeAlias = NoReturn
+
+ class StartEvent(Message[_StartEventFields]):
+ """
+ ```proto
+ message filesystem.WatchDirResponse.StartEvent
+ ```
+ """
+
+ __slots__ = ()
+
+ if TYPE_CHECKING:
+
+ def __init__(
+ self,
+ ) -> None:
+ pass
+
+ _KeepAliveFields: TypeAlias = NoReturn
+
+ class KeepAlive(Message[_KeepAliveFields]):
+ """
+ ```proto
+ message filesystem.WatchDirResponse.KeepAlive
+ ```
+ """
+
+ __slots__ = ()
+
+ if TYPE_CHECKING:
+
+ def __init__(
+ self,
+ ) -> None:
+ pass
+
+_CreateWatcherRequestFields: TypeAlias = Literal["path", "recursive", "include_entry", "allow_network_mounts"]
+
+class CreateWatcherRequest(Message[_CreateWatcherRequestFields]):
+ """
+ ```proto
+ message filesystem.CreateWatcherRequest
+ ```
+
+ Attributes:
+ path:
+ ```proto
+ string path = 1;
+ ```
+ recursive:
+ ```proto
+ bool recursive = 2;
+ ```
+ include_entry:
+ If true, each FilesystemEvent includes the EntryInfo of the affected entry, when available.
+
+ ```proto
+ bool include_entry = 3;
+ ```
+ allow_network_mounts:
+ If true, allows watching paths on network filesystem mounts (NFS, CIFS, SMB, FUSE).
+ Events on network mounts may be unreliable or not delivered at all.
+
+ ```proto
+ bool allow_network_mounts = 4;
+ ```
+ """
+
+ __slots__ = ("path", "recursive", "include_entry", "allow_network_mounts")
+
+ if TYPE_CHECKING:
+
+ def __init__(
+ self,
+ *,
+ path: str = "",
+ recursive: bool = False,
+ include_entry: bool = False,
+ allow_network_mounts: bool = False,
+ ) -> None:
+ pass
+
+ path: str
+ recursive: bool
+ include_entry: bool
+ allow_network_mounts: bool
+
+_CreateWatcherResponseFields: TypeAlias = Literal["watcher_id"]
+
+class CreateWatcherResponse(Message[_CreateWatcherResponseFields]):
+ """
+ ```proto
+ message filesystem.CreateWatcherResponse
+ ```
+
+ Attributes:
+ watcher_id:
+ ```proto
+ string watcher_id = 1;
+ ```
+ """
+
+ __slots__ = ("watcher_id",)
+
+ if TYPE_CHECKING:
+
+ def __init__(
+ self,
+ *,
+ watcher_id: str = "",
+ ) -> None:
+ pass
+
+ watcher_id: str
+
+_GetWatcherEventsRequestFields: TypeAlias = Literal["watcher_id"]
+
+class GetWatcherEventsRequest(Message[_GetWatcherEventsRequestFields]):
+ """
+ ```proto
+ message filesystem.GetWatcherEventsRequest
+ ```
+
+ Attributes:
+ watcher_id:
+ ```proto
+ string watcher_id = 1;
+ ```
+ """
+
+ __slots__ = ("watcher_id",)
+
+ if TYPE_CHECKING:
+
+ def __init__(
+ self,
+ *,
+ watcher_id: str = "",
+ ) -> None:
+ pass
+
+ watcher_id: str
+
+_GetWatcherEventsResponseFields: TypeAlias = Literal["events"]
+
+class GetWatcherEventsResponse(Message[_GetWatcherEventsResponseFields]):
+ """
+ ```proto
+ message filesystem.GetWatcherEventsResponse
+ ```
+
+ Attributes:
+ events:
+ ```proto
+ repeated filesystem.FilesystemEvent events = 1;
+ ```
+ """
+
+ __slots__ = ("events",)
+
+ if TYPE_CHECKING:
+
+ def __init__(
+ self,
+ *,
+ events: list[FilesystemEvent] | None = None,
+ ) -> None:
+ pass
+
+ events: list[FilesystemEvent]
+
+_RemoveWatcherRequestFields: TypeAlias = Literal["watcher_id"]
+
+class RemoveWatcherRequest(Message[_RemoveWatcherRequestFields]):
+ """
+ ```proto
+ message filesystem.RemoveWatcherRequest
+ ```
+
+ Attributes:
+ watcher_id:
+ ```proto
+ string watcher_id = 1;
+ ```
+ """
+
+ __slots__ = ("watcher_id",)
+
+ if TYPE_CHECKING:
+
+ def __init__(
+ self,
+ *,
+ watcher_id: str = "",
+ ) -> None:
+ pass
+
+ watcher_id: str
+
+_RemoveWatcherResponseFields: TypeAlias = NoReturn
+
+class RemoveWatcherResponse(Message[_RemoveWatcherResponseFields]):
+ """
+ ```proto
+ message filesystem.RemoveWatcherResponse
+ ```
+ """
+
+ __slots__ = ()
+
+ if TYPE_CHECKING:
+
+ def __init__(
+ self,
+ ) -> None:
+ pass
+
+class FileType(Enum):
+ """
+ ```proto
+ enum filesystem.FileType
+ ```
+
+ Attributes:
+ UNSPECIFIED:
+ ```proto
+ FILE_TYPE_UNSPECIFIED = 0
+ ```
+ FILE:
+ ```proto
+ FILE_TYPE_FILE = 1
+ ```
+ DIRECTORY:
+ ```proto
+ FILE_TYPE_DIRECTORY = 2
+ ```
+ """
+
+ UNSPECIFIED = 0
+ FILE = 1
+ DIRECTORY = 2
+
+class EventType(Enum):
+ """
+ ```proto
+ enum filesystem.EventType
+ ```
+
+ Attributes:
+ UNSPECIFIED:
+ ```proto
+ EVENT_TYPE_UNSPECIFIED = 0
+ ```
+ CREATE:
+ ```proto
+ EVENT_TYPE_CREATE = 1
+ ```
+ WRITE:
+ ```proto
+ EVENT_TYPE_WRITE = 2
+ ```
+ REMOVE:
+ ```proto
+ EVENT_TYPE_REMOVE = 3
+ ```
+ RENAME:
+ ```proto
+ EVENT_TYPE_RENAME = 4
+ ```
+ CHMOD:
+ ```proto
+ EVENT_TYPE_CHMOD = 5
+ ```
+ """
+
+ UNSPECIFIED = 0
+ CREATE = 1
+ WRITE = 2
+ REMOVE = 3
+ RENAME = 4
+ CHMOD = 5
+
+
+_DESC = file_desc(
+ b'\n\x1bfilesystem/filesystem.proto\x12\nfilesystem\x1a\x1fgoogle/protobuf/timestamp.proto"G\n\x0bMoveRequest\x12\x16\n\x06source\x18\x01 \x01(\tR\x06source\x12 \n\x0bdestination\x18\x02 \x01(\tR\x0bdestination";\n\x0cMoveResponse\x12+\n\x05entry\x18\x01 \x01(\x0b2\x15.filesystem.EntryInfoR\x05entry"$\n\x0eMakeDirRequest\x12\x12\n\x04path\x18\x01 \x01(\tR\x04path">\n\x0fMakeDirResponse\x12+\n\x05entry\x18\x01 \x01(\x0b2\x15.filesystem.EntryInfoR\x05entry"#\n\rRemoveRequest\x12\x12\n\x04path\x18\x01 \x01(\tR\x04path"\x10\n\x0eRemoveResponse"!\n\x0bStatRequest\x12\x12\n\x04path\x18\x01 \x01(\tR\x04path";\n\x0cStatResponse\x12+\n\x05entry\x18\x01 \x01(\x0b2\x15.filesystem.EntryInfoR\x05entry"\xd1\x03\n\tEntryInfo\x12\x12\n\x04name\x18\x01 \x01(\tR\x04name\x12(\n\x04type\x18\x02 \x01(\x0e2\x14.filesystem.FileTypeR\x04type\x12\x12\n\x04path\x18\x03 \x01(\tR\x04path\x12\x12\n\x04size\x18\x04 \x01(\x03R\x04size\x12\x12\n\x04mode\x18\x05 \x01(\rR\x04mode\x12 \n\x0bpermissions\x18\x06 \x01(\tR\x0bpermissions\x12\x14\n\x05owner\x18\x07 \x01(\tR\x05owner\x12\x14\n\x05group\x18\x08 \x01(\tR\x05group\x12?\n\rmodified_time\x18\t \x01(\x0b2\x1a.google.protobuf.TimestampR\x0cmodifiedTime\x12*\n\x0esymlink_target\x18\n \x01(\tH\x00R\rsymlinkTarget\x88\x01\x01\x12?\n\x08metadata\x18\x0b \x03(\x0b2#.filesystem.EntryInfo.MetadataEntryR\x08metadata\x1a;\n\rMetadataEntry\x12\x10\n\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n\x05value\x18\x02 \x01(\tR\x05value:\x028\x01B\x11\n\x0f_symlink_target":\n\x0eListDirRequest\x12\x12\n\x04path\x18\x01 \x01(\tR\x04path\x12\x14\n\x05depth\x18\x02 \x01(\rR\x05depth"B\n\x0fListDirResponse\x12/\n\x07entries\x18\x01 \x03(\x0b2\x15.filesystem.EntryInfoR\x07entries"\x9a\x01\n\x0fWatchDirRequest\x12\x12\n\x04path\x18\x01 \x01(\tR\x04path\x12\x1c\n\trecursive\x18\x02 \x01(\x08R\trecursive\x12#\n\rinclude_entry\x18\x03 \x01(\x08R\x0cincludeEntry\x120\n\x14allow_network_mounts\x18\x04 \x01(\x08R\x12allowNetworkMounts"\x8c\x01\n\x0fFilesystemEvent\x12\x12\n\x04name\x18\x01 \x01(\tR\x04name\x12)\n\x04type\x18\x02 \x01(\x0e2\x15.filesystem.EventTypeR\x04type\x120\n\x05entry\x18\x03 \x01(\x0b2\x15.filesystem.EntryInfoH\x00R\x05entry\x88\x01\x01B\x08\n\x06_entry"\xfe\x01\n\x10WatchDirResponse\x12?\n\x05start\x18\x01 \x01(\x0b2\'.filesystem.WatchDirResponse.StartEventH\x00R\x05start\x12=\n\nfilesystem\x18\x02 \x01(\x0b2\x1b.filesystem.FilesystemEventH\x00R\nfilesystem\x12F\n\tkeepalive\x18\x03 \x01(\x0b2&.filesystem.WatchDirResponse.KeepAliveH\x00R\tkeepalive\x1a\x0c\n\nStartEvent\x1a\x0b\n\tKeepAliveB\x07\n\x05event"\x9f\x01\n\x14CreateWatcherRequest\x12\x12\n\x04path\x18\x01 \x01(\tR\x04path\x12\x1c\n\trecursive\x18\x02 \x01(\x08R\trecursive\x12#\n\rinclude_entry\x18\x03 \x01(\x08R\x0cincludeEntry\x120\n\x14allow_network_mounts\x18\x04 \x01(\x08R\x12allowNetworkMounts"6\n\x15CreateWatcherResponse\x12\x1d\n\nwatcher_id\x18\x01 \x01(\tR\twatcherId"8\n\x17GetWatcherEventsRequest\x12\x1d\n\nwatcher_id\x18\x01 \x01(\tR\twatcherId"O\n\x18GetWatcherEventsResponse\x123\n\x06events\x18\x01 \x03(\x0b2\x1b.filesystem.FilesystemEventR\x06events"5\n\x14RemoveWatcherRequest\x12\x1d\n\nwatcher_id\x18\x01 \x01(\tR\twatcherId"\x17\n\x15RemoveWatcherResponse*R\n\x08FileType\x12\x19\n\x15FILE_TYPE_UNSPECIFIED\x10\x00\x12\x12\n\x0eFILE_TYPE_FILE\x10\x01\x12\x17\n\x13FILE_TYPE_DIRECTORY\x10\x02*\x98\x01\n\tEventType\x12\x1a\n\x16EVENT_TYPE_UNSPECIFIED\x10\x00\x12\x15\n\x11EVENT_TYPE_CREATE\x10\x01\x12\x14\n\x10EVENT_TYPE_WRITE\x10\x02\x12\x15\n\x11EVENT_TYPE_REMOVE\x10\x03\x12\x15\n\x11EVENT_TYPE_RENAME\x10\x04\x12\x14\n\x10EVENT_TYPE_CHMOD\x10\x052\x9f\x05\n\nFilesystem\x129\n\x04Stat\x12\x17.filesystem.StatRequest\x1a\x18.filesystem.StatResponse\x12B\n\x07MakeDir\x12\x1a.filesystem.MakeDirRequest\x1a\x1b.filesystem.MakeDirResponse\x129\n\x04Move\x12\x17.filesystem.MoveRequest\x1a\x18.filesystem.MoveResponse\x12B\n\x07ListDir\x12\x1a.filesystem.ListDirRequest\x1a\x1b.filesystem.ListDirResponse\x12?\n\x06Remove\x12\x19.filesystem.RemoveRequest\x1a\x1a.filesystem.RemoveResponse\x12G\n\x08WatchDir\x12\x1b.filesystem.WatchDirRequest\x1a\x1c.filesystem.WatchDirResponse0\x01\x12T\n\rCreateWatcher\x12 .filesystem.CreateWatcherRequest\x1a!.filesystem.CreateWatcherResponse\x12]\n\x10GetWatcherEvents\x12#.filesystem.GetWatcherEventsRequest\x1a$.filesystem.GetWatcherEventsResponse\x12T\n\rRemoveWatcher\x12 .filesystem.RemoveWatcherRequest\x1a!.filesystem.RemoveWatcherResponseBi\n\x0ecom.filesystemB\x0fFilesystemProtoP\x01\xa2\x02\x03FXX\xaa\x02\nFilesystem\xca\x02\nFilesystem\xe2\x02\x16Filesystem\\GPBMetadata\xea\x02\nFilesystemb\x06proto3',
+ [
+ timestamp_pb.desc(),
+ ],
+ {
+ "MoveRequest": MoveRequest,
+ "MoveResponse": MoveResponse,
+ "MakeDirRequest": MakeDirRequest,
+ "MakeDirResponse": MakeDirResponse,
+ "RemoveRequest": RemoveRequest,
+ "RemoveResponse": RemoveResponse,
+ "StatRequest": StatRequest,
+ "StatResponse": StatResponse,
+ "EntryInfo": EntryInfo,
+ "ListDirRequest": ListDirRequest,
+ "ListDirResponse": ListDirResponse,
+ "WatchDirRequest": WatchDirRequest,
+ "FilesystemEvent": FilesystemEvent,
+ "WatchDirResponse": WatchDirResponse,
+ "WatchDirResponse.StartEvent": WatchDirResponse.StartEvent,
+ "WatchDirResponse.KeepAlive": WatchDirResponse.KeepAlive,
+ "CreateWatcherRequest": CreateWatcherRequest,
+ "CreateWatcherResponse": CreateWatcherResponse,
+ "GetWatcherEventsRequest": GetWatcherEventsRequest,
+ "GetWatcherEventsResponse": GetWatcherEventsResponse,
+ "RemoveWatcherRequest": RemoveWatcherRequest,
+ "RemoveWatcherResponse": RemoveWatcherResponse,
+ "FileType": FileType,
+ "EventType": EventType,
+ },
+)
+
+
+def desc() -> DescFile:
+ """Returns the descriptor for the file `filesystem/filesystem.proto`."""
+ return _DESC
diff --git a/packages/python-sdk/e2b/envd/filesystem/filesystem_pb2.py b/packages/python-sdk/e2b/envd/filesystem/filesystem_pb2.py
deleted file mode 100644
index f2a37967a..000000000
--- a/packages/python-sdk/e2b/envd/filesystem/filesystem_pb2.py
+++ /dev/null
@@ -1,80 +0,0 @@
-# -*- coding: utf-8 -*-
-# Generated by the protocol buffer compiler. DO NOT EDIT!
-# source: filesystem/filesystem.proto
-# Protobuf Python Version: 5.26.1
-"""Generated protocol buffer code."""
-from google.protobuf import descriptor as _descriptor
-from google.protobuf import descriptor_pool as _descriptor_pool
-from google.protobuf import symbol_database as _symbol_database
-from google.protobuf.internal import builder as _builder
-# @@protoc_insertion_point(imports)
-
-_sym_db = _symbol_database.Default()
-
-
-from google.protobuf import timestamp_pb2 as google_dot_protobuf_dot_timestamp__pb2
-
-
-DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x1b\x66ilesystem/filesystem.proto\x12\nfilesystem\x1a\x1fgoogle/protobuf/timestamp.proto\"G\n\x0bMoveRequest\x12\x16\n\x06source\x18\x01 \x01(\tR\x06source\x12 \n\x0b\x64\x65stination\x18\x02 \x01(\tR\x0b\x64\x65stination\";\n\x0cMoveResponse\x12+\n\x05\x65ntry\x18\x01 \x01(\x0b\x32\x15.filesystem.EntryInfoR\x05\x65ntry\"$\n\x0eMakeDirRequest\x12\x12\n\x04path\x18\x01 \x01(\tR\x04path\">\n\x0fMakeDirResponse\x12+\n\x05\x65ntry\x18\x01 \x01(\x0b\x32\x15.filesystem.EntryInfoR\x05\x65ntry\"#\n\rRemoveRequest\x12\x12\n\x04path\x18\x01 \x01(\tR\x04path\"\x10\n\x0eRemoveResponse\"!\n\x0bStatRequest\x12\x12\n\x04path\x18\x01 \x01(\tR\x04path\";\n\x0cStatResponse\x12+\n\x05\x65ntry\x18\x01 \x01(\x0b\x32\x15.filesystem.EntryInfoR\x05\x65ntry\"\xd1\x03\n\tEntryInfo\x12\x12\n\x04name\x18\x01 \x01(\tR\x04name\x12(\n\x04type\x18\x02 \x01(\x0e\x32\x14.filesystem.FileTypeR\x04type\x12\x12\n\x04path\x18\x03 \x01(\tR\x04path\x12\x12\n\x04size\x18\x04 \x01(\x03R\x04size\x12\x12\n\x04mode\x18\x05 \x01(\rR\x04mode\x12 \n\x0bpermissions\x18\x06 \x01(\tR\x0bpermissions\x12\x14\n\x05owner\x18\x07 \x01(\tR\x05owner\x12\x14\n\x05group\x18\x08 \x01(\tR\x05group\x12?\n\rmodified_time\x18\t \x01(\x0b\x32\x1a.google.protobuf.TimestampR\x0cmodifiedTime\x12*\n\x0esymlink_target\x18\n \x01(\tH\x00R\rsymlinkTarget\x88\x01\x01\x12?\n\x08metadata\x18\x0b \x03(\x0b\x32#.filesystem.EntryInfo.MetadataEntryR\x08metadata\x1a;\n\rMetadataEntry\x12\x10\n\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n\x05value\x18\x02 \x01(\tR\x05value:\x02\x38\x01\x42\x11\n\x0f_symlink_target\":\n\x0eListDirRequest\x12\x12\n\x04path\x18\x01 \x01(\tR\x04path\x12\x14\n\x05\x64\x65pth\x18\x02 \x01(\rR\x05\x64\x65pth\"B\n\x0fListDirResponse\x12/\n\x07\x65ntries\x18\x01 \x03(\x0b\x32\x15.filesystem.EntryInfoR\x07\x65ntries\"\x9a\x01\n\x0fWatchDirRequest\x12\x12\n\x04path\x18\x01 \x01(\tR\x04path\x12\x1c\n\trecursive\x18\x02 \x01(\x08R\trecursive\x12#\n\rinclude_entry\x18\x03 \x01(\x08R\x0cincludeEntry\x12\x30\n\x14\x61llow_network_mounts\x18\x04 \x01(\x08R\x12\x61llowNetworkMounts\"\x8c\x01\n\x0f\x46ilesystemEvent\x12\x12\n\x04name\x18\x01 \x01(\tR\x04name\x12)\n\x04type\x18\x02 \x01(\x0e\x32\x15.filesystem.EventTypeR\x04type\x12\x30\n\x05\x65ntry\x18\x03 \x01(\x0b\x32\x15.filesystem.EntryInfoH\x00R\x05\x65ntry\x88\x01\x01\x42\x08\n\x06_entry\"\xfe\x01\n\x10WatchDirResponse\x12?\n\x05start\x18\x01 \x01(\x0b\x32\'.filesystem.WatchDirResponse.StartEventH\x00R\x05start\x12=\n\nfilesystem\x18\x02 \x01(\x0b\x32\x1b.filesystem.FilesystemEventH\x00R\nfilesystem\x12\x46\n\tkeepalive\x18\x03 \x01(\x0b\x32&.filesystem.WatchDirResponse.KeepAliveH\x00R\tkeepalive\x1a\x0c\n\nStartEvent\x1a\x0b\n\tKeepAliveB\x07\n\x05\x65vent\"\x9f\x01\n\x14\x43reateWatcherRequest\x12\x12\n\x04path\x18\x01 \x01(\tR\x04path\x12\x1c\n\trecursive\x18\x02 \x01(\x08R\trecursive\x12#\n\rinclude_entry\x18\x03 \x01(\x08R\x0cincludeEntry\x12\x30\n\x14\x61llow_network_mounts\x18\x04 \x01(\x08R\x12\x61llowNetworkMounts\"6\n\x15\x43reateWatcherResponse\x12\x1d\n\nwatcher_id\x18\x01 \x01(\tR\twatcherId\"8\n\x17GetWatcherEventsRequest\x12\x1d\n\nwatcher_id\x18\x01 \x01(\tR\twatcherId\"O\n\x18GetWatcherEventsResponse\x12\x33\n\x06\x65vents\x18\x01 \x03(\x0b\x32\x1b.filesystem.FilesystemEventR\x06\x65vents\"5\n\x14RemoveWatcherRequest\x12\x1d\n\nwatcher_id\x18\x01 \x01(\tR\twatcherId\"\x17\n\x15RemoveWatcherResponse*R\n\x08\x46ileType\x12\x19\n\x15\x46ILE_TYPE_UNSPECIFIED\x10\x00\x12\x12\n\x0e\x46ILE_TYPE_FILE\x10\x01\x12\x17\n\x13\x46ILE_TYPE_DIRECTORY\x10\x02*\x98\x01\n\tEventType\x12\x1a\n\x16\x45VENT_TYPE_UNSPECIFIED\x10\x00\x12\x15\n\x11\x45VENT_TYPE_CREATE\x10\x01\x12\x14\n\x10\x45VENT_TYPE_WRITE\x10\x02\x12\x15\n\x11\x45VENT_TYPE_REMOVE\x10\x03\x12\x15\n\x11\x45VENT_TYPE_RENAME\x10\x04\x12\x14\n\x10\x45VENT_TYPE_CHMOD\x10\x05\x32\x9f\x05\n\nFilesystem\x12\x39\n\x04Stat\x12\x17.filesystem.StatRequest\x1a\x18.filesystem.StatResponse\x12\x42\n\x07MakeDir\x12\x1a.filesystem.MakeDirRequest\x1a\x1b.filesystem.MakeDirResponse\x12\x39\n\x04Move\x12\x17.filesystem.MoveRequest\x1a\x18.filesystem.MoveResponse\x12\x42\n\x07ListDir\x12\x1a.filesystem.ListDirRequest\x1a\x1b.filesystem.ListDirResponse\x12?\n\x06Remove\x12\x19.filesystem.RemoveRequest\x1a\x1a.filesystem.RemoveResponse\x12G\n\x08WatchDir\x12\x1b.filesystem.WatchDirRequest\x1a\x1c.filesystem.WatchDirResponse0\x01\x12T\n\rCreateWatcher\x12 .filesystem.CreateWatcherRequest\x1a!.filesystem.CreateWatcherResponse\x12]\n\x10GetWatcherEvents\x12#.filesystem.GetWatcherEventsRequest\x1a$.filesystem.GetWatcherEventsResponse\x12T\n\rRemoveWatcher\x12 .filesystem.RemoveWatcherRequest\x1a!.filesystem.RemoveWatcherResponseBi\n\x0e\x63om.filesystemB\x0f\x46ilesystemProtoP\x01\xa2\x02\x03\x46XX\xaa\x02\nFilesystem\xca\x02\nFilesystem\xe2\x02\x16\x46ilesystem\\GPBMetadata\xea\x02\nFilesystemb\x06proto3')
-
-_globals = globals()
-_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
-_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'filesystem.filesystem_pb2', _globals)
-if not _descriptor._USE_C_DESCRIPTORS:
- _globals['DESCRIPTOR']._loaded_options = None
- _globals['DESCRIPTOR']._serialized_options = b'\n\016com.filesystemB\017FilesystemProtoP\001\242\002\003FXX\252\002\nFilesystem\312\002\nFilesystem\342\002\026Filesystem\\GPBMetadata\352\002\nFilesystem'
- _globals['_ENTRYINFO_METADATAENTRY']._loaded_options = None
- _globals['_ENTRYINFO_METADATAENTRY']._serialized_options = b'8\001'
- _globals['_FILETYPE']._serialized_start=2053
- _globals['_FILETYPE']._serialized_end=2135
- _globals['_EVENTTYPE']._serialized_start=2138
- _globals['_EVENTTYPE']._serialized_end=2290
- _globals['_MOVEREQUEST']._serialized_start=76
- _globals['_MOVEREQUEST']._serialized_end=147
- _globals['_MOVERESPONSE']._serialized_start=149
- _globals['_MOVERESPONSE']._serialized_end=208
- _globals['_MAKEDIRREQUEST']._serialized_start=210
- _globals['_MAKEDIRREQUEST']._serialized_end=246
- _globals['_MAKEDIRRESPONSE']._serialized_start=248
- _globals['_MAKEDIRRESPONSE']._serialized_end=310
- _globals['_REMOVEREQUEST']._serialized_start=312
- _globals['_REMOVEREQUEST']._serialized_end=347
- _globals['_REMOVERESPONSE']._serialized_start=349
- _globals['_REMOVERESPONSE']._serialized_end=365
- _globals['_STATREQUEST']._serialized_start=367
- _globals['_STATREQUEST']._serialized_end=400
- _globals['_STATRESPONSE']._serialized_start=402
- _globals['_STATRESPONSE']._serialized_end=461
- _globals['_ENTRYINFO']._serialized_start=464
- _globals['_ENTRYINFO']._serialized_end=929
- _globals['_ENTRYINFO_METADATAENTRY']._serialized_start=851
- _globals['_ENTRYINFO_METADATAENTRY']._serialized_end=910
- _globals['_LISTDIRREQUEST']._serialized_start=931
- _globals['_LISTDIRREQUEST']._serialized_end=989
- _globals['_LISTDIRRESPONSE']._serialized_start=991
- _globals['_LISTDIRRESPONSE']._serialized_end=1057
- _globals['_WATCHDIRREQUEST']._serialized_start=1060
- _globals['_WATCHDIRREQUEST']._serialized_end=1214
- _globals['_FILESYSTEMEVENT']._serialized_start=1217
- _globals['_FILESYSTEMEVENT']._serialized_end=1357
- _globals['_WATCHDIRRESPONSE']._serialized_start=1360
- _globals['_WATCHDIRRESPONSE']._serialized_end=1614
- _globals['_WATCHDIRRESPONSE_STARTEVENT']._serialized_start=1580
- _globals['_WATCHDIRRESPONSE_STARTEVENT']._serialized_end=1592
- _globals['_WATCHDIRRESPONSE_KEEPALIVE']._serialized_start=1594
- _globals['_WATCHDIRRESPONSE_KEEPALIVE']._serialized_end=1605
- _globals['_CREATEWATCHERREQUEST']._serialized_start=1617
- _globals['_CREATEWATCHERREQUEST']._serialized_end=1776
- _globals['_CREATEWATCHERRESPONSE']._serialized_start=1778
- _globals['_CREATEWATCHERRESPONSE']._serialized_end=1832
- _globals['_GETWATCHEREVENTSREQUEST']._serialized_start=1834
- _globals['_GETWATCHEREVENTSREQUEST']._serialized_end=1890
- _globals['_GETWATCHEREVENTSRESPONSE']._serialized_start=1892
- _globals['_GETWATCHEREVENTSRESPONSE']._serialized_end=1971
- _globals['_REMOVEWATCHERREQUEST']._serialized_start=1973
- _globals['_REMOVEWATCHERREQUEST']._serialized_end=2026
- _globals['_REMOVEWATCHERRESPONSE']._serialized_start=2028
- _globals['_REMOVEWATCHERRESPONSE']._serialized_end=2051
- _globals['_FILESYSTEM']._serialized_start=2293
- _globals['_FILESYSTEM']._serialized_end=2964
-# @@protoc_insertion_point(module_scope)
diff --git a/packages/python-sdk/e2b/envd/filesystem/filesystem_pb2.pyi b/packages/python-sdk/e2b/envd/filesystem/filesystem_pb2.pyi
deleted file mode 100644
index 73ede13a1..000000000
--- a/packages/python-sdk/e2b/envd/filesystem/filesystem_pb2.pyi
+++ /dev/null
@@ -1,272 +0,0 @@
-from google.protobuf import timestamp_pb2 as _timestamp_pb2
-from google.protobuf.internal import containers as _containers
-from google.protobuf.internal import enum_type_wrapper as _enum_type_wrapper
-from google.protobuf import descriptor as _descriptor
-from google.protobuf import message as _message
-from typing import (
- ClassVar as _ClassVar,
- Iterable as _Iterable,
- Mapping as _Mapping,
- Optional as _Optional,
- Union as _Union,
-)
-
-DESCRIPTOR: _descriptor.FileDescriptor
-
-class FileType(int, metaclass=_enum_type_wrapper.EnumTypeWrapper):
- __slots__ = ()
- FILE_TYPE_UNSPECIFIED: _ClassVar[FileType]
- FILE_TYPE_FILE: _ClassVar[FileType]
- FILE_TYPE_DIRECTORY: _ClassVar[FileType]
-
-class EventType(int, metaclass=_enum_type_wrapper.EnumTypeWrapper):
- __slots__ = ()
- EVENT_TYPE_UNSPECIFIED: _ClassVar[EventType]
- EVENT_TYPE_CREATE: _ClassVar[EventType]
- EVENT_TYPE_WRITE: _ClassVar[EventType]
- EVENT_TYPE_REMOVE: _ClassVar[EventType]
- EVENT_TYPE_RENAME: _ClassVar[EventType]
- EVENT_TYPE_CHMOD: _ClassVar[EventType]
-
-FILE_TYPE_UNSPECIFIED: FileType
-FILE_TYPE_FILE: FileType
-FILE_TYPE_DIRECTORY: FileType
-EVENT_TYPE_UNSPECIFIED: EventType
-EVENT_TYPE_CREATE: EventType
-EVENT_TYPE_WRITE: EventType
-EVENT_TYPE_REMOVE: EventType
-EVENT_TYPE_RENAME: EventType
-EVENT_TYPE_CHMOD: EventType
-
-class MoveRequest(_message.Message):
- __slots__ = ("source", "destination")
- SOURCE_FIELD_NUMBER: _ClassVar[int]
- DESTINATION_FIELD_NUMBER: _ClassVar[int]
- source: str
- destination: str
- def __init__(
- self, source: _Optional[str] = ..., destination: _Optional[str] = ...
- ) -> None: ...
-
-class MoveResponse(_message.Message):
- __slots__ = ("entry",)
- ENTRY_FIELD_NUMBER: _ClassVar[int]
- entry: EntryInfo
- def __init__(self, entry: _Optional[_Union[EntryInfo, _Mapping]] = ...) -> None: ...
-
-class MakeDirRequest(_message.Message):
- __slots__ = ("path",)
- PATH_FIELD_NUMBER: _ClassVar[int]
- path: str
- def __init__(self, path: _Optional[str] = ...) -> None: ...
-
-class MakeDirResponse(_message.Message):
- __slots__ = ("entry",)
- ENTRY_FIELD_NUMBER: _ClassVar[int]
- entry: EntryInfo
- def __init__(self, entry: _Optional[_Union[EntryInfo, _Mapping]] = ...) -> None: ...
-
-class RemoveRequest(_message.Message):
- __slots__ = ("path",)
- PATH_FIELD_NUMBER: _ClassVar[int]
- path: str
- def __init__(self, path: _Optional[str] = ...) -> None: ...
-
-class RemoveResponse(_message.Message):
- __slots__ = ()
- def __init__(self) -> None: ...
-
-class StatRequest(_message.Message):
- __slots__ = ("path",)
- PATH_FIELD_NUMBER: _ClassVar[int]
- path: str
- def __init__(self, path: _Optional[str] = ...) -> None: ...
-
-class StatResponse(_message.Message):
- __slots__ = ("entry",)
- ENTRY_FIELD_NUMBER: _ClassVar[int]
- entry: EntryInfo
- def __init__(self, entry: _Optional[_Union[EntryInfo, _Mapping]] = ...) -> None: ...
-
-class EntryInfo(_message.Message):
- __slots__ = (
- "name",
- "type",
- "path",
- "size",
- "mode",
- "permissions",
- "owner",
- "group",
- "modified_time",
- "symlink_target",
- "metadata",
- )
- class MetadataEntry(_message.Message):
- __slots__ = ("key", "value")
- KEY_FIELD_NUMBER: _ClassVar[int]
- VALUE_FIELD_NUMBER: _ClassVar[int]
- key: str
- value: str
- def __init__(
- self, key: _Optional[str] = ..., value: _Optional[str] = ...
- ) -> None: ...
-
- NAME_FIELD_NUMBER: _ClassVar[int]
- TYPE_FIELD_NUMBER: _ClassVar[int]
- PATH_FIELD_NUMBER: _ClassVar[int]
- SIZE_FIELD_NUMBER: _ClassVar[int]
- MODE_FIELD_NUMBER: _ClassVar[int]
- PERMISSIONS_FIELD_NUMBER: _ClassVar[int]
- OWNER_FIELD_NUMBER: _ClassVar[int]
- GROUP_FIELD_NUMBER: _ClassVar[int]
- MODIFIED_TIME_FIELD_NUMBER: _ClassVar[int]
- SYMLINK_TARGET_FIELD_NUMBER: _ClassVar[int]
- METADATA_FIELD_NUMBER: _ClassVar[int]
- name: str
- type: FileType
- path: str
- size: int
- mode: int
- permissions: str
- owner: str
- group: str
- modified_time: _timestamp_pb2.Timestamp
- symlink_target: str
- metadata: _containers.ScalarMap[str, str]
- def __init__(
- self,
- name: _Optional[str] = ...,
- type: _Optional[_Union[FileType, str]] = ...,
- path: _Optional[str] = ...,
- size: _Optional[int] = ...,
- mode: _Optional[int] = ...,
- permissions: _Optional[str] = ...,
- owner: _Optional[str] = ...,
- group: _Optional[str] = ...,
- modified_time: _Optional[_Union[_timestamp_pb2.Timestamp, _Mapping]] = ...,
- symlink_target: _Optional[str] = ...,
- metadata: _Optional[_Mapping[str, str]] = ...,
- ) -> None: ...
-
-class ListDirRequest(_message.Message):
- __slots__ = ("path", "depth")
- PATH_FIELD_NUMBER: _ClassVar[int]
- DEPTH_FIELD_NUMBER: _ClassVar[int]
- path: str
- depth: int
- def __init__(
- self, path: _Optional[str] = ..., depth: _Optional[int] = ...
- ) -> None: ...
-
-class ListDirResponse(_message.Message):
- __slots__ = ("entries",)
- ENTRIES_FIELD_NUMBER: _ClassVar[int]
- entries: _containers.RepeatedCompositeFieldContainer[EntryInfo]
- def __init__(
- self, entries: _Optional[_Iterable[_Union[EntryInfo, _Mapping]]] = ...
- ) -> None: ...
-
-class WatchDirRequest(_message.Message):
- __slots__ = ("path", "recursive", "include_entry", "allow_network_mounts")
- PATH_FIELD_NUMBER: _ClassVar[int]
- RECURSIVE_FIELD_NUMBER: _ClassVar[int]
- INCLUDE_ENTRY_FIELD_NUMBER: _ClassVar[int]
- ALLOW_NETWORK_MOUNTS_FIELD_NUMBER: _ClassVar[int]
- path: str
- recursive: bool
- include_entry: bool
- allow_network_mounts: bool
- def __init__(
- self,
- path: _Optional[str] = ...,
- recursive: bool = ...,
- include_entry: bool = ...,
- allow_network_mounts: bool = ...,
- ) -> None: ...
-
-class FilesystemEvent(_message.Message):
- __slots__ = ("name", "type", "entry")
- NAME_FIELD_NUMBER: _ClassVar[int]
- TYPE_FIELD_NUMBER: _ClassVar[int]
- ENTRY_FIELD_NUMBER: _ClassVar[int]
- name: str
- type: EventType
- entry: EntryInfo
- def __init__(
- self,
- name: _Optional[str] = ...,
- type: _Optional[_Union[EventType, str]] = ...,
- entry: _Optional[_Union[EntryInfo, _Mapping]] = ...,
- ) -> None: ...
-
-class WatchDirResponse(_message.Message):
- __slots__ = ("start", "filesystem", "keepalive")
- class StartEvent(_message.Message):
- __slots__ = ()
- def __init__(self) -> None: ...
-
- class KeepAlive(_message.Message):
- __slots__ = ()
- def __init__(self) -> None: ...
-
- START_FIELD_NUMBER: _ClassVar[int]
- FILESYSTEM_FIELD_NUMBER: _ClassVar[int]
- KEEPALIVE_FIELD_NUMBER: _ClassVar[int]
- start: WatchDirResponse.StartEvent
- filesystem: FilesystemEvent
- keepalive: WatchDirResponse.KeepAlive
- def __init__(
- self,
- start: _Optional[_Union[WatchDirResponse.StartEvent, _Mapping]] = ...,
- filesystem: _Optional[_Union[FilesystemEvent, _Mapping]] = ...,
- keepalive: _Optional[_Union[WatchDirResponse.KeepAlive, _Mapping]] = ...,
- ) -> None: ...
-
-class CreateWatcherRequest(_message.Message):
- __slots__ = ("path", "recursive", "include_entry", "allow_network_mounts")
- PATH_FIELD_NUMBER: _ClassVar[int]
- RECURSIVE_FIELD_NUMBER: _ClassVar[int]
- INCLUDE_ENTRY_FIELD_NUMBER: _ClassVar[int]
- ALLOW_NETWORK_MOUNTS_FIELD_NUMBER: _ClassVar[int]
- path: str
- recursive: bool
- include_entry: bool
- allow_network_mounts: bool
- def __init__(
- self,
- path: _Optional[str] = ...,
- recursive: bool = ...,
- include_entry: bool = ...,
- allow_network_mounts: bool = ...,
- ) -> None: ...
-
-class CreateWatcherResponse(_message.Message):
- __slots__ = ("watcher_id",)
- WATCHER_ID_FIELD_NUMBER: _ClassVar[int]
- watcher_id: str
- def __init__(self, watcher_id: _Optional[str] = ...) -> None: ...
-
-class GetWatcherEventsRequest(_message.Message):
- __slots__ = ("watcher_id",)
- WATCHER_ID_FIELD_NUMBER: _ClassVar[int]
- watcher_id: str
- def __init__(self, watcher_id: _Optional[str] = ...) -> None: ...
-
-class GetWatcherEventsResponse(_message.Message):
- __slots__ = ("events",)
- EVENTS_FIELD_NUMBER: _ClassVar[int]
- events: _containers.RepeatedCompositeFieldContainer[FilesystemEvent]
- def __init__(
- self, events: _Optional[_Iterable[_Union[FilesystemEvent, _Mapping]]] = ...
- ) -> None: ...
-
-class RemoveWatcherRequest(_message.Message):
- __slots__ = ("watcher_id",)
- WATCHER_ID_FIELD_NUMBER: _ClassVar[int]
- watcher_id: str
- def __init__(self, watcher_id: _Optional[str] = ...) -> None: ...
-
-class RemoveWatcherResponse(_message.Message):
- __slots__ = ()
- def __init__(self) -> None: ...
diff --git a/packages/python-sdk/e2b/envd/interceptors.py b/packages/python-sdk/e2b/envd/interceptors.py
new file mode 100644
index 000000000..396bf650c
--- /dev/null
+++ b/packages/python-sdk/e2b/envd/interceptors.py
@@ -0,0 +1,223 @@
+"""connectrpc interceptors for envd RPC calls.
+
+Each interceptor implements both the sync and async connectrpc interceptor
+protocols so one instance works with either client flavor.
+"""
+
+import logging
+from typing import (
+ AsyncIterator,
+ Awaitable,
+ Callable,
+ Iterator,
+ Mapping,
+ Optional,
+ TypeVar,
+)
+
+from connectrpc.errors import ConnectError
+from connectrpc.request import RequestContext
+
+from e2b.connection_config import ConnectionConfig
+
+REQ = TypeVar("REQ")
+RES = TypeVar("RES")
+
+
+def _close_stream(stream: Iterator) -> None:
+ """Close an inner server stream if it supports it (connectrpc streams are
+ real generators; the protocols only promise ``Iterator``)."""
+ close = getattr(stream, "close", None)
+ if close is not None:
+ close()
+
+
+async def _aclose_stream(stream: AsyncIterator) -> None:
+ """Async variant of :func:`_close_stream`."""
+ aclose = getattr(stream, "aclose", None)
+ if aclose is not None:
+ await aclose()
+
+
+class DefaultHeadersInterceptor:
+ """Add default headers (User-Agent, sandbox access token) to every RPC.
+
+ Per-call headers win.
+
+ Implemented as the per-method-kind interceptor protocols rather than the
+ simpler connectrpc metadata protocol: connectrpc wraps metadata
+ interceptors around server streams in a generator that doesn't propagate
+ ``close()``/``aclose()`` to the inner stream, which would defer the
+ RST_STREAM the SDK relies on for early stream cancellation to the
+ async-generator GC finalizer. Returning ``call_next``'s iterator directly
+ adds no such layer.
+ """
+
+ def __init__(self, headers: Mapping[str, str]):
+ self._headers = headers
+
+ def _apply(self, ctx: RequestContext) -> None:
+ for key, value in self._headers.items():
+ if key not in ctx.request_headers:
+ ctx.request_headers[key] = value
+
+ def intercept_unary_sync(
+ self,
+ call_next: Callable[[REQ, RequestContext], RES],
+ request: REQ,
+ ctx: RequestContext,
+ ) -> RES:
+ self._apply(ctx)
+ return call_next(request, ctx)
+
+ async def intercept_unary(
+ self,
+ call_next: Callable[[REQ, RequestContext], Awaitable[RES]],
+ request: REQ,
+ ctx: RequestContext,
+ ) -> RES:
+ self._apply(ctx)
+ return await call_next(request, ctx)
+
+ def intercept_server_stream_sync(
+ self,
+ call_next: Callable[[REQ, RequestContext], Iterator[RES]],
+ request: REQ,
+ ctx: RequestContext,
+ ) -> Iterator[RES]:
+ self._apply(ctx)
+ return call_next(request, ctx)
+
+ def intercept_server_stream(
+ self,
+ call_next: Callable[[REQ, RequestContext], AsyncIterator[RES]],
+ request: REQ,
+ ctx: RequestContext,
+ ) -> AsyncIterator[RES]:
+ self._apply(ctx)
+ return call_next(request, ctx)
+
+
+class LoggingInterceptor:
+ """Log RPC requests, responses, and stream messages to the user's logger.
+
+ Requests and successful responses log at INFO, failures at ERROR and each
+ streamed message at DEBUG — mirroring the httpx event hooks used for the
+ REST API and file transfer requests.
+
+ Upstreamed to pyqwest as a logging middleware
+ (https://github.com/curioswitch/pyqwest/pull/192); this interceptor stays
+ until that ships in a pyqwest release the SDK can depend on.
+ """
+
+ def __init__(self, logger: logging.Logger, base_url: str):
+ self._logger = logger
+ self._base_url = base_url
+
+ def _url(self, ctx: RequestContext) -> str:
+ return f"{self._base_url}/{ctx.method.service_name}/{ctx.method.name}"
+
+ def _log_request(self, ctx: RequestContext) -> None:
+ self._logger.info(f"Request: POST {self._url(ctx)}")
+
+ def _log_response(self, ctx: RequestContext, error: Optional[Exception]) -> None:
+ if error is None:
+ self._logger.info(f"Response: ok {self._url(ctx)}")
+ else:
+ code = error.code.name.lower() if isinstance(error, ConnectError) else error
+ self._logger.error(f"Response: {code} {self._url(ctx)}")
+
+ def intercept_unary_sync(
+ self,
+ call_next: Callable[[REQ, RequestContext], RES],
+ request: REQ,
+ ctx: RequestContext,
+ ) -> RES:
+ self._log_request(ctx)
+ try:
+ response = call_next(request, ctx)
+ except Exception as e:
+ self._log_response(ctx, e)
+ raise
+ self._log_response(ctx, None)
+ return response
+
+ async def intercept_unary(
+ self,
+ call_next: Callable[[REQ, RequestContext], Awaitable[RES]],
+ request: REQ,
+ ctx: RequestContext,
+ ) -> RES:
+ self._log_request(ctx)
+ try:
+ response = await call_next(request, ctx)
+ except Exception as e:
+ self._log_response(ctx, e)
+ raise
+ self._log_response(ctx, None)
+ return response
+
+ def intercept_server_stream_sync(
+ self,
+ call_next: Callable[[REQ, RequestContext], Iterator[RES]],
+ request: REQ,
+ ctx: RequestContext,
+ ) -> Iterator[RES]:
+ self._log_request(ctx)
+ inner = call_next(request, ctx)
+ # Hoisted out of the loop and %-formatted lazily: this logs once per
+ # streamed message — the per-stdout-chunk hot path.
+ url = self._url(ctx)
+ try:
+ for message in inner:
+ self._logger.debug("Response stream: %s", url)
+ yield message
+ except Exception as e:
+ self._log_response(ctx, e)
+ raise
+ finally:
+ # Propagate early close: a bare `for ... yield` would strand the
+ # inner stream when the consumer calls close(), deferring the
+ # transport's stream reset to garbage collection.
+ _close_stream(inner)
+ self._log_response(ctx, None)
+
+ async def intercept_server_stream(
+ self,
+ call_next: Callable[[REQ, RequestContext], AsyncIterator[RES]],
+ request: REQ,
+ ctx: RequestContext,
+ ) -> AsyncIterator[RES]:
+ self._log_request(ctx)
+ inner = call_next(request, ctx)
+ # Hoisted out of the loop and %-formatted lazily: this logs once per
+ # streamed message — the per-stdout-chunk hot path.
+ url = self._url(ctx)
+ try:
+ async for message in inner:
+ self._logger.debug("Response stream: %s", url)
+ yield message
+ except Exception as e:
+ self._log_response(ctx, e)
+ raise
+ finally:
+ # Propagate early close: a bare `async for ... yield` would strand
+ # the inner stream when the consumer calls aclose(), deferring the
+ # transport's stream reset to the async-generator GC finalizer.
+ await _aclose_stream(inner)
+ self._log_response(ctx, None)
+
+
+def build_interceptors(config: ConnectionConfig, base_url: str) -> list:
+ # Connection retries live below connectrpc, in the pyqwest transport
+ # middleware (`ConnectionRetryTransport` in client_sync/client_async),
+ # not in an interceptor.
+ #
+ # Every interceptor here either adds no generator layer around server
+ # streams or explicitly propagates close()/aclose() to the inner stream —
+ # the SDK relies on closing a stream early to reset it on the shared
+ # HTTP/2 connection (see `as_stream` in client_sync/client_async).
+ interceptors: list = [DefaultHeadersInterceptor(config.sandbox_headers)]
+ if config.logger is not None:
+ interceptors.append(LoggingInterceptor(config.logger, base_url))
+ return interceptors
diff --git a/packages/python-sdk/e2b/envd/process/__init__.py b/packages/python-sdk/e2b/envd/process/__init__.py
new file mode 100644
index 000000000..9d48db4f9
--- /dev/null
+++ b/packages/python-sdk/e2b/envd/process/__init__.py
@@ -0,0 +1 @@
+from __future__ import annotations
diff --git a/packages/python-sdk/e2b/envd/process/process_connect.py b/packages/python-sdk/e2b/envd/process/process_connect.py
index dc09fbe69..b7b62f935 100644
--- a/packages/python-sdk/e2b/envd/process/process_connect.py
+++ b/packages/python-sdk/e2b/envd/process/process_connect.py
@@ -1,174 +1,603 @@
-# Code generated by protoc-gen-connect-python 0.1.0.dev2, DO NOT EDIT.
-from typing import Any, Generator, Coroutine, AsyncGenerator, Optional
-from httpcore import ConnectionPool, AsyncConnectionPool
+# Generated from process/process.proto. DO NOT EDIT.
+# Generated by protoc-gen-connectrpc-py v0.11.1 with parameter "".
+# ruff: noqa: PGH004
+# ruff: noqa
+# fmt: off
-import e2b_connect as connect
+from __future__ import annotations
-from e2b.envd.process import process_pb2 as process_dot_process__pb2
+from typing import Protocol, TYPE_CHECKING
-ProcessName = "process.Process"
+from connectrpc.client import ConnectClient, ConnectClientSync
+from connectrpc.code import Code
+from connectrpc.errors import ConnectError
+from connectrpc.method import IdempotencyLevel, MethodInfo
+from connectrpc.server import ConnectASGIApplication, ConnectWSGIApplication, Endpoint, EndpointSync
+from .process_pb import CloseStdinRequest, CloseStdinResponse, ConnectRequest, ConnectResponse, ListRequest, ListResponse, SendInputRequest, SendInputResponse, SendSignalRequest, SendSignalResponse, StartRequest, StartResponse, StreamInputRequest, StreamInputResponse, UpdateRequest, UpdateResponse
-class ProcessClient:
+if TYPE_CHECKING:
+ from collections.abc import AsyncGenerator, AsyncIterator, Iterable, Iterator, Mapping
+
+ from connectrpc.codec import Codec
+ from connectrpc.compression import Compression
+ from connectrpc.interceptor import Interceptor, InterceptorSync
+ from connectrpc.request import Headers, RequestContext
+
+
+class Process(Protocol):
+ async def list(self, request: ListRequest, ctx: RequestContext[ListRequest, ListResponse]) -> ListResponse:
+ raise ConnectError(Code.UNIMPLEMENTED, 'Not implemented')
+
+ def connect(self, request: ConnectRequest, ctx: RequestContext[ConnectRequest, ConnectResponse]) -> AsyncIterator[ConnectResponse]:
+ raise ConnectError(Code.UNIMPLEMENTED, 'Not implemented')
+
+ def start(self, request: StartRequest, ctx: RequestContext[StartRequest, StartResponse]) -> AsyncIterator[StartResponse]:
+ raise ConnectError(Code.UNIMPLEMENTED, 'Not implemented')
+
+ async def update(self, request: UpdateRequest, ctx: RequestContext[UpdateRequest, UpdateResponse]) -> UpdateResponse:
+ raise ConnectError(Code.UNIMPLEMENTED, 'Not implemented')
+
+ async def stream_input(self, request: AsyncIterator[StreamInputRequest], ctx: RequestContext[StreamInputRequest, StreamInputResponse]) -> StreamInputResponse:
+ raise ConnectError(Code.UNIMPLEMENTED, 'Not implemented')
+
+ async def send_input(self, request: SendInputRequest, ctx: RequestContext[SendInputRequest, SendInputResponse]) -> SendInputResponse:
+ raise ConnectError(Code.UNIMPLEMENTED, 'Not implemented')
+
+ async def send_signal(self, request: SendSignalRequest, ctx: RequestContext[SendSignalRequest, SendSignalResponse]) -> SendSignalResponse:
+ raise ConnectError(Code.UNIMPLEMENTED, 'Not implemented')
+
+ async def close_stdin(self, request: CloseStdinRequest, ctx: RequestContext[CloseStdinRequest, CloseStdinResponse]) -> CloseStdinResponse:
+ raise ConnectError(Code.UNIMPLEMENTED, 'Not implemented')
+
+
+class ProcessASGIApplication(ConnectASGIApplication[Process]):
def __init__(
self,
- base_url: str,
- *,
- pool: Optional[ConnectionPool] = None,
- async_pool: Optional[AsyncConnectionPool] = None,
- compressor=None,
- json=False,
- **opts,
- ):
- self._list = connect.Client(
- pool=pool,
- async_pool=async_pool,
- url=f"{base_url}/{ProcessName}/List",
- response_type=process_dot_process__pb2.ListResponse,
- compressor=compressor,
- json=json,
- **opts,
- )
- self._connect = connect.Client(
- pool=pool,
- async_pool=async_pool,
- url=f"{base_url}/{ProcessName}/Connect",
- response_type=process_dot_process__pb2.ConnectResponse,
- compressor=compressor,
- json=json,
- **opts,
- )
- self._start = connect.Client(
- pool=pool,
- async_pool=async_pool,
- url=f"{base_url}/{ProcessName}/Start",
- response_type=process_dot_process__pb2.StartResponse,
- compressor=compressor,
- json=json,
- **opts,
- )
- self._update = connect.Client(
- pool=pool,
- async_pool=async_pool,
- url=f"{base_url}/{ProcessName}/Update",
- response_type=process_dot_process__pb2.UpdateResponse,
- compressor=compressor,
- json=json,
- **opts,
- )
- self._stream_input = connect.Client(
- pool=pool,
- async_pool=async_pool,
- url=f"{base_url}/{ProcessName}/StreamInput",
- response_type=process_dot_process__pb2.StreamInputResponse,
- compressor=compressor,
- json=json,
- **opts,
- )
- self._send_input = connect.Client(
- pool=pool,
- async_pool=async_pool,
- url=f"{base_url}/{ProcessName}/SendInput",
- response_type=process_dot_process__pb2.SendInputResponse,
- compressor=compressor,
- json=json,
- **opts,
- )
- self._send_signal = connect.Client(
- pool=pool,
- async_pool=async_pool,
- url=f"{base_url}/{ProcessName}/SendSignal",
- response_type=process_dot_process__pb2.SendSignalResponse,
- compressor=compressor,
- json=json,
- **opts,
- )
- self._close_stdin = connect.Client(
- pool=pool,
- async_pool=async_pool,
- url=f"{base_url}/{ProcessName}/CloseStdin",
- response_type=process_dot_process__pb2.CloseStdinResponse,
- compressor=compressor,
- json=json,
- **opts,
+ service: Process | AsyncGenerator[Process],
+ *,
+ interceptors: Iterable[Interceptor] = (),
+ read_max_bytes: int | None = None,
+ compressions: Iterable[Compression] | None = None,
+ codecs: Iterable[Codec] | None = None,
+ ) -> None:
+ super().__init__(
+ service=service,
+ endpoints=lambda svc: {
+ "/process.Process/List": Endpoint.unary(
+ method=MethodInfo(
+ name="List",
+ service_name="process.Process",
+ input=ListRequest,
+ output=ListResponse,
+ idempotency_level=IdempotencyLevel.UNKNOWN,
+ ),
+ function=svc.list,
+ ),
+ "/process.Process/Connect": Endpoint.server_stream(
+ method=MethodInfo(
+ name="Connect",
+ service_name="process.Process",
+ input=ConnectRequest,
+ output=ConnectResponse,
+ idempotency_level=IdempotencyLevel.UNKNOWN,
+ ),
+ function=svc.connect,
+ ),
+ "/process.Process/Start": Endpoint.server_stream(
+ method=MethodInfo(
+ name="Start",
+ service_name="process.Process",
+ input=StartRequest,
+ output=StartResponse,
+ idempotency_level=IdempotencyLevel.UNKNOWN,
+ ),
+ function=svc.start,
+ ),
+ "/process.Process/Update": Endpoint.unary(
+ method=MethodInfo(
+ name="Update",
+ service_name="process.Process",
+ input=UpdateRequest,
+ output=UpdateResponse,
+ idempotency_level=IdempotencyLevel.UNKNOWN,
+ ),
+ function=svc.update,
+ ),
+ "/process.Process/StreamInput": Endpoint.client_stream(
+ method=MethodInfo(
+ name="StreamInput",
+ service_name="process.Process",
+ input=StreamInputRequest,
+ output=StreamInputResponse,
+ idempotency_level=IdempotencyLevel.UNKNOWN,
+ ),
+ function=svc.stream_input,
+ ),
+ "/process.Process/SendInput": Endpoint.unary(
+ method=MethodInfo(
+ name="SendInput",
+ service_name="process.Process",
+ input=SendInputRequest,
+ output=SendInputResponse,
+ idempotency_level=IdempotencyLevel.UNKNOWN,
+ ),
+ function=svc.send_input,
+ ),
+ "/process.Process/SendSignal": Endpoint.unary(
+ method=MethodInfo(
+ name="SendSignal",
+ service_name="process.Process",
+ input=SendSignalRequest,
+ output=SendSignalResponse,
+ idempotency_level=IdempotencyLevel.UNKNOWN,
+ ),
+ function=svc.send_signal,
+ ),
+ "/process.Process/CloseStdin": Endpoint.unary(
+ method=MethodInfo(
+ name="CloseStdin",
+ service_name="process.Process",
+ input=CloseStdinRequest,
+ output=CloseStdinResponse,
+ idempotency_level=IdempotencyLevel.UNKNOWN,
+ ),
+ function=svc.close_stdin,
+ ),
+ },
+ interceptors=interceptors,
+ read_max_bytes=read_max_bytes,
+ compressions=compressions,
+ codecs=codecs,
)
- def list(
- self, req: process_dot_process__pb2.ListRequest, **opts
- ) -> process_dot_process__pb2.ListResponse:
- return self._list.call_unary(req, **opts)
+ @property
+ def path(self) -> str:
+ """Returns the URL path to mount the application to when serving multiple applications."""
+ return "/process.Process"
- def alist(
- self, req: process_dot_process__pb2.ListRequest, **opts
- ) -> Coroutine[Any, Any, process_dot_process__pb2.ListResponse]:
- return self._list.acall_unary(req, **opts)
- def connect(
- self, req: process_dot_process__pb2.ConnectRequest, **opts
- ) -> Generator[process_dot_process__pb2.ConnectResponse, Any, None]:
- return self._connect.call_server_stream(req, **opts)
+class ProcessClient(ConnectClient):
+ async def list(
+ self,
+ request: ListRequest,
+ *,
+ headers: Headers | Mapping[str, str] | None = None,
+ timeout_ms: int | None = None,
+ ) -> ListResponse:
+ return await self.execute_unary(
+ request=request,
+ method=MethodInfo(
+ name="List",
+ service_name="process.Process",
+ input=ListRequest,
+ output=ListResponse,
+ idempotency_level=IdempotencyLevel.UNKNOWN,
+ ),
+ headers=headers,
+ timeout_ms=timeout_ms,
+ )
- def aconnect(
- self, req: process_dot_process__pb2.ConnectRequest, **opts
- ) -> AsyncGenerator[process_dot_process__pb2.ConnectResponse, Any]:
- return self._connect.acall_server_stream(req, **opts)
+ def connect(
+ self,
+ request: ConnectRequest,
+ *,
+ headers: Headers | Mapping[str, str] | None = None,
+ timeout_ms: int | None = None,
+ ) -> AsyncIterator[ConnectResponse]:
+ return self.execute_server_stream(
+ request=request,
+ method=MethodInfo(
+ name="Connect",
+ service_name="process.Process",
+ input=ConnectRequest,
+ output=ConnectResponse,
+ idempotency_level=IdempotencyLevel.UNKNOWN,
+ ),
+ headers=headers,
+ timeout_ms=timeout_ms,
+ )
def start(
- self, req: process_dot_process__pb2.StartRequest, **opts
- ) -> Generator[process_dot_process__pb2.StartResponse, Any, None]:
- return self._start.call_server_stream(req, **opts)
+ self,
+ request: StartRequest,
+ *,
+ headers: Headers | Mapping[str, str] | None = None,
+ timeout_ms: int | None = None,
+ ) -> AsyncIterator[StartResponse]:
+ return self.execute_server_stream(
+ request=request,
+ method=MethodInfo(
+ name="Start",
+ service_name="process.Process",
+ input=StartRequest,
+ output=StartResponse,
+ idempotency_level=IdempotencyLevel.UNKNOWN,
+ ),
+ headers=headers,
+ timeout_ms=timeout_ms,
+ )
- def astart(
- self, req: process_dot_process__pb2.StartRequest, **opts
- ) -> AsyncGenerator[process_dot_process__pb2.StartResponse, Any]:
- return self._start.acall_server_stream(req, **opts)
+ async def update(
+ self,
+ request: UpdateRequest,
+ *,
+ headers: Headers | Mapping[str, str] | None = None,
+ timeout_ms: int | None = None,
+ ) -> UpdateResponse:
+ return await self.execute_unary(
+ request=request,
+ method=MethodInfo(
+ name="Update",
+ service_name="process.Process",
+ input=UpdateRequest,
+ output=UpdateResponse,
+ idempotency_level=IdempotencyLevel.UNKNOWN,
+ ),
+ headers=headers,
+ timeout_ms=timeout_ms,
+ )
- def update(
- self, req: process_dot_process__pb2.UpdateRequest, **opts
- ) -> process_dot_process__pb2.UpdateResponse:
- return self._update.call_unary(req, **opts)
+ async def stream_input(
+ self,
+ request: AsyncIterator[StreamInputRequest],
+ *,
+ headers: Headers | Mapping[str, str] | None = None,
+ timeout_ms: int | None = None,
+ ) -> StreamInputResponse:
+ return await self.execute_client_stream(
+ request=request,
+ method=MethodInfo(
+ name="StreamInput",
+ service_name="process.Process",
+ input=StreamInputRequest,
+ output=StreamInputResponse,
+ idempotency_level=IdempotencyLevel.UNKNOWN,
+ ),
+ headers=headers,
+ timeout_ms=timeout_ms,
+ )
- def aupdate(
- self, req: process_dot_process__pb2.UpdateRequest, **opts
- ) -> Coroutine[Any, Any, process_dot_process__pb2.UpdateResponse]:
- return self._update.acall_unary(req, **opts)
+ async def send_input(
+ self,
+ request: SendInputRequest,
+ *,
+ headers: Headers | Mapping[str, str] | None = None,
+ timeout_ms: int | None = None,
+ ) -> SendInputResponse:
+ return await self.execute_unary(
+ request=request,
+ method=MethodInfo(
+ name="SendInput",
+ service_name="process.Process",
+ input=SendInputRequest,
+ output=SendInputResponse,
+ idempotency_level=IdempotencyLevel.UNKNOWN,
+ ),
+ headers=headers,
+ timeout_ms=timeout_ms,
+ )
- def stream_input(
- self, req: process_dot_process__pb2.StreamInputRequest, **opts
- ) -> process_dot_process__pb2.StreamInputResponse:
- return self._stream_input.call_client_stream(req, **opts)
+ async def send_signal(
+ self,
+ request: SendSignalRequest,
+ *,
+ headers: Headers | Mapping[str, str] | None = None,
+ timeout_ms: int | None = None,
+ ) -> SendSignalResponse:
+ return await self.execute_unary(
+ request=request,
+ method=MethodInfo(
+ name="SendSignal",
+ service_name="process.Process",
+ input=SendSignalRequest,
+ output=SendSignalResponse,
+ idempotency_level=IdempotencyLevel.UNKNOWN,
+ ),
+ headers=headers,
+ timeout_ms=timeout_ms,
+ )
- def astream_input(
- self, req: process_dot_process__pb2.StreamInputRequest, **opts
- ) -> Coroutine[Any, Any, process_dot_process__pb2.StreamInputResponse]:
- return self._stream_input.acall_client_stream(req, **opts)
+ async def close_stdin(
+ self,
+ request: CloseStdinRequest,
+ *,
+ headers: Headers | Mapping[str, str] | None = None,
+ timeout_ms: int | None = None,
+ ) -> CloseStdinResponse:
+ return await self.execute_unary(
+ request=request,
+ method=MethodInfo(
+ name="CloseStdin",
+ service_name="process.Process",
+ input=CloseStdinRequest,
+ output=CloseStdinResponse,
+ idempotency_level=IdempotencyLevel.UNKNOWN,
+ ),
+ headers=headers,
+ timeout_ms=timeout_ms,
+ )
- def send_input(
- self, req: process_dot_process__pb2.SendInputRequest, **opts
- ) -> process_dot_process__pb2.SendInputResponse:
- return self._send_input.call_unary(req, **opts)
+class ProcessSync(Protocol):
+ def list(self, request: ListRequest, ctx: RequestContext[ListRequest, ListResponse]) -> ListResponse:
+ raise ConnectError(Code.UNIMPLEMENTED, 'Not implemented')
- def asend_input(
- self, req: process_dot_process__pb2.SendInputRequest, **opts
- ) -> Coroutine[Any, Any, process_dot_process__pb2.SendInputResponse]:
- return self._send_input.acall_unary(req, **opts)
+ def connect(self, request: ConnectRequest, ctx: RequestContext[ConnectRequest, ConnectResponse]) -> Iterator[ConnectResponse]:
+ raise ConnectError(Code.UNIMPLEMENTED, 'Not implemented')
- def send_signal(
- self, req: process_dot_process__pb2.SendSignalRequest, **opts
- ) -> process_dot_process__pb2.SendSignalResponse:
- return self._send_signal.call_unary(req, **opts)
+ def start(self, request: StartRequest, ctx: RequestContext[StartRequest, StartResponse]) -> Iterator[StartResponse]:
+ raise ConnectError(Code.UNIMPLEMENTED, 'Not implemented')
+
+ def update(self, request: UpdateRequest, ctx: RequestContext[UpdateRequest, UpdateResponse]) -> UpdateResponse:
+ raise ConnectError(Code.UNIMPLEMENTED, 'Not implemented')
+
+ def stream_input(self, request: Iterator[StreamInputRequest], ctx: RequestContext[StreamInputRequest, StreamInputResponse]) -> StreamInputResponse:
+ raise ConnectError(Code.UNIMPLEMENTED, 'Not implemented')
+
+ def send_input(self, request: SendInputRequest, ctx: RequestContext[SendInputRequest, SendInputResponse]) -> SendInputResponse:
+ raise ConnectError(Code.UNIMPLEMENTED, 'Not implemented')
+
+ def send_signal(self, request: SendSignalRequest, ctx: RequestContext[SendSignalRequest, SendSignalResponse]) -> SendSignalResponse:
+ raise ConnectError(Code.UNIMPLEMENTED, 'Not implemented')
+
+ def close_stdin(self, request: CloseStdinRequest, ctx: RequestContext[CloseStdinRequest, CloseStdinResponse]) -> CloseStdinResponse:
+ raise ConnectError(Code.UNIMPLEMENTED, 'Not implemented')
+
+
+class ProcessWSGIApplication(ConnectWSGIApplication):
+ def __init__(
+ self,
+ service: ProcessSync,
+ interceptors: Iterable[InterceptorSync] = (),
+ read_max_bytes: int | None = None,
+ compressions: Iterable[Compression] | None = None,
+ codecs: Iterable[Codec] | None = None,
+ ) -> None:
+ super().__init__(
+ endpoints={
+ "/process.Process/List": EndpointSync.unary(
+ method=MethodInfo(
+ name="List",
+ service_name="process.Process",
+ input=ListRequest,
+ output=ListResponse,
+ idempotency_level=IdempotencyLevel.UNKNOWN,
+ ),
+ function=service.list,
+ ),
+ "/process.Process/Connect": EndpointSync.server_stream(
+ method=MethodInfo(
+ name="Connect",
+ service_name="process.Process",
+ input=ConnectRequest,
+ output=ConnectResponse,
+ idempotency_level=IdempotencyLevel.UNKNOWN,
+ ),
+ function=service.connect,
+ ),
+ "/process.Process/Start": EndpointSync.server_stream(
+ method=MethodInfo(
+ name="Start",
+ service_name="process.Process",
+ input=StartRequest,
+ output=StartResponse,
+ idempotency_level=IdempotencyLevel.UNKNOWN,
+ ),
+ function=service.start,
+ ),
+ "/process.Process/Update": EndpointSync.unary(
+ method=MethodInfo(
+ name="Update",
+ service_name="process.Process",
+ input=UpdateRequest,
+ output=UpdateResponse,
+ idempotency_level=IdempotencyLevel.UNKNOWN,
+ ),
+ function=service.update,
+ ),
+ "/process.Process/StreamInput": EndpointSync.client_stream(
+ method=MethodInfo(
+ name="StreamInput",
+ service_name="process.Process",
+ input=StreamInputRequest,
+ output=StreamInputResponse,
+ idempotency_level=IdempotencyLevel.UNKNOWN,
+ ),
+ function=service.stream_input,
+ ),
+ "/process.Process/SendInput": EndpointSync.unary(
+ method=MethodInfo(
+ name="SendInput",
+ service_name="process.Process",
+ input=SendInputRequest,
+ output=SendInputResponse,
+ idempotency_level=IdempotencyLevel.UNKNOWN,
+ ),
+ function=service.send_input,
+ ),
+ "/process.Process/SendSignal": EndpointSync.unary(
+ method=MethodInfo(
+ name="SendSignal",
+ service_name="process.Process",
+ input=SendSignalRequest,
+ output=SendSignalResponse,
+ idempotency_level=IdempotencyLevel.UNKNOWN,
+ ),
+ function=service.send_signal,
+ ),
+ "/process.Process/CloseStdin": EndpointSync.unary(
+ method=MethodInfo(
+ name="CloseStdin",
+ service_name="process.Process",
+ input=CloseStdinRequest,
+ output=CloseStdinResponse,
+ idempotency_level=IdempotencyLevel.UNKNOWN,
+ ),
+ function=service.close_stdin,
+ ),
+ },
+ interceptors=interceptors,
+ read_max_bytes=read_max_bytes,
+ compressions=compressions,
+ codecs=codecs,
+ )
- def asend_signal(
- self, req: process_dot_process__pb2.SendSignalRequest, **opts
- ) -> Coroutine[Any, Any, process_dot_process__pb2.SendSignalResponse]:
- return self._send_signal.acall_unary(req, **opts)
+ @property
+ def path(self) -> str:
+ """Returns the URL path to mount the application to when serving multiple applications."""
+ return "/process.Process"
+
+class ProcessClientSync(ConnectClientSync):
+ def list(
+ self,
+ request: ListRequest,
+ *,
+ headers: Headers | Mapping[str, str] | None = None,
+ timeout_ms: int | None = None,
+ ) -> ListResponse:
+ return self.execute_unary(
+ request=request,
+ method=MethodInfo(
+ name="List",
+ service_name="process.Process",
+ input=ListRequest,
+ output=ListResponse,
+ idempotency_level=IdempotencyLevel.UNKNOWN,
+ ),
+ headers=headers,
+ timeout_ms=timeout_ms,
+ )
+ def connect(
+ self,
+ request: ConnectRequest,
+ *,
+ headers: Headers | Mapping[str, str] | None = None,
+ timeout_ms: int | None = None,
+ ) -> Iterator[ConnectResponse]:
+ return self.execute_server_stream(
+ request=request,
+ method=MethodInfo(
+ name="Connect",
+ service_name="process.Process",
+ input=ConnectRequest,
+ output=ConnectResponse,
+ idempotency_level=IdempotencyLevel.UNKNOWN,
+ ),
+ headers=headers,
+ timeout_ms=timeout_ms,
+ )
+ def start(
+ self,
+ request: StartRequest,
+ *,
+ headers: Headers | Mapping[str, str] | None = None,
+ timeout_ms: int | None = None,
+ ) -> Iterator[StartResponse]:
+ return self.execute_server_stream(
+ request=request,
+ method=MethodInfo(
+ name="Start",
+ service_name="process.Process",
+ input=StartRequest,
+ output=StartResponse,
+ idempotency_level=IdempotencyLevel.UNKNOWN,
+ ),
+ headers=headers,
+ timeout_ms=timeout_ms,
+ )
+ def update(
+ self,
+ request: UpdateRequest,
+ *,
+ headers: Headers | Mapping[str, str] | None = None,
+ timeout_ms: int | None = None,
+ ) -> UpdateResponse:
+ return self.execute_unary(
+ request=request,
+ method=MethodInfo(
+ name="Update",
+ service_name="process.Process",
+ input=UpdateRequest,
+ output=UpdateResponse,
+ idempotency_level=IdempotencyLevel.UNKNOWN,
+ ),
+ headers=headers,
+ timeout_ms=timeout_ms,
+ )
+ def stream_input(
+ self,
+ request: Iterator[StreamInputRequest],
+ *,
+ headers: Headers | Mapping[str, str] | None = None,
+ timeout_ms: int | None = None,
+ ) -> StreamInputResponse:
+ return self.execute_client_stream(
+ request=request,
+ method=MethodInfo(
+ name="StreamInput",
+ service_name="process.Process",
+ input=StreamInputRequest,
+ output=StreamInputResponse,
+ idempotency_level=IdempotencyLevel.UNKNOWN,
+ ),
+ headers=headers,
+ timeout_ms=timeout_ms,
+ )
+ def send_input(
+ self,
+ request: SendInputRequest,
+ *,
+ headers: Headers | Mapping[str, str] | None = None,
+ timeout_ms: int | None = None,
+ ) -> SendInputResponse:
+ return self.execute_unary(
+ request=request,
+ method=MethodInfo(
+ name="SendInput",
+ service_name="process.Process",
+ input=SendInputRequest,
+ output=SendInputResponse,
+ idempotency_level=IdempotencyLevel.UNKNOWN,
+ ),
+ headers=headers,
+ timeout_ms=timeout_ms,
+ )
+ def send_signal(
+ self,
+ request: SendSignalRequest,
+ *,
+ headers: Headers | Mapping[str, str] | None = None,
+ timeout_ms: int | None = None,
+ ) -> SendSignalResponse:
+ return self.execute_unary(
+ request=request,
+ method=MethodInfo(
+ name="SendSignal",
+ service_name="process.Process",
+ input=SendSignalRequest,
+ output=SendSignalResponse,
+ idempotency_level=IdempotencyLevel.UNKNOWN,
+ ),
+ headers=headers,
+ timeout_ms=timeout_ms,
+ )
def close_stdin(
- self, req: process_dot_process__pb2.CloseStdinRequest, **opts
- ) -> process_dot_process__pb2.CloseStdinResponse:
- return self._close_stdin.call_unary(req, **opts)
-
- def aclose_stdin(
- self, req: process_dot_process__pb2.CloseStdinRequest, **opts
- ) -> Coroutine[Any, Any, process_dot_process__pb2.CloseStdinResponse]:
- return self._close_stdin.acall_unary(req, **opts)
+ self,
+ request: CloseStdinRequest,
+ *,
+ headers: Headers | Mapping[str, str] | None = None,
+ timeout_ms: int | None = None,
+ ) -> CloseStdinResponse:
+ return self.execute_unary(
+ request=request,
+ method=MethodInfo(
+ name="CloseStdin",
+ service_name="process.Process",
+ input=CloseStdinRequest,
+ output=CloseStdinResponse,
+ idempotency_level=IdempotencyLevel.UNKNOWN,
+ ),
+ headers=headers,
+ timeout_ms=timeout_ms,
+ )
diff --git a/packages/python-sdk/e2b/envd/process/process_pb.py b/packages/python-sdk/e2b/envd/process/process_pb.py
new file mode 100644
index 000000000..bcc0ba0d5
--- /dev/null
+++ b/packages/python-sdk/e2b/envd/process/process_pb.py
@@ -0,0 +1,935 @@
+# Generated from process/process.proto. DO NOT EDIT.
+# Generated by protoc-gen-py v0.1.1 with parameter "".
+# ruff: noqa: PGH004
+# ruff: noqa
+# fmt: off
+
+from __future__ import annotations
+
+from typing import Literal, NoReturn, TYPE_CHECKING, TypeAlias
+
+from protobuf import Enum, Message
+from protobuf._codegen import file_desc
+
+if TYPE_CHECKING:
+ from protobuf import DescFile, Oneof
+
+
+_PTYFields: TypeAlias = Literal["size"]
+
+class PTY(Message[_PTYFields]):
+ """
+ ```proto
+ message process.PTY
+ ```
+
+ Attributes:
+ size:
+ ```proto
+ optional process.PTY.Size size = 1;
+ ```
+ """
+
+ __slots__ = ("size",)
+
+ if TYPE_CHECKING:
+
+ def __init__(
+ self,
+ *,
+ size: PTY.Size | None = None,
+ ) -> None:
+ pass
+
+ size: PTY.Size | None
+
+ _SizeFields: TypeAlias = Literal["cols", "rows"]
+
+ class Size(Message[_SizeFields]):
+ """
+ ```proto
+ message process.PTY.Size
+ ```
+
+ Attributes:
+ cols:
+ ```proto
+ uint32 cols = 1;
+ ```
+ rows:
+ ```proto
+ uint32 rows = 2;
+ ```
+ """
+
+ __slots__ = ("cols", "rows")
+
+ if TYPE_CHECKING:
+
+ def __init__(
+ self,
+ *,
+ cols: int = 0,
+ rows: int = 0,
+ ) -> None:
+ pass
+
+ cols: int
+ rows: int
+
+_ProcessConfigFields: TypeAlias = Literal["cmd", "args", "envs", "cwd"]
+
+class ProcessConfig(Message[_ProcessConfigFields]):
+ """
+ ```proto
+ message process.ProcessConfig
+ ```
+
+ Attributes:
+ cmd:
+ ```proto
+ string cmd = 1;
+ ```
+ args:
+ ```proto
+ repeated string args = 2;
+ ```
+ envs:
+ ```proto
+ map<string, string> envs = 3;
+ ```
+ cwd:
+ ```proto
+ optional string cwd = 4;
+ ```
+ """
+
+ __slots__ = ("cmd", "args", "envs", "cwd")
+
+ if TYPE_CHECKING:
+
+ def __init__(
+ self,
+ *,
+ cmd: str = "",
+ args: list[str] | None = None,
+ envs: dict[str, str] | None = None,
+ cwd: str | None = None,
+ ) -> None:
+ pass
+
+ cmd: str
+ args: list[str]
+ envs: dict[str, str]
+ cwd: str
+
+_ListRequestFields: TypeAlias = NoReturn
+
+class ListRequest(Message[_ListRequestFields]):
+ """
+ ```proto
+ message process.ListRequest
+ ```
+ """
+
+ __slots__ = ()
+
+ if TYPE_CHECKING:
+
+ def __init__(
+ self,
+ ) -> None:
+ pass
+
+_ProcessInfoFields: TypeAlias = Literal["config", "pid", "tag"]
+
+class ProcessInfo(Message[_ProcessInfoFields]):
+ """
+ ```proto
+ message process.ProcessInfo
+ ```
+
+ Attributes:
+ config:
+ ```proto
+ optional process.ProcessConfig config = 1;
+ ```
+ pid:
+ ```proto
+ uint32 pid = 2;
+ ```
+ tag:
+ ```proto
+ optional string tag = 3;
+ ```
+ """
+
+ __slots__ = ("config", "pid", "tag")
+
+ if TYPE_CHECKING:
+
+ def __init__(
+ self,
+ *,
+ config: ProcessConfig | None = None,
+ pid: int = 0,
+ tag: str | None = None,
+ ) -> None:
+ pass
+
+ config: ProcessConfig | None
+ pid: int
+ tag: str
+
+_ListResponseFields: TypeAlias = Literal["processes"]
+
+class ListResponse(Message[_ListResponseFields]):
+ """
+ ```proto
+ message process.ListResponse
+ ```
+
+ Attributes:
+ processes:
+ ```proto
+ repeated process.ProcessInfo processes = 1;
+ ```
+ """
+
+ __slots__ = ("processes",)
+
+ if TYPE_CHECKING:
+
+ def __init__(
+ self,
+ *,
+ processes: list[ProcessInfo] | None = None,
+ ) -> None:
+ pass
+
+ processes: list[ProcessInfo]
+
+_StartRequestFields: TypeAlias = Literal["process", "pty", "tag", "stdin"]
+
+class StartRequest(Message[_StartRequestFields]):
+ """
+ ```proto
+ message process.StartRequest
+ ```
+
+ Attributes:
+ process:
+ ```proto
+ optional process.ProcessConfig process = 1;
+ ```
+ pty:
+ ```proto
+ optional process.PTY pty = 2;
+ ```
+ tag:
+ ```proto
+ optional string tag = 3;
+ ```
+ stdin:
+ ```proto
+ optional bool stdin = 4;
+ ```
+ """
+
+ __slots__ = ("process", "pty", "tag", "stdin")
+
+ if TYPE_CHECKING:
+
+ def __init__(
+ self,
+ *,
+ process: ProcessConfig | None = None,
+ pty: PTY | None = None,
+ tag: str | None = None,
+ stdin: bool | None = None,
+ ) -> None:
+ pass
+
+ process: ProcessConfig | None
+ pty: PTY | None
+ tag: str
+ stdin: bool
+
+_UpdateRequestFields: TypeAlias = Literal["process", "pty"]
+
+class UpdateRequest(Message[_UpdateRequestFields]):
+ """
+ ```proto
+ message process.UpdateRequest
+ ```
+
+ Attributes:
+ process:
+ ```proto
+ optional process.ProcessSelector process = 1;
+ ```
+ pty:
+ ```proto
+ optional process.PTY pty = 2;
+ ```
+ """
+
+ __slots__ = ("process", "pty")
+
+ if TYPE_CHECKING:
+
+ def __init__(
+ self,
+ *,
+ process: ProcessSelector | None = None,
+ pty: PTY | None = None,
+ ) -> None:
+ pass
+
+ process: ProcessSelector | None
+ pty: PTY | None
+
+_UpdateResponseFields: TypeAlias = NoReturn
+
+class UpdateResponse(Message[_UpdateResponseFields]):
+ """
+ ```proto
+ message process.UpdateResponse
+ ```
+ """
+
+ __slots__ = ()
+
+ if TYPE_CHECKING:
+
+ def __init__(
+ self,
+ ) -> None:
+ pass
+
+_ProcessEventFields: TypeAlias = Literal["start", "data", "end", "keepalive"]
+
+class ProcessEvent(Message[_ProcessEventFields]):
+ """
+ ```proto
+ message process.ProcessEvent
+ ```
+
+ Attributes:
+ event:
+ ```proto
+ oneof event
+ ```
+ """
+
+ __slots__ = ("event",)
+
+ if TYPE_CHECKING:
+
+ def __init__(
+ self,
+ *,
+ event: Oneof[Literal["start"], ProcessEvent.StartEvent] | Oneof[Literal["data"], ProcessEvent.DataEvent] | Oneof[Literal["end"], ProcessEvent.EndEvent] | Oneof[Literal["keepalive"], ProcessEvent.KeepAlive] | None = None,
+ ) -> None:
+ pass
+
+ event: Oneof[Literal["start"], ProcessEvent.StartEvent] | Oneof[Literal["data"], ProcessEvent.DataEvent] | Oneof[Literal["end"], ProcessEvent.EndEvent] | Oneof[Literal["keepalive"], ProcessEvent.KeepAlive] | None
+
+ _StartEventFields: TypeAlias = Literal["pid"]
+
+ class StartEvent(Message[_StartEventFields]):
+ """
+ ```proto
+ message process.ProcessEvent.StartEvent
+ ```
+
+ Attributes:
+ pid:
+ ```proto
+ uint32 pid = 1;
+ ```
+ """
+
+ __slots__ = ("pid",)
+
+ if TYPE_CHECKING:
+
+ def __init__(
+ self,
+ *,
+ pid: int = 0,
+ ) -> None:
+ pass
+
+ pid: int
+
+ _DataEventFields: TypeAlias = Literal["stdout", "stderr", "pty"]
+
+ class DataEvent(Message[_DataEventFields]):
+ """
+ ```proto
+ message process.ProcessEvent.DataEvent
+ ```
+
+ Attributes:
+ output:
+ ```proto
+ oneof output
+ ```
+ """
+
+ __slots__ = ("output",)
+
+ if TYPE_CHECKING:
+
+ def __init__(
+ self,
+ *,
+ output: Oneof[Literal["stdout"], bytes] | Oneof[Literal["stderr"], bytes] | Oneof[Literal["pty"], bytes] | None = None,
+ ) -> None:
+ pass
+
+ output: Oneof[Literal["stdout"], bytes] | Oneof[Literal["stderr"], bytes] | Oneof[Literal["pty"], bytes] | None
+
+ _EndEventFields: TypeAlias = Literal["exit_code", "exited", "status", "error"]
+
+ class EndEvent(Message[_EndEventFields]):
+ """
+ ```proto
+ message process.ProcessEvent.EndEvent
+ ```
+
+ Attributes:
+ exit_code:
+ ```proto
+ sint32 exit_code = 1;
+ ```
+ exited:
+ ```proto
+ bool exited = 2;
+ ```
+ status:
+ ```proto
+ string status = 3;
+ ```
+ error:
+ ```proto
+ optional string error = 4;
+ ```
+ """
+
+ __slots__ = ("exit_code", "exited", "status", "error")
+
+ if TYPE_CHECKING:
+
+ def __init__(
+ self,
+ *,
+ exit_code: int = 0,
+ exited: bool = False,
+ status: str = "",
+ error: str | None = None,
+ ) -> None:
+ pass
+
+ exit_code: int
+ exited: bool
+ status: str
+ error: str
+
+ _KeepAliveFields: TypeAlias = NoReturn
+
+ class KeepAlive(Message[_KeepAliveFields]):
+ """
+ ```proto
+ message process.ProcessEvent.KeepAlive
+ ```
+ """
+
+ __slots__ = ()
+
+ if TYPE_CHECKING:
+
+ def __init__(
+ self,
+ ) -> None:
+ pass
+
+_StartResponseFields: TypeAlias = Literal["event"]
+
+class StartResponse(Message[_StartResponseFields]):
+ """
+ ```proto
+ message process.StartResponse
+ ```
+
+ Attributes:
+ event:
+ ```proto
+ optional process.ProcessEvent event = 1;
+ ```
+ """
+
+ __slots__ = ("event",)
+
+ if TYPE_CHECKING:
+
+ def __init__(
+ self,
+ *,
+ event: ProcessEvent | None = None,
+ ) -> None:
+ pass
+
+ event: ProcessEvent | None
+
+_ConnectResponseFields: TypeAlias = Literal["event"]
+
+class ConnectResponse(Message[_ConnectResponseFields]):
+ """
+ ```proto
+ message process.ConnectResponse
+ ```
+
+ Attributes:
+ event:
+ ```proto
+ optional process.ProcessEvent event = 1;
+ ```
+ """
+
+ __slots__ = ("event",)
+
+ if TYPE_CHECKING:
+
+ def __init__(
+ self,
+ *,
+ event: ProcessEvent | None = None,
+ ) -> None:
+ pass
+
+ event: ProcessEvent | None
+
+_SendInputRequestFields: TypeAlias = Literal["process", "input"]
+
+class SendInputRequest(Message[_SendInputRequestFields]):
+ """
+ ```proto
+ message process.SendInputRequest
+ ```
+
+ Attributes:
+ process:
+ ```proto
+ optional process.ProcessSelector process = 1;
+ ```
+ input:
+ ```proto
+ optional process.ProcessInput input = 2;
+ ```
+ """
+
+ __slots__ = ("process", "input")
+
+ if TYPE_CHECKING:
+
+ def __init__(
+ self,
+ *,
+ process: ProcessSelector | None = None,
+ input: ProcessInput | None = None,
+ ) -> None:
+ pass
+
+ process: ProcessSelector | None
+ input: ProcessInput | None
+
+_SendInputResponseFields: TypeAlias = NoReturn
+
+class SendInputResponse(Message[_SendInputResponseFields]):
+ """
+ ```proto
+ message process.SendInputResponse
+ ```
+ """
+
+ __slots__ = ()
+
+ if TYPE_CHECKING:
+
+ def __init__(
+ self,
+ ) -> None:
+ pass
+
+_ProcessInputFields: TypeAlias = Literal["stdin", "pty"]
+
+class ProcessInput(Message[_ProcessInputFields]):
+ """
+ ```proto
+ message process.ProcessInput
+ ```
+
+ Attributes:
+ input:
+ ```proto
+ oneof input
+ ```
+ """
+
+ __slots__ = ("input",)
+
+ if TYPE_CHECKING:
+
+ def __init__(
+ self,
+ *,
+ input: Oneof[Literal["stdin"], bytes] | Oneof[Literal["pty"], bytes] | None = None,
+ ) -> None:
+ pass
+
+ input: Oneof[Literal["stdin"], bytes] | Oneof[Literal["pty"], bytes] | None
+
+_StreamInputRequestFields: TypeAlias = Literal["start", "data", "keepalive"]
+
+class StreamInputRequest(Message[_StreamInputRequestFields]):
+ """
+ ```proto
+ message process.StreamInputRequest
+ ```
+
+ Attributes:
+ event:
+ ```proto
+ oneof event
+ ```
+ """
+
+ __slots__ = ("event",)
+
+ if TYPE_CHECKING:
+
+ def __init__(
+ self,
+ *,
+ event: Oneof[Literal["start"], StreamInputRequest.StartEvent] | Oneof[Literal["data"], StreamInputRequest.DataEvent] | Oneof[Literal["keepalive"], StreamInputRequest.KeepAlive] | None = None,
+ ) -> None:
+ pass
+
+ event: Oneof[Literal["start"], StreamInputRequest.StartEvent] | Oneof[Literal["data"], StreamInputRequest.DataEvent] | Oneof[Literal["keepalive"], StreamInputRequest.KeepAlive] | None
+
+ _StartEventFields: TypeAlias = Literal["process"]
+
+ class StartEvent(Message[_StartEventFields]):
+ """
+ ```proto
+ message process.StreamInputRequest.StartEvent
+ ```
+
+ Attributes:
+ process:
+ ```proto
+ optional process.ProcessSelector process = 1;
+ ```
+ """
+
+ __slots__ = ("process",)
+
+ if TYPE_CHECKING:
+
+ def __init__(
+ self,
+ *,
+ process: ProcessSelector | None = None,
+ ) -> None:
+ pass
+
+ process: ProcessSelector | None
+
+ _DataEventFields: TypeAlias = Literal["input"]
+
+ class DataEvent(Message[_DataEventFields]):
+ """
+ ```proto
+ message process.StreamInputRequest.DataEvent
+ ```
+
+ Attributes:
+ input:
+ ```proto
+ optional process.ProcessInput input = 2;
+ ```
+ """
+
+ __slots__ = ("input",)
+
+ if TYPE_CHECKING:
+
+ def __init__(
+ self,
+ *,
+ input: ProcessInput | None = None,
+ ) -> None:
+ pass
+
+ input: ProcessInput | None
+
+ _KeepAliveFields: TypeAlias = NoReturn
+
+ class KeepAlive(Message[_KeepAliveFields]):
+ """
+ ```proto
+ message process.StreamInputRequest.KeepAlive
+ ```
+ """
+
+ __slots__ = ()
+
+ if TYPE_CHECKING:
+
+ def __init__(
+ self,
+ ) -> None:
+ pass
+
+_StreamInputResponseFields: TypeAlias = NoReturn
+
+class StreamInputResponse(Message[_StreamInputResponseFields]):
+ """
+ ```proto
+ message process.StreamInputResponse
+ ```
+ """
+
+ __slots__ = ()
+
+ if TYPE_CHECKING:
+
+ def __init__(
+ self,
+ ) -> None:
+ pass
+
+_SendSignalRequestFields: TypeAlias = Literal["process", "signal"]
+
+class SendSignalRequest(Message[_SendSignalRequestFields]):
+ """
+ ```proto
+ message process.SendSignalRequest
+ ```
+
+ Attributes:
+ process:
+ ```proto
+ optional process.ProcessSelector process = 1;
+ ```
+ signal:
+ ```proto
+ process.Signal signal = 2;
+ ```
+ """
+
+ __slots__ = ("process", "signal")
+
+ if TYPE_CHECKING:
+
+ def __init__(
+ self,
+ *,
+ process: ProcessSelector | None = None,
+ signal: Signal | None = None,
+ ) -> None:
+ pass
+
+ process: ProcessSelector | None
+ signal: Signal
+
+_SendSignalResponseFields: TypeAlias = NoReturn
+
+class SendSignalResponse(Message[_SendSignalResponseFields]):
+ """
+ ```proto
+ message process.SendSignalResponse
+ ```
+ """
+
+ __slots__ = ()
+
+ if TYPE_CHECKING:
+
+ def __init__(
+ self,
+ ) -> None:
+ pass
+
+_CloseStdinRequestFields: TypeAlias = Literal["process"]
+
+class CloseStdinRequest(Message[_CloseStdinRequestFields]):
+ """
+ ```proto
+ message process.CloseStdinRequest
+ ```
+
+ Attributes:
+ process:
+ ```proto
+ optional process.ProcessSelector process = 1;
+ ```
+ """
+
+ __slots__ = ("process",)
+
+ if TYPE_CHECKING:
+
+ def __init__(
+ self,
+ *,
+ process: ProcessSelector | None = None,
+ ) -> None:
+ pass
+
+ process: ProcessSelector | None
+
+_CloseStdinResponseFields: TypeAlias = NoReturn
+
+class CloseStdinResponse(Message[_CloseStdinResponseFields]):
+ """
+ ```proto
+ message process.CloseStdinResponse
+ ```
+ """
+
+ __slots__ = ()
+
+ if TYPE_CHECKING:
+
+ def __init__(
+ self,
+ ) -> None:
+ pass
+
+_ConnectRequestFields: TypeAlias = Literal["process"]
+
+class ConnectRequest(Message[_ConnectRequestFields]):
+ """
+ ```proto
+ message process.ConnectRequest
+ ```
+
+ Attributes:
+ process:
+ ```proto
+ optional process.ProcessSelector process = 1;
+ ```
+ """
+
+ __slots__ = ("process",)
+
+ if TYPE_CHECKING:
+
+ def __init__(
+ self,
+ *,
+ process: ProcessSelector | None = None,
+ ) -> None:
+ pass
+
+ process: ProcessSelector | None
+
+_ProcessSelectorFields: TypeAlias = Literal["pid", "tag"]
+
+class ProcessSelector(Message[_ProcessSelectorFields]):
+ """
+ ```proto
+ message process.ProcessSelector
+ ```
+
+ Attributes:
+ selector:
+ ```proto
+ oneof selector
+ ```
+ """
+
+ __slots__ = ("selector",)
+
+ if TYPE_CHECKING:
+
+ def __init__(
+ self,
+ *,
+ selector: Oneof[Literal["pid"], int] | Oneof[Literal["tag"], str] | None = None,
+ ) -> None:
+ pass
+
+ selector: Oneof[Literal["pid"], int] | Oneof[Literal["tag"], str] | None
+
+class Signal(Enum):
+ """
+ ```proto
+ enum process.Signal
+ ```
+
+ Attributes:
+ UNSPECIFIED:
+ ```proto
+ SIGNAL_UNSPECIFIED = 0
+ ```
+ SIGTERM:
+ ```proto
+ SIGNAL_SIGTERM = 15
+ ```
+ SIGKILL:
+ ```proto
+ SIGNAL_SIGKILL = 9
+ ```
+ """
+
+ UNSPECIFIED = 0
+ SIGTERM = 15
+ SIGKILL = 9
+
+
+_DESC = file_desc(
+ b'\n\x15process/process.proto\x12\x07process"\\\n\x03PTY\x12%\n\x04size\x18\x01 \x01(\x0b2\x11.process.PTY.SizeR\x04size\x1a.\n\x04Size\x12\x12\n\x04cols\x18\x01 \x01(\rR\x04cols\x12\x12\n\x04rows\x18\x02 \x01(\rR\x04rows"\xc3\x01\n\rProcessConfig\x12\x10\n\x03cmd\x18\x01 \x01(\tR\x03cmd\x12\x12\n\x04args\x18\x02 \x03(\tR\x04args\x124\n\x04envs\x18\x03 \x03(\x0b2 .process.ProcessConfig.EnvsEntryR\x04envs\x12\x15\n\x03cwd\x18\x04 \x01(\tH\x00R\x03cwd\x88\x01\x01\x1a7\n\tEnvsEntry\x12\x10\n\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n\x05value\x18\x02 \x01(\tR\x05value:\x028\x01B\x06\n\x04_cwd"\r\n\x0bListRequest"n\n\x0bProcessInfo\x12.\n\x06config\x18\x01 \x01(\x0b2\x16.process.ProcessConfigR\x06config\x12\x10\n\x03pid\x18\x02 \x01(\rR\x03pid\x12\x15\n\x03tag\x18\x03 \x01(\tH\x00R\x03tag\x88\x01\x01B\x06\n\x04_tag"B\n\x0cListResponse\x122\n\tprocesses\x18\x01 \x03(\x0b2\x14.process.ProcessInfoR\tprocesses"\xb1\x01\n\x0cStartRequest\x120\n\x07process\x18\x01 \x01(\x0b2\x16.process.ProcessConfigR\x07process\x12#\n\x03pty\x18\x02 \x01(\x0b2\x0c.process.PTYH\x00R\x03pty\x88\x01\x01\x12\x15\n\x03tag\x18\x03 \x01(\tH\x01R\x03tag\x88\x01\x01\x12\x19\n\x05stdin\x18\x04 \x01(\x08H\x02R\x05stdin\x88\x01\x01B\x06\n\x04_ptyB\x06\n\x04_tagB\x08\n\x06_stdin"p\n\rUpdateRequest\x122\n\x07process\x18\x01 \x01(\x0b2\x18.process.ProcessSelectorR\x07process\x12#\n\x03pty\x18\x02 \x01(\x0b2\x0c.process.PTYH\x00R\x03pty\x88\x01\x01B\x06\n\x04_pty"\x10\n\x0eUpdateResponse"\x87\x04\n\x0cProcessEvent\x128\n\x05start\x18\x01 \x01(\x0b2 .process.ProcessEvent.StartEventH\x00R\x05start\x125\n\x04data\x18\x02 \x01(\x0b2\x1f.process.ProcessEvent.DataEventH\x00R\x04data\x122\n\x03end\x18\x03 \x01(\x0b2\x1e.process.ProcessEvent.EndEventH\x00R\x03end\x12?\n\tkeepalive\x18\x04 \x01(\x0b2\x1f.process.ProcessEvent.KeepAliveH\x00R\tkeepalive\x1a\x1e\n\nStartEvent\x12\x10\n\x03pid\x18\x01 \x01(\rR\x03pid\x1a]\n\tDataEvent\x12\x18\n\x06stdout\x18\x01 \x01(\x0cH\x00R\x06stdout\x12\x18\n\x06stderr\x18\x02 \x01(\x0cH\x00R\x06stderr\x12\x12\n\x03pty\x18\x03 \x01(\x0cH\x00R\x03ptyB\x08\n\x06output\x1a|\n\x08EndEvent\x12\x1b\n\texit_code\x18\x01 \x01(\x11R\x08exitCode\x12\x16\n\x06exited\x18\x02 \x01(\x08R\x06exited\x12\x16\n\x06status\x18\x03 \x01(\tR\x06status\x12\x19\n\x05error\x18\x04 \x01(\tH\x00R\x05error\x88\x01\x01B\x08\n\x06_error\x1a\x0b\n\tKeepAliveB\x07\n\x05event"<\n\rStartResponse\x12+\n\x05event\x18\x01 \x01(\x0b2\x15.process.ProcessEventR\x05event">\n\x0fConnectResponse\x12+\n\x05event\x18\x01 \x01(\x0b2\x15.process.ProcessEventR\x05event"s\n\x10SendInputRequest\x122\n\x07process\x18\x01 \x01(\x0b2\x18.process.ProcessSelectorR\x07process\x12+\n\x05input\x18\x02 \x01(\x0b2\x15.process.ProcessInputR\x05input"\x13\n\x11SendInputResponse"C\n\x0cProcessInput\x12\x16\n\x05stdin\x18\x01 \x01(\x0cH\x00R\x05stdin\x12\x12\n\x03pty\x18\x02 \x01(\x0cH\x00R\x03ptyB\x07\n\x05input"\xea\x02\n\x12StreamInputRequest\x12>\n\x05start\x18\x01 \x01(\x0b2&.process.StreamInputRequest.StartEventH\x00R\x05start\x12;\n\x04data\x18\x02 \x01(\x0b2%.process.StreamInputRequest.DataEventH\x00R\x04data\x12E\n\tkeepalive\x18\x03 \x01(\x0b2%.process.StreamInputRequest.KeepAliveH\x00R\tkeepalive\x1a@\n\nStartEvent\x122\n\x07process\x18\x01 \x01(\x0b2\x18.process.ProcessSelectorR\x07process\x1a8\n\tDataEvent\x12+\n\x05input\x18\x02 \x01(\x0b2\x15.process.ProcessInputR\x05input\x1a\x0b\n\tKeepAliveB\x07\n\x05event"\x15\n\x13StreamInputResponse"p\n\x11SendSignalRequest\x122\n\x07process\x18\x01 \x01(\x0b2\x18.process.ProcessSelectorR\x07process\x12\'\n\x06signal\x18\x02 \x01(\x0e2\x0f.process.SignalR\x06signal"\x14\n\x12SendSignalResponse"G\n\x11CloseStdinRequest\x122\n\x07process\x18\x01 \x01(\x0b2\x18.process.ProcessSelectorR\x07process"\x14\n\x12CloseStdinResponse"D\n\x0eConnectRequest\x122\n\x07process\x18\x01 \x01(\x0b2\x18.process.ProcessSelectorR\x07process"E\n\x0fProcessSelector\x12\x12\n\x03pid\x18\x01 \x01(\rH\x00R\x03pid\x12\x12\n\x03tag\x18\x02 \x01(\tH\x00R\x03tagB\n\n\x08selector*H\n\x06Signal\x12\x16\n\x12SIGNAL_UNSPECIFIED\x10\x00\x12\x12\n\x0eSIGNAL_SIGTERM\x10\x0f\x12\x12\n\x0eSIGNAL_SIGKILL\x10\t2\x91\x04\n\x07Process\x123\n\x04List\x12\x14.process.ListRequest\x1a\x15.process.ListResponse\x12>\n\x07Connect\x12\x17.process.ConnectRequest\x1a\x18.process.ConnectResponse0\x01\x128\n\x05Start\x12\x15.process.StartRequest\x1a\x16.process.StartResponse0\x01\x129\n\x06Update\x12\x16.process.UpdateRequest\x1a\x17.process.UpdateResponse\x12J\n\x0bStreamInput\x12\x1b.process.StreamInputRequest\x1a\x1c.process.StreamInputResponse(\x01\x12B\n\tSendInput\x12\x19.process.SendInputRequest\x1a\x1a.process.SendInputResponse\x12E\n\nSendSignal\x12\x1a.process.SendSignalRequest\x1a\x1b.process.SendSignalResponse\x12E\n\nCloseStdin\x12\x1a.process.CloseStdinRequest\x1a\x1b.process.CloseStdinResponseBW\n\x0bcom.processB\x0cProcessProtoP\x01\xa2\x02\x03PXX\xaa\x02\x07Process\xca\x02\x07Process\xe2\x02\x13Process\\GPBMetadata\xea\x02\x07Processb\x06proto3',
+ [],
+ {
+ "PTY": PTY,
+ "PTY.Size": PTY.Size,
+ "ProcessConfig": ProcessConfig,
+ "ListRequest": ListRequest,
+ "ProcessInfo": ProcessInfo,
+ "ListResponse": ListResponse,
+ "StartRequest": StartRequest,
+ "UpdateRequest": UpdateRequest,
+ "UpdateResponse": UpdateResponse,
+ "ProcessEvent": ProcessEvent,
+ "ProcessEvent.StartEvent": ProcessEvent.StartEvent,
+ "ProcessEvent.DataEvent": ProcessEvent.DataEvent,
+ "ProcessEvent.EndEvent": ProcessEvent.EndEvent,
+ "ProcessEvent.KeepAlive": ProcessEvent.KeepAlive,
+ "StartResponse": StartResponse,
+ "ConnectResponse": ConnectResponse,
+ "SendInputRequest": SendInputRequest,
+ "SendInputResponse": SendInputResponse,
+ "ProcessInput": ProcessInput,
+ "StreamInputRequest": StreamInputRequest,
+ "StreamInputRequest.StartEvent": StreamInputRequest.StartEvent,
+ "StreamInputRequest.DataEvent": StreamInputRequest.DataEvent,
+ "StreamInputRequest.KeepAlive": StreamInputRequest.KeepAlive,
+ "StreamInputResponse": StreamInputResponse,
+ "SendSignalRequest": SendSignalRequest,
+ "SendSignalResponse": SendSignalResponse,
+ "CloseStdinRequest": CloseStdinRequest,
+ "CloseStdinResponse": CloseStdinResponse,
+ "ConnectRequest": ConnectRequest,
+ "ProcessSelector": ProcessSelector,
+ "Signal": Signal,
+ },
+)
+
+
+def desc() -> DescFile:
+ """Returns the descriptor for the file `process/process.proto`."""
+ return _DESC
diff --git a/packages/python-sdk/e2b/envd/process/process_pb2.py b/packages/python-sdk/e2b/envd/process/process_pb2.py
deleted file mode 100644
index bb69b6409..000000000
--- a/packages/python-sdk/e2b/envd/process/process_pb2.py
+++ /dev/null
@@ -1,96 +0,0 @@
-# -*- coding: utf-8 -*-
-# Generated by the protocol buffer compiler. DO NOT EDIT!
-# source: process/process.proto
-# Protobuf Python Version: 5.26.1
-"""Generated protocol buffer code."""
-
-from google.protobuf import descriptor as _descriptor
-from google.protobuf import descriptor_pool as _descriptor_pool
-from google.protobuf import symbol_database as _symbol_database
-from google.protobuf.internal import builder as _builder
-# @@protoc_insertion_point(imports)
-
-_sym_db = _symbol_database.Default()
-
-
-DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(
- b'\n\x15process/process.proto\x12\x07process"\\\n\x03PTY\x12%\n\x04size\x18\x01 \x01(\x0b\x32\x11.process.PTY.SizeR\x04size\x1a.\n\x04Size\x12\x12\n\x04\x63ols\x18\x01 \x01(\rR\x04\x63ols\x12\x12\n\x04rows\x18\x02 \x01(\rR\x04rows"\xc3\x01\n\rProcessConfig\x12\x10\n\x03\x63md\x18\x01 \x01(\tR\x03\x63md\x12\x12\n\x04\x61rgs\x18\x02 \x03(\tR\x04\x61rgs\x12\x34\n\x04\x65nvs\x18\x03 \x03(\x0b\x32 .process.ProcessConfig.EnvsEntryR\x04\x65nvs\x12\x15\n\x03\x63wd\x18\x04 \x01(\tH\x00R\x03\x63wd\x88\x01\x01\x1a\x37\n\tEnvsEntry\x12\x10\n\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n\x05value\x18\x02 \x01(\tR\x05value:\x02\x38\x01\x42\x06\n\x04_cwd"\r\n\x0bListRequest"n\n\x0bProcessInfo\x12.\n\x06\x63onfig\x18\x01 \x01(\x0b\x32\x16.process.ProcessConfigR\x06\x63onfig\x12\x10\n\x03pid\x18\x02 \x01(\rR\x03pid\x12\x15\n\x03tag\x18\x03 \x01(\tH\x00R\x03tag\x88\x01\x01\x42\x06\n\x04_tag"B\n\x0cListResponse\x12\x32\n\tprocesses\x18\x01 \x03(\x0b\x32\x14.process.ProcessInfoR\tprocesses"\xb1\x01\n\x0cStartRequest\x12\x30\n\x07process\x18\x01 \x01(\x0b\x32\x16.process.ProcessConfigR\x07process\x12#\n\x03pty\x18\x02 \x01(\x0b\x32\x0c.process.PTYH\x00R\x03pty\x88\x01\x01\x12\x15\n\x03tag\x18\x03 \x01(\tH\x01R\x03tag\x88\x01\x01\x12\x19\n\x05stdin\x18\x04 \x01(\x08H\x02R\x05stdin\x88\x01\x01\x42\x06\n\x04_ptyB\x06\n\x04_tagB\x08\n\x06_stdin"p\n\rUpdateRequest\x12\x32\n\x07process\x18\x01 \x01(\x0b\x32\x18.process.ProcessSelectorR\x07process\x12#\n\x03pty\x18\x02 \x01(\x0b\x32\x0c.process.PTYH\x00R\x03pty\x88\x01\x01\x42\x06\n\x04_pty"\x10\n\x0eUpdateResponse"\x87\x04\n\x0cProcessEvent\x12\x38\n\x05start\x18\x01 \x01(\x0b\x32 .process.ProcessEvent.StartEventH\x00R\x05start\x12\x35\n\x04\x64\x61ta\x18\x02 \x01(\x0b\x32\x1f.process.ProcessEvent.DataEventH\x00R\x04\x64\x61ta\x12\x32\n\x03\x65nd\x18\x03 \x01(\x0b\x32\x1e.process.ProcessEvent.EndEventH\x00R\x03\x65nd\x12?\n\tkeepalive\x18\x04 \x01(\x0b\x32\x1f.process.ProcessEvent.KeepAliveH\x00R\tkeepalive\x1a\x1e\n\nStartEvent\x12\x10\n\x03pid\x18\x01 \x01(\rR\x03pid\x1a]\n\tDataEvent\x12\x18\n\x06stdout\x18\x01 \x01(\x0cH\x00R\x06stdout\x12\x18\n\x06stderr\x18\x02 \x01(\x0cH\x00R\x06stderr\x12\x12\n\x03pty\x18\x03 \x01(\x0cH\x00R\x03ptyB\x08\n\x06output\x1a|\n\x08\x45ndEvent\x12\x1b\n\texit_code\x18\x01 \x01(\x11R\x08\x65xitCode\x12\x16\n\x06\x65xited\x18\x02 \x01(\x08R\x06\x65xited\x12\x16\n\x06status\x18\x03 \x01(\tR\x06status\x12\x19\n\x05\x65rror\x18\x04 \x01(\tH\x00R\x05\x65rror\x88\x01\x01\x42\x08\n\x06_error\x1a\x0b\n\tKeepAliveB\x07\n\x05\x65vent"<\n\rStartResponse\x12+\n\x05\x65vent\x18\x01 \x01(\x0b\x32\x15.process.ProcessEventR\x05\x65vent">\n\x0f\x43onnectResponse\x12+\n\x05\x65vent\x18\x01 \x01(\x0b\x32\x15.process.ProcessEventR\x05\x65vent"s\n\x10SendInputRequest\x12\x32\n\x07process\x18\x01 \x01(\x0b\x32\x18.process.ProcessSelectorR\x07process\x12+\n\x05input\x18\x02 \x01(\x0b\x32\x15.process.ProcessInputR\x05input"\x13\n\x11SendInputResponse"C\n\x0cProcessInput\x12\x16\n\x05stdin\x18\x01 \x01(\x0cH\x00R\x05stdin\x12\x12\n\x03pty\x18\x02 \x01(\x0cH\x00R\x03ptyB\x07\n\x05input"\xea\x02\n\x12StreamInputRequest\x12>\n\x05start\x18\x01 \x01(\x0b\x32&.process.StreamInputRequest.StartEventH\x00R\x05start\x12;\n\x04\x64\x61ta\x18\x02 \x01(\x0b\x32%.process.StreamInputRequest.DataEventH\x00R\x04\x64\x61ta\x12\x45\n\tkeepalive\x18\x03 \x01(\x0b\x32%.process.StreamInputRequest.KeepAliveH\x00R\tkeepalive\x1a@\n\nStartEvent\x12\x32\n\x07process\x18\x01 \x01(\x0b\x32\x18.process.ProcessSelectorR\x07process\x1a\x38\n\tDataEvent\x12+\n\x05input\x18\x02 \x01(\x0b\x32\x15.process.ProcessInputR\x05input\x1a\x0b\n\tKeepAliveB\x07\n\x05\x65vent"\x15\n\x13StreamInputResponse"p\n\x11SendSignalRequest\x12\x32\n\x07process\x18\x01 \x01(\x0b\x32\x18.process.ProcessSelectorR\x07process\x12\'\n\x06signal\x18\x02 \x01(\x0e\x32\x0f.process.SignalR\x06signal"\x14\n\x12SendSignalResponse"G\n\x11\x43loseStdinRequest\x12\x32\n\x07process\x18\x01 \x01(\x0b\x32\x18.process.ProcessSelectorR\x07process"\x14\n\x12\x43loseStdinResponse"D\n\x0e\x43onnectRequest\x12\x32\n\x07process\x18\x01 \x01(\x0b\x32\x18.process.ProcessSelectorR\x07process"E\n\x0fProcessSelector\x12\x12\n\x03pid\x18\x01 \x01(\rH\x00R\x03pid\x12\x12\n\x03tag\x18\x02 \x01(\tH\x00R\x03tagB\n\n\x08selector*H\n\x06Signal\x12\x16\n\x12SIGNAL_UNSPECIFIED\x10\x00\x12\x12\n\x0eSIGNAL_SIGTERM\x10\x0f\x12\x12\n\x0eSIGNAL_SIGKILL\x10\t2\x91\x04\n\x07Process\x12\x33\n\x04List\x12\x14.process.ListRequest\x1a\x15.process.ListResponse\x12>\n\x07\x43onnect\x12\x17.process.ConnectRequest\x1a\x18.process.ConnectResponse0\x01\x12\x38\n\x05Start\x12\x15.process.StartRequest\x1a\x16.process.StartResponse0\x01\x12\x39\n\x06Update\x12\x16.process.UpdateRequest\x1a\x17.process.UpdateResponse\x12J\n\x0bStreamInput\x12\x1b.process.StreamInputRequest\x1a\x1c.process.StreamInputResponse(\x01\x12\x42\n\tSendInput\x12\x19.process.SendInputRequest\x1a\x1a.process.SendInputResponse\x12\x45\n\nSendSignal\x12\x1a.process.SendSignalRequest\x1a\x1b.process.SendSignalResponse\x12\x45\n\nCloseStdin\x12\x1a.process.CloseStdinRequest\x1a\x1b.process.CloseStdinResponseBW\n\x0b\x63om.processB\x0cProcessProtoP\x01\xa2\x02\x03PXX\xaa\x02\x07Process\xca\x02\x07Process\xe2\x02\x13Process\\GPBMetadata\xea\x02\x07Processb\x06proto3'
-)
-
-_globals = globals()
-_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
-_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, "process.process_pb2", _globals)
-if not _descriptor._USE_C_DESCRIPTORS:
- _globals["DESCRIPTOR"]._loaded_options = None
- _globals[
- "DESCRIPTOR"
- ]._serialized_options = b"\n\013com.processB\014ProcessProtoP\001\242\002\003PXX\252\002\007Process\312\002\007Process\342\002\023Process\\GPBMetadata\352\002\007Process"
- _globals["_PROCESSCONFIG_ENVSENTRY"]._loaded_options = None
- _globals["_PROCESSCONFIG_ENVSENTRY"]._serialized_options = b"8\001"
- _globals["_SIGNAL"]._serialized_start = 2448
- _globals["_SIGNAL"]._serialized_end = 2520
- _globals["_PTY"]._serialized_start = 34
- _globals["_PTY"]._serialized_end = 126
- _globals["_PTY_SIZE"]._serialized_start = 80
- _globals["_PTY_SIZE"]._serialized_end = 126
- _globals["_PROCESSCONFIG"]._serialized_start = 129
- _globals["_PROCESSCONFIG"]._serialized_end = 324
- _globals["_PROCESSCONFIG_ENVSENTRY"]._serialized_start = 261
- _globals["_PROCESSCONFIG_ENVSENTRY"]._serialized_end = 316
- _globals["_LISTREQUEST"]._serialized_start = 326
- _globals["_LISTREQUEST"]._serialized_end = 339
- _globals["_PROCESSINFO"]._serialized_start = 341
- _globals["_PROCESSINFO"]._serialized_end = 451
- _globals["_LISTRESPONSE"]._serialized_start = 453
- _globals["_LISTRESPONSE"]._serialized_end = 519
- _globals["_STARTREQUEST"]._serialized_start = 522
- _globals["_STARTREQUEST"]._serialized_end = 699
- _globals["_UPDATEREQUEST"]._serialized_start = 701
- _globals["_UPDATEREQUEST"]._serialized_end = 813
- _globals["_UPDATERESPONSE"]._serialized_start = 815
- _globals["_UPDATERESPONSE"]._serialized_end = 831
- _globals["_PROCESSEVENT"]._serialized_start = 834
- _globals["_PROCESSEVENT"]._serialized_end = 1353
- _globals["_PROCESSEVENT_STARTEVENT"]._serialized_start = 1080
- _globals["_PROCESSEVENT_STARTEVENT"]._serialized_end = 1110
- _globals["_PROCESSEVENT_DATAEVENT"]._serialized_start = 1112
- _globals["_PROCESSEVENT_DATAEVENT"]._serialized_end = 1205
- _globals["_PROCESSEVENT_ENDEVENT"]._serialized_start = 1207
- _globals["_PROCESSEVENT_ENDEVENT"]._serialized_end = 1331
- _globals["_PROCESSEVENT_KEEPALIVE"]._serialized_start = 1333
- _globals["_PROCESSEVENT_KEEPALIVE"]._serialized_end = 1344
- _globals["_STARTRESPONSE"]._serialized_start = 1355
- _globals["_STARTRESPONSE"]._serialized_end = 1415
- _globals["_CONNECTRESPONSE"]._serialized_start = 1417
- _globals["_CONNECTRESPONSE"]._serialized_end = 1479
- _globals["_SENDINPUTREQUEST"]._serialized_start = 1481
- _globals["_SENDINPUTREQUEST"]._serialized_end = 1596
- _globals["_SENDINPUTRESPONSE"]._serialized_start = 1598
- _globals["_SENDINPUTRESPONSE"]._serialized_end = 1617
- _globals["_PROCESSINPUT"]._serialized_start = 1619
- _globals["_PROCESSINPUT"]._serialized_end = 1686
- _globals["_STREAMINPUTREQUEST"]._serialized_start = 1689
- _globals["_STREAMINPUTREQUEST"]._serialized_end = 2051
- _globals["_STREAMINPUTREQUEST_STARTEVENT"]._serialized_start = 1907
- _globals["_STREAMINPUTREQUEST_STARTEVENT"]._serialized_end = 1971
- _globals["_STREAMINPUTREQUEST_DATAEVENT"]._serialized_start = 1973
- _globals["_STREAMINPUTREQUEST_DATAEVENT"]._serialized_end = 2029
- _globals["_STREAMINPUTREQUEST_KEEPALIVE"]._serialized_start = 1333
- _globals["_STREAMINPUTREQUEST_KEEPALIVE"]._serialized_end = 1344
- _globals["_STREAMINPUTRESPONSE"]._serialized_start = 2053
- _globals["_STREAMINPUTRESPONSE"]._serialized_end = 2074
- _globals["_SENDSIGNALREQUEST"]._serialized_start = 2076
- _globals["_SENDSIGNALREQUEST"]._serialized_end = 2188
- _globals["_SENDSIGNALRESPONSE"]._serialized_start = 2190
- _globals["_SENDSIGNALRESPONSE"]._serialized_end = 2210
- _globals["_CLOSESTDINREQUEST"]._serialized_start = 2212
- _globals["_CLOSESTDINREQUEST"]._serialized_end = 2283
- _globals["_CLOSESTDINRESPONSE"]._serialized_start = 2285
- _globals["_CLOSESTDINRESPONSE"]._serialized_end = 2305
- _globals["_CONNECTREQUEST"]._serialized_start = 2307
- _globals["_CONNECTREQUEST"]._serialized_end = 2375
- _globals["_PROCESSSELECTOR"]._serialized_start = 2377
- _globals["_PROCESSSELECTOR"]._serialized_end = 2446
- _globals["_PROCESS"]._serialized_start = 2523
- _globals["_PROCESS"]._serialized_end = 3052
-# @@protoc_insertion_point(module_scope)
diff --git a/packages/python-sdk/e2b/envd/process/process_pb2.pyi b/packages/python-sdk/e2b/envd/process/process_pb2.pyi
deleted file mode 100644
index e61158e46..000000000
--- a/packages/python-sdk/e2b/envd/process/process_pb2.pyi
+++ /dev/null
@@ -1,316 +0,0 @@
-from google.protobuf.internal import containers as _containers
-from google.protobuf.internal import enum_type_wrapper as _enum_type_wrapper
-from google.protobuf import descriptor as _descriptor
-from google.protobuf import message as _message
-from typing import (
- ClassVar as _ClassVar,
- Iterable as _Iterable,
- Mapping as _Mapping,
- Optional as _Optional,
- Union as _Union,
-)
-
-DESCRIPTOR: _descriptor.FileDescriptor
-
-class Signal(int, metaclass=_enum_type_wrapper.EnumTypeWrapper):
- __slots__ = ()
- SIGNAL_UNSPECIFIED: _ClassVar[Signal]
- SIGNAL_SIGTERM: _ClassVar[Signal]
- SIGNAL_SIGKILL: _ClassVar[Signal]
-
-SIGNAL_UNSPECIFIED: Signal
-SIGNAL_SIGTERM: Signal
-SIGNAL_SIGKILL: Signal
-
-class PTY(_message.Message):
- __slots__ = ("size",)
- class Size(_message.Message):
- __slots__ = ("cols", "rows")
- COLS_FIELD_NUMBER: _ClassVar[int]
- ROWS_FIELD_NUMBER: _ClassVar[int]
- cols: int
- rows: int
- def __init__(
- self, cols: _Optional[int] = ..., rows: _Optional[int] = ...
- ) -> None: ...
-
- SIZE_FIELD_NUMBER: _ClassVar[int]
- size: PTY.Size
- def __init__(self, size: _Optional[_Union[PTY.Size, _Mapping]] = ...) -> None: ...
-
-class ProcessConfig(_message.Message):
- __slots__ = ("cmd", "args", "envs", "cwd")
- class EnvsEntry(_message.Message):
- __slots__ = ("key", "value")
- KEY_FIELD_NUMBER: _ClassVar[int]
- VALUE_FIELD_NUMBER: _ClassVar[int]
- key: str
- value: str
- def __init__(
- self, key: _Optional[str] = ..., value: _Optional[str] = ...
- ) -> None: ...
-
- CMD_FIELD_NUMBER: _ClassVar[int]
- ARGS_FIELD_NUMBER: _ClassVar[int]
- ENVS_FIELD_NUMBER: _ClassVar[int]
- CWD_FIELD_NUMBER: _ClassVar[int]
- cmd: str
- args: _containers.RepeatedScalarFieldContainer[str]
- envs: _containers.ScalarMap[str, str]
- cwd: str
- def __init__(
- self,
- cmd: _Optional[str] = ...,
- args: _Optional[_Iterable[str]] = ...,
- envs: _Optional[_Mapping[str, str]] = ...,
- cwd: _Optional[str] = ...,
- ) -> None: ...
-
-class ListRequest(_message.Message):
- __slots__ = ()
- def __init__(self) -> None: ...
-
-class ProcessInfo(_message.Message):
- __slots__ = ("config", "pid", "tag")
- CONFIG_FIELD_NUMBER: _ClassVar[int]
- PID_FIELD_NUMBER: _ClassVar[int]
- TAG_FIELD_NUMBER: _ClassVar[int]
- config: ProcessConfig
- pid: int
- tag: str
- def __init__(
- self,
- config: _Optional[_Union[ProcessConfig, _Mapping]] = ...,
- pid: _Optional[int] = ...,
- tag: _Optional[str] = ...,
- ) -> None: ...
-
-class ListResponse(_message.Message):
- __slots__ = ("processes",)
- PROCESSES_FIELD_NUMBER: _ClassVar[int]
- processes: _containers.RepeatedCompositeFieldContainer[ProcessInfo]
- def __init__(
- self, processes: _Optional[_Iterable[_Union[ProcessInfo, _Mapping]]] = ...
- ) -> None: ...
-
-class StartRequest(_message.Message):
- __slots__ = ("process", "pty", "tag", "stdin")
- PROCESS_FIELD_NUMBER: _ClassVar[int]
- PTY_FIELD_NUMBER: _ClassVar[int]
- TAG_FIELD_NUMBER: _ClassVar[int]
- STDIN_FIELD_NUMBER: _ClassVar[int]
- process: ProcessConfig
- pty: PTY
- tag: str
- stdin: bool
- def __init__(
- self,
- process: _Optional[_Union[ProcessConfig, _Mapping]] = ...,
- pty: _Optional[_Union[PTY, _Mapping]] = ...,
- tag: _Optional[str] = ...,
- stdin: bool = ...,
- ) -> None: ...
-
-class UpdateRequest(_message.Message):
- __slots__ = ("process", "pty")
- PROCESS_FIELD_NUMBER: _ClassVar[int]
- PTY_FIELD_NUMBER: _ClassVar[int]
- process: ProcessSelector
- pty: PTY
- def __init__(
- self,
- process: _Optional[_Union[ProcessSelector, _Mapping]] = ...,
- pty: _Optional[_Union[PTY, _Mapping]] = ...,
- ) -> None: ...
-
-class UpdateResponse(_message.Message):
- __slots__ = ()
- def __init__(self) -> None: ...
-
-class ProcessEvent(_message.Message):
- __slots__ = ("start", "data", "end", "keepalive")
- class StartEvent(_message.Message):
- __slots__ = ("pid",)
- PID_FIELD_NUMBER: _ClassVar[int]
- pid: int
- def __init__(self, pid: _Optional[int] = ...) -> None: ...
-
- class DataEvent(_message.Message):
- __slots__ = ("stdout", "stderr", "pty")
- STDOUT_FIELD_NUMBER: _ClassVar[int]
- STDERR_FIELD_NUMBER: _ClassVar[int]
- PTY_FIELD_NUMBER: _ClassVar[int]
- stdout: bytes
- stderr: bytes
- pty: bytes
- def __init__(
- self,
- stdout: _Optional[bytes] = ...,
- stderr: _Optional[bytes] = ...,
- pty: _Optional[bytes] = ...,
- ) -> None: ...
-
- class EndEvent(_message.Message):
- __slots__ = ("exit_code", "exited", "status", "error")
- EXIT_CODE_FIELD_NUMBER: _ClassVar[int]
- EXITED_FIELD_NUMBER: _ClassVar[int]
- STATUS_FIELD_NUMBER: _ClassVar[int]
- ERROR_FIELD_NUMBER: _ClassVar[int]
- exit_code: int
- exited: bool
- status: str
- error: str
- def __init__(
- self,
- exit_code: _Optional[int] = ...,
- exited: bool = ...,
- status: _Optional[str] = ...,
- error: _Optional[str] = ...,
- ) -> None: ...
-
- class KeepAlive(_message.Message):
- __slots__ = ()
- def __init__(self) -> None: ...
-
- START_FIELD_NUMBER: _ClassVar[int]
- DATA_FIELD_NUMBER: _ClassVar[int]
- END_FIELD_NUMBER: _ClassVar[int]
- KEEPALIVE_FIELD_NUMBER: _ClassVar[int]
- start: ProcessEvent.StartEvent
- data: ProcessEvent.DataEvent
- end: ProcessEvent.EndEvent
- keepalive: ProcessEvent.KeepAlive
- def __init__(
- self,
- start: _Optional[_Union[ProcessEvent.StartEvent, _Mapping]] = ...,
- data: _Optional[_Union[ProcessEvent.DataEvent, _Mapping]] = ...,
- end: _Optional[_Union[ProcessEvent.EndEvent, _Mapping]] = ...,
- keepalive: _Optional[_Union[ProcessEvent.KeepAlive, _Mapping]] = ...,
- ) -> None: ...
-
-class StartResponse(_message.Message):
- __slots__ = ("event",)
- EVENT_FIELD_NUMBER: _ClassVar[int]
- event: ProcessEvent
- def __init__(
- self, event: _Optional[_Union[ProcessEvent, _Mapping]] = ...
- ) -> None: ...
-
-class ConnectResponse(_message.Message):
- __slots__ = ("event",)
- EVENT_FIELD_NUMBER: _ClassVar[int]
- event: ProcessEvent
- def __init__(
- self, event: _Optional[_Union[ProcessEvent, _Mapping]] = ...
- ) -> None: ...
-
-class SendInputRequest(_message.Message):
- __slots__ = ("process", "input")
- PROCESS_FIELD_NUMBER: _ClassVar[int]
- INPUT_FIELD_NUMBER: _ClassVar[int]
- process: ProcessSelector
- input: ProcessInput
- def __init__(
- self,
- process: _Optional[_Union[ProcessSelector, _Mapping]] = ...,
- input: _Optional[_Union[ProcessInput, _Mapping]] = ...,
- ) -> None: ...
-
-class SendInputResponse(_message.Message):
- __slots__ = ()
- def __init__(self) -> None: ...
-
-class ProcessInput(_message.Message):
- __slots__ = ("stdin", "pty")
- STDIN_FIELD_NUMBER: _ClassVar[int]
- PTY_FIELD_NUMBER: _ClassVar[int]
- stdin: bytes
- pty: bytes
- def __init__(
- self, stdin: _Optional[bytes] = ..., pty: _Optional[bytes] = ...
- ) -> None: ...
-
-class StreamInputRequest(_message.Message):
- __slots__ = ("start", "data", "keepalive")
- class StartEvent(_message.Message):
- __slots__ = ("process",)
- PROCESS_FIELD_NUMBER: _ClassVar[int]
- process: ProcessSelector
- def __init__(
- self, process: _Optional[_Union[ProcessSelector, _Mapping]] = ...
- ) -> None: ...
-
- class DataEvent(_message.Message):
- __slots__ = ("input",)
- INPUT_FIELD_NUMBER: _ClassVar[int]
- input: ProcessInput
- def __init__(
- self, input: _Optional[_Union[ProcessInput, _Mapping]] = ...
- ) -> None: ...
-
- class KeepAlive(_message.Message):
- __slots__ = ()
- def __init__(self) -> None: ...
-
- START_FIELD_NUMBER: _ClassVar[int]
- DATA_FIELD_NUMBER: _ClassVar[int]
- KEEPALIVE_FIELD_NUMBER: _ClassVar[int]
- start: StreamInputRequest.StartEvent
- data: StreamInputRequest.DataEvent
- keepalive: StreamInputRequest.KeepAlive
- def __init__(
- self,
- start: _Optional[_Union[StreamInputRequest.StartEvent, _Mapping]] = ...,
- data: _Optional[_Union[StreamInputRequest.DataEvent, _Mapping]] = ...,
- keepalive: _Optional[_Union[StreamInputRequest.KeepAlive, _Mapping]] = ...,
- ) -> None: ...
-
-class StreamInputResponse(_message.Message):
- __slots__ = ()
- def __init__(self) -> None: ...
-
-class SendSignalRequest(_message.Message):
- __slots__ = ("process", "signal")
- PROCESS_FIELD_NUMBER: _ClassVar[int]
- SIGNAL_FIELD_NUMBER: _ClassVar[int]
- process: ProcessSelector
- signal: Signal
- def __init__(
- self,
- process: _Optional[_Union[ProcessSelector, _Mapping]] = ...,
- signal: _Optional[_Union[Signal, str]] = ...,
- ) -> None: ...
-
-class SendSignalResponse(_message.Message):
- __slots__ = ()
- def __init__(self) -> None: ...
-
-class CloseStdinRequest(_message.Message):
- __slots__ = ("process",)
- PROCESS_FIELD_NUMBER: _ClassVar[int]
- process: ProcessSelector
- def __init__(
- self, process: _Optional[_Union[ProcessSelector, _Mapping]] = ...
- ) -> None: ...
-
-class CloseStdinResponse(_message.Message):
- __slots__ = ()
- def __init__(self) -> None: ...
-
-class ConnectRequest(_message.Message):
- __slots__ = ("process",)
- PROCESS_FIELD_NUMBER: _ClassVar[int]
- process: ProcessSelector
- def __init__(
- self, process: _Optional[_Union[ProcessSelector, _Mapping]] = ...
- ) -> None: ...
-
-class ProcessSelector(_message.Message):
- __slots__ = ("pid", "tag")
- PID_FIELD_NUMBER: _ClassVar[int]
- TAG_FIELD_NUMBER: _ClassVar[int]
- pid: int
- tag: str
- def __init__(
- self, pid: _Optional[int] = ..., tag: _Optional[str] = ...
- ) -> None: ...
diff --git a/packages/python-sdk/e2b/envd/rpc.py b/packages/python-sdk/e2b/envd/rpc.py
index 0f9c27797..7caca5c70 100644
--- a/packages/python-sdk/e2b/envd/rpc.py
+++ b/packages/python-sdk/e2b/envd/rpc.py
@@ -1,9 +1,9 @@
-import base64
+import asyncio
-import httpcore
from typing import Awaitable, Callable, Optional
-from packaging.version import Version
-from e2b_connect.client import Code, ConnectException
+from connectrpc.code import Code
+from connectrpc.errors import ConnectError
+from pyqwest import ReadError, StreamError, WriteError
from e2b.exceptions import (
SandboxException,
@@ -14,26 +14,51 @@ from e2b.exceptions import (
AuthenticationException,
RateLimitException,
)
-from e2b.connection_config import Username, default_username
-from e2b.envd.versions import ENVD_DEFAULT_USER
_DEFAULT_RPC_ERROR_MAP: dict[Code, Callable[[str], Exception]] = {
- Code.invalid_argument: InvalidArgumentException,
- Code.unauthenticated: AuthenticationException,
- Code.not_found: NotFoundException,
- Code.unavailable: format_sandbox_timeout_exception,
- Code.resource_exhausted: lambda message: RateLimitException(
+ Code.INVALID_ARGUMENT: InvalidArgumentException,
+ Code.UNAUTHENTICATED: AuthenticationException,
+ Code.NOT_FOUND: NotFoundException,
+ Code.UNAVAILABLE: format_sandbox_timeout_exception,
+ Code.RESOURCE_EXHAUSTED: lambda message: RateLimitException(
f"{message}: Rate limit exceeded, please try again later."
),
- Code.canceled: lambda message: TimeoutException(
- f"{message}: This error is likely due to exceeding 'request_timeout'. You can pass the request timeout value as an option when making the request."
+ Code.CANCELED: lambda message: TimeoutException(
+ f"{message}: The request was cancelled by the server or a proxy while it was in flight — for example when the sandbox is paused or shut down."
),
- Code.deadline_exceeded: lambda message: TimeoutException(
- f"{message}: This error is likely due to exceeding 'timeout' — the total time a long running request (like process or directory watch) can be active. It can be modified by passing 'timeout' when making the request. Use '0' to disable the timeout."
+ Code.DEADLINE_EXCEEDED: lambda message: TimeoutException(
+ f"{message}: This error is likely due to exceeding 'timeout' — the total time a long running request (like process or directory watch) can be active — or 'request_timeout'. You can modify these by passing 'timeout' or 'request_timeout' when making the request. Use '0' to disable the timeout."
),
}
+# pyqwest raises the builtin ConnectionError for connection-establishment
+# failures and TimeoutError for its transport timeouts (both OSError
+# subclasses); failures after the connection is up raise its ReadError /
+# WriteError / StreamError (an HTTP/2 stream reset is a StreamError).
+_TRANSPORT_ERRORS = (OSError, ReadError, WriteError, StreamError)
+
+
+def is_transport_failure(e: Exception) -> bool:
+ """Whether the error is a connection-level failure (failed connect, stream
+ reset, connection dropped mid-request) rather than an error response from
+ envd.
+
+ connectrpc wraps transport errors with the original exception as
+ ``__cause__``, but its catch-all wraps *any* unexpected exception the same
+ way — including a response body that fails to decode — so the cause must
+ actually be a transport error type, not merely present. Client-enforced
+ deadlines (mapped to ``DEADLINE_EXCEEDED`` with a ``TimeoutError`` cause)
+ are definitive results, not connection failures — they must not trigger
+ a sandbox health probe.
+ """
+ return (
+ isinstance(e, ConnectError)
+ and isinstance(e.__cause__, _TRANSPORT_ERRORS)
+ and e.code is not Code.DEADLINE_EXCEEDED
+ )
+
+
def format_terminated_exception(
e: Exception,
sandbox_running: Optional[bool],
@@ -55,37 +80,37 @@ def handle_rpc_exception(
):
"""Handle errors from envd RPC calls by mapping gRPC status codes to specific exception types.
- :param e: The caught exception, expected to be a ``ConnectException`` or a transport-level ``httpcore`` error.
+ :param e: The caught exception, expected to be a ``ConnectError``.
:param error_map: Optional map of gRPC codes to exception factories that override the defaults.
:param sandbox_running: Result of a sandbox health probe (``None`` when unknown), used to disambiguate a connection dropped mid-request.
- :return: The corresponding exception. A connection dropped mid-request with the sandbox confirmed gone becomes a ``TimeoutException``; non-``ConnectException`` errors are otherwise returned as-is.
+ :return: The corresponding exception. A connection dropped mid-request with the sandbox confirmed gone becomes a ``TimeoutException``; non-``ConnectError`` errors are otherwise returned as-is.
"""
- if isinstance(e, ConnectException):
- if error_map and e.status in error_map:
- return error_map[e.status](e.message)
-
- if e.status in _DEFAULT_RPC_ERROR_MAP:
- return _DEFAULT_RPC_ERROR_MAP[e.status](e.message)
-
- return SandboxException(f"{e.status}: {e.message}")
-
- # A remote protocol error (e.g. an HTTP/2 stream reset) means the connection to the
- # sandbox was dropped mid-request — either the sandbox died or the network failed
- if isinstance(e, httpcore.RemoteProtocolError):
- return format_terminated_exception(e, sandbox_running)
-
- # A transport-level timeout from httpcore means a configured timeout was exceeded
- # before the server responded: `request_timeout` on a unary call's read phase, or
- # `connect`/`pool`/`write` on a stream's setup/send phase. Streams have no read
- # timeout — the command `timeout` is enforced server-side and surfaces as a
- # `deadline_exceeded` ConnectException instead. Unlike the JS SDK, where the
- # request timeout is an `AbortSignal` that connect normalizes into a `Code.canceled`
- # ConnectError, httpcore raises this raw transport error outside the ConnectException
- # path, so we map it here to a `TimeoutException` for a consistent timeout error.
- if isinstance(e, httpcore.TimeoutException):
- return TimeoutException(
- f"{e}: This error is likely due to exceeding 'timeout' — the total time a long running request (like process or directory watch) can be active — or 'request_timeout'. You can modify these by passing 'timeout' or 'request_timeout' when making the request. Use '0' to disable the timeout."
- )
+ if isinstance(e, ConnectError):
+ # connectrpc converts asyncio cancellation into a ConnectError with
+ # code CANCELED; restore the original CancelledError so cancelling a
+ # task keeps its asyncio semantics instead of surfacing as an RPC
+ # error (or, via the CANCELED mapping below, a TimeoutException).
+ if isinstance(e.__cause__, asyncio.CancelledError):
+ return e.__cause__
+
+ # A transport-level failure (e.g. an HTTP/2 stream reset) means the
+ # connection to the sandbox was dropped mid-request — either the
+ # sandbox died or the network failed — so the code mapping below,
+ # which describes envd responses, doesn't apply.
+ if is_transport_failure(e):
+ return format_terminated_exception(e, sandbox_running)
+
+ # Everything else maps by code; classifiable client-side failures
+ # are typed at their source rather than sniffed from __cause__ here
+ # (undecodable bodies: the envd codec; plain HTTP errors:
+ # PlainHTTPErrorTransport).
+ if error_map and e.code in error_map:
+ return error_map[e.code](e.message)
+
+ if e.code in _DEFAULT_RPC_ERROR_MAP:
+ return _DEFAULT_RPC_ERROR_MAP[e.code](e.message)
+
+ return SandboxException(f"{e.code}: {e.message}")
return e
@@ -100,7 +125,7 @@ def handle_rpc_exception_with_health(
killed from a transient network failure (e.g. a load balancer dropping the connection).
"""
sandbox_running = None
- if check_health is not None and isinstance(e, httpcore.RemoteProtocolError):
+ if check_health is not None and is_transport_failure(e):
try:
sandbox_running = check_health()
except Exception:
@@ -115,25 +140,9 @@ async def ahandle_rpc_exception_with_health(
):
"""Async version of :func:`handle_rpc_exception_with_health`."""
sandbox_running = None
- if check_health is not None and isinstance(e, httpcore.RemoteProtocolError):
+ if check_health is not None and is_transport_failure(e):
try:
sandbox_running = await check_health()
except Exception:
sandbox_running = None
return handle_rpc_exception(e, error_map, sandbox_running)
-
-
-def authentication_header(
- envd_version: Version, user: Optional[Username] = None
-) -> dict[str, str]:
- if user is None and envd_version < ENVD_DEFAULT_USER:
- user = default_username
-
- if not user:
- return {}
-
- value = f"{user}:"
-
- encoded = base64.b64encode(value.encode("utf-8")).decode("utf-8")
-
- return {"Authorization": f"Basic {encoded}"}
diff --git a/packages/python-sdk/e2b/envd/utils.py b/packages/python-sdk/e2b/envd/utils.py
new file mode 100644
index 000000000..a4df2bd35
--- /dev/null
+++ b/packages/python-sdk/e2b/envd/utils.py
@@ -0,0 +1,57 @@
+"""Helpers shared by the envd RPC call sites (commands, PTY, filesystem)."""
+
+import base64
+
+from typing import Optional, Union
+from packaging.version import Version
+from protobuf import Oneof
+
+from e2b.connection_config import Username, default_username
+from e2b.envd.process import process_pb
+from e2b.envd.versions import ENVD_DEFAULT_USER
+from e2b.exceptions import SandboxException
+
+
+def timeout_to_ms(timeout: Optional[float]) -> Optional[int]:
+ """Convert a timeout in seconds to the ``timeout_ms`` connectrpc calls
+ expect. ``None`` and ``0`` (timeout disabled) map to ``None`` — connectrpc
+ treats a non-positive deadline as already expired. Positive values map to
+ at least 1 ms so a sub-millisecond timeout stays a deadline instead of
+ the 0 that connectrpc's ``timeout_ms or default`` fallback would
+ discard."""
+ if not timeout:
+ return None
+ return max(1, round(timeout * 1000))
+
+
+def extract_start_pid(
+ start_event: Union[process_pb.StartResponse, process_pb.ConnectResponse],
+ action: str,
+) -> int:
+ """Return the pid carried by the ``start`` event that must open a process
+ stream (start/connect), raising :class:`SandboxException` when the stream
+ opened with anything else."""
+ # `event.event` is the ProcessEvent; its `event` oneof holds the payload.
+ match start_event.event.event if start_event.event is not None else None:
+ case Oneof(field="start", value=start):
+ return start.pid
+ case _:
+ raise SandboxException(
+ f"Failed to {action}: expected start event, got {start_event}"
+ )
+
+
+def authentication_header(
+ envd_version: Version, user: Optional[Username] = None
+) -> dict[str, str]:
+ if user is None and envd_version < ENVD_DEFAULT_USER:
+ user = default_username
+
+ if not user:
+ return {}
+
+ value = f"{user}:"
+
+ encoded = base64.b64encode(value.encode("utf-8")).decode("utf-8")
+
+ return {"Authorization": f"Basic {encoded}"}
diff --git a/packages/python-sdk/e2b/sandbox/filesystem/filesystem.py b/packages/python-sdk/e2b/sandbox/filesystem/filesystem.py
index 4d0455653..7cf284439 100644
--- a/packages/python-sdk/e2b/sandbox/filesystem/filesystem.py
+++ b/packages/python-sdk/e2b/sandbox/filesystem/filesystem.py
@@ -1,14 +1,16 @@
import gzip
import re
from dataclasses import dataclass, field
-from datetime import datetime, timezone
+from datetime import datetime
from enum import Enum
from io import IOBase, TextIOBase
from typing import IO, AsyncIterator, Dict, Iterator, Optional, Union, TypedDict
import httpx
-from e2b.envd.filesystem import filesystem_pb2
+from protobuf.wkt import Timestamp
+
+from e2b.envd.filesystem import filesystem_pb
from e2b.exceptions import InvalidArgumentException
from e2b.io_utils import agzip_iter, aiter_io_chunks, gzip_iter, iter_io_chunks
@@ -28,10 +30,10 @@ class FileType(Enum):
"""
-def map_file_type(ft: filesystem_pb2.FileType):
- if ft == filesystem_pb2.FileType.FILE_TYPE_FILE:
+def map_file_type(ft: filesystem_pb.FileType):
+ if ft == filesystem_pb.FileType.FILE:
return FileType.FILE
- elif ft == filesystem_pb2.FileType.FILE_TYPE_DIRECTORY:
+ elif ft == filesystem_pb.FileType.DIRECTORY:
return FileType.DIR
@@ -118,7 +120,7 @@ class EntryInfo(WriteInfo):
"""
-def map_entry_info(entry: filesystem_pb2.EntryInfo) -> EntryInfo:
+def map_entry_info(entry: filesystem_pb.EntryInfo) -> EntryInfo:
return EntryInfo(
name=entry.name,
type=map_file_type(entry.type),
@@ -128,10 +130,10 @@ def map_entry_info(entry: filesystem_pb2.EntryInfo) -> EntryInfo:
permissions=entry.permissions,
owner=entry.owner,
group=entry.group,
- modified_time=entry.modified_time.ToDatetime(tzinfo=timezone.utc),
- # Optional, we can't directly access symlink_target otherwise it will be "" instead of None
+ modified_time=(entry.modified_time or Timestamp()).to_datetime(),
+ # Optional scalar: unset reads as "" — presence check keeps it None
symlink_target=(
- entry.symlink_target if entry.HasField("symlink_target") else None
+ entry.symlink_target if entry.has_field("symlink_target") else None
),
metadata=map_metadata(entry.metadata),
)
diff --git a/packages/python-sdk/e2b/sandbox/filesystem/watch_handle.py b/packages/python-sdk/e2b/sandbox/filesystem/watch_handle.py
index 6d6767d4f..5d00ebafc 100644
--- a/packages/python-sdk/e2b/sandbox/filesystem/watch_handle.py
+++ b/packages/python-sdk/e2b/sandbox/filesystem/watch_handle.py
@@ -2,7 +2,7 @@ from dataclasses import dataclass
from enum import Enum
from typing import Optional
-from e2b.envd.filesystem.filesystem_pb2 import EventType
+from e2b.envd.filesystem.filesystem_pb import EventType
from e2b.sandbox.filesystem.filesystem import EntryInfo
@@ -34,15 +34,15 @@ class FilesystemEventType(Enum):
def map_event_type(event: EventType):
- if event == EventType.EVENT_TYPE_CHMOD:
+ if event == EventType.CHMOD:
return FilesystemEventType.CHMOD
- elif event == EventType.EVENT_TYPE_CREATE:
+ elif event == EventType.CREATE:
return FilesystemEventType.CREATE
- elif event == EventType.EVENT_TYPE_REMOVE:
+ elif event == EventType.REMOVE:
return FilesystemEventType.REMOVE
- elif event == EventType.EVENT_TYPE_RENAME:
+ elif event == EventType.RENAME:
return FilesystemEventType.RENAME
- elif event == EventType.EVENT_TYPE_WRITE:
+ elif event == EventType.WRITE:
return FilesystemEventType.WRITE
diff --git a/packages/python-sdk/e2b/sandbox_async/commands/command.py b/packages/python-sdk/e2b/sandbox_async/commands/command.py
index 93d6c3b9c..b345843af 100644
--- a/packages/python-sdk/e2b/sandbox_async/commands/command.py
+++ b/packages/python-sdk/e2b/sandbox_async/commands/command.py
@@ -1,8 +1,8 @@
from typing import Dict, List, Literal, Optional, Union, overload
-import e2b_connect
-import httpcore
import httpx
+from connectrpc.code import Code
+from connectrpc.errors import ConnectError
from packaging.version import Version
from e2b.connection_config import (
ConnectionConfig,
@@ -10,9 +10,17 @@ from e2b.connection_config import (
KEEPALIVE_PING_HEADER,
KEEPALIVE_PING_INTERVAL_SEC,
)
-from e2b.envd.process import process_connect, process_pb2
+from protobuf import Oneof
+
+from e2b.envd.process import process_connect, process_pb
from e2b.envd.api import acheck_sandbox_health
-from e2b.envd.rpc import authentication_header, ahandle_rpc_exception_with_health
+from e2b.envd.rpc import ahandle_rpc_exception_with_health
+from e2b.envd.utils import (
+ authentication_header,
+ extract_start_pid,
+ timeout_to_ms,
+)
+from e2b.envd.client_async import as_stream, create_rpc_client, first_event
from e2b.envd.versions import ENVD_COMMANDS_STDIN, ENVD_ENVD_CLOSE
from e2b.exceptions import SandboxException
from e2b.sandbox.commands.main import ProcessInfo
@@ -30,21 +38,16 @@ class Commands:
self,
envd_api_url: str,
connection_config: ConnectionConfig,
- pool: httpcore.AsyncConnectionPool,
envd_version: Version,
envd_api: httpx.AsyncClient,
) -> None:
self._connection_config = connection_config
self._envd_version = envd_version
self._check_health = lambda: acheck_sandbox_health(envd_api)
- self._rpc = process_connect.ProcessClient(
+ self._rpc = create_rpc_client(
+ process_connect.ProcessClient,
envd_api_url,
- # TODO: Fix and enable compression again — the headers compression is not solved for streaming.
- # compressor=e2b_connect.GzipCompressor,
- async_pool=pool,
- json=True,
- headers=connection_config.sandbox_headers,
- logger=connection_config.logger,
+ connection_config,
)
async def list(
@@ -59,22 +62,25 @@ class Commands:
:return: List of running commands and PTY sessions
"""
try:
- res = await self._rpc.alist(
- process_pb2.ListRequest(),
- request_timeout=self._connection_config.get_request_timeout(
- request_timeout
+ res = await self._rpc.list(
+ process_pb.ListRequest(),
+ timeout_ms=timeout_to_ms(
+ self._connection_config.get_request_timeout(request_timeout)
),
)
return [
ProcessInfo(
pid=p.pid,
- tag=p.tag if p.HasField("tag") else None,
- cmd=p.config.cmd,
- args=list(p.config.args),
- envs=dict(p.config.envs),
- cwd=p.config.cwd if p.config.HasField("cwd") else None,
+ # Optional scalars: unset reads as "" — presence checks keep
+ # them None
+ tag=p.tag if p.has_field("tag") else None,
+ cmd=config.cmd,
+ args=list(config.args),
+ envs=dict(config.envs),
+ cwd=config.cwd if config.has_field("cwd") else None,
)
for p in res.processes
+ for config in (p.config or process_pb.ProcessConfig(),)
]
except Exception as e:
raise await ahandle_rpc_exception_with_health(e, self._check_health)
@@ -94,19 +100,19 @@ class Commands:
:return: `True` if the command was killed, `False` if the command was not found
"""
try:
- await self._rpc.asend_signal(
- process_pb2.SendSignalRequest(
- process=process_pb2.ProcessSelector(pid=pid),
- signal=process_pb2.Signal.SIGNAL_SIGKILL,
+ await self._rpc.send_signal(
+ process_pb.SendSignalRequest(
+ process=process_pb.ProcessSelector(selector=Oneof("pid", pid)),
+ signal=process_pb.Signal.SIGKILL,
),
- request_timeout=self._connection_config.get_request_timeout(
- request_timeout
+ timeout_ms=timeout_to_ms(
+ self._connection_config.get_request_timeout(request_timeout)
),
)
return True
except Exception as e:
- if isinstance(e, e2b_connect.ConnectException):
- if e.status == e2b_connect.Code.not_found:
+ if isinstance(e, ConnectError):
+ if e.code == Code.NOT_FOUND:
return False
raise await ahandle_rpc_exception_with_health(e, self._check_health)
@@ -124,15 +130,17 @@ class Commands:
:param request_timeout: Timeout for the request in **seconds**
"""
try:
- await self._rpc.asend_input(
- process_pb2.SendInputRequest(
- process=process_pb2.ProcessSelector(pid=pid),
- input=process_pb2.ProcessInput(
- stdin=data.encode() if isinstance(data, str) else data,
+ await self._rpc.send_input(
+ process_pb.SendInputRequest(
+ process=process_pb.ProcessSelector(selector=Oneof("pid", pid)),
+ input=process_pb.ProcessInput(
+ input=Oneof(
+ "stdin", data.encode() if isinstance(data, str) else data
+ ),
),
),
- request_timeout=self._connection_config.get_request_timeout(
- request_timeout
+ timeout_ms=timeout_to_ms(
+ self._connection_config.get_request_timeout(request_timeout)
),
)
except Exception as e:
@@ -158,12 +166,12 @@ class Commands:
)
try:
- await self._rpc.aclose_stdin(
- process_pb2.CloseStdinRequest(
- process=process_pb2.ProcessSelector(pid=pid),
+ await self._rpc.close_stdin(
+ process_pb.CloseStdinRequest(
+ process=process_pb.ProcessSelector(selector=Oneof("pid", pid)),
),
- request_timeout=self._connection_config.get_request_timeout(
- request_timeout
+ timeout_ms=timeout_to_ms(
+ self._connection_config.get_request_timeout(request_timeout)
),
)
except Exception as e:
@@ -195,7 +203,7 @@ class Commands:
:param on_stderr: Callback for command stderr output
:param stdin: If `True`, the command will have a stdin stream that you can send data to using `sandbox.commands.send_stdin()`
:param timeout: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time
- :param request_timeout: Timeout for the request in **seconds**
+ :param request_timeout: Timeout for opening the stream in **seconds** — the wait until envd confirms with a start event. The running stream is bounded by `timeout`
:return: `CommandResult` result of the command execution
"""
@@ -227,7 +235,7 @@ class Commands:
:param on_stderr: Callback for command stderr output
:param stdin: If `True`, the command will have a stdin stream that you can send data to using `sandbox.commands.send_stdin()`
:param timeout: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time
- :param request_timeout: Timeout for the request in **seconds**
+ :param request_timeout: Timeout for opening the stream in **seconds** — the wait until envd confirms with a start event. The running stream is bounded by `timeout`
:return: `AsyncCommandHandle` handle to interact with the running command
"""
@@ -282,35 +290,34 @@ class Commands:
on_stdout: Optional[OutputHandler[Stdout]],
on_stderr: Optional[OutputHandler[Stderr]],
) -> AsyncCommandHandle:
- events = self._rpc.astart(
- process_pb2.StartRequest(
- process=process_pb2.ProcessConfig(
- cmd="/bin/bash",
- envs=envs,
- args=["-l", "-c", cmd],
- cwd=cwd,
+ events = as_stream(
+ self._rpc.start(
+ process_pb.StartRequest(
+ process=process_pb.ProcessConfig(
+ cmd="/bin/bash",
+ envs=envs,
+ args=["-l", "-c", cmd],
+ cwd=cwd,
+ ),
+ stdin=stdin,
),
- stdin=stdin,
- ),
- headers={
- **authentication_header(self._envd_version, user),
- KEEPALIVE_PING_HEADER: str(KEEPALIVE_PING_INTERVAL_SEC),
- },
- timeout=timeout,
- request_timeout=self._connection_config.get_request_timeout(
- request_timeout
- ),
+ headers={
+ **authentication_header(self._envd_version, user),
+ KEEPALIVE_PING_HEADER: str(KEEPALIVE_PING_INTERVAL_SEC),
+ },
+ # The command `timeout` bounds the whole stream;
+ # `request_timeout` bounds opening it (the wait for the
+ # start event below).
+ timeout_ms=timeout_to_ms(timeout),
+ )
)
try:
- start_event = await events.__anext__()
-
- if not start_event.HasField("event"):
- raise SandboxException(
- f"Failed to start process: expected start event, got {start_event}"
- )
+ start_event = await first_event(
+ events, self._connection_config.get_request_timeout(request_timeout)
+ )
- pid = start_event.event.start.pid
+ pid = extract_start_pid(start_event, "start process")
return AsyncCommandHandle(
pid=pid,
handle_kill=lambda: self.kill(pid),
@@ -345,35 +352,31 @@ class Commands:
You can use `AsyncCommandHandle.wait()` to wait for the command to finish and get execution results.
:param pid: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()`
- :param request_timeout: Request timeout in **seconds**
+ :param request_timeout: Timeout for opening the stream in **seconds** — the wait until envd confirms with a start event. The running stream is bounded by `timeout`
:param timeout: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time
:param on_stdout: Callback for command stdout output
:param on_stderr: Callback for command stderr output
:return: `AsyncCommandHandle` handle to interact with the running command
"""
- events = self._rpc.aconnect(
- process_pb2.ConnectRequest(
- process=process_pb2.ProcessSelector(pid=pid),
- ),
- headers={
- KEEPALIVE_PING_HEADER: str(KEEPALIVE_PING_INTERVAL_SEC),
- },
- timeout=timeout,
- request_timeout=self._connection_config.get_request_timeout(
- request_timeout
- ),
+ events = as_stream(
+ self._rpc.connect(
+ process_pb.ConnectRequest(
+ process=process_pb.ProcessSelector(selector=Oneof("pid", pid)),
+ ),
+ headers={
+ KEEPALIVE_PING_HEADER: str(KEEPALIVE_PING_INTERVAL_SEC),
+ },
+ timeout_ms=timeout_to_ms(timeout),
+ )
)
try:
- start_event = await events.__anext__()
-
- if not start_event.HasField("event"):
- raise SandboxException(
- f"Failed to connect to process: expected start event, got {start_event}"
- )
+ start_event = await first_event(
+ events, self._connection_config.get_request_timeout(request_timeout)
+ )
- pid = start_event.event.start.pid
+ pid = extract_start_pid(start_event, "connect to process")
return AsyncCommandHandle(
pid=pid,
handle_kill=lambda: self.kill(pid),
diff --git a/packages/python-sdk/e2b/sandbox_async/commands/command_handle.py b/packages/python-sdk/e2b/sandbox_async/commands/command_handle.py
index a8436beb1..4168cfe63 100644
--- a/packages/python-sdk/e2b/sandbox_async/commands/command_handle.py
+++ b/packages/python-sdk/e2b/sandbox_async/commands/command_handle.py
@@ -14,7 +14,9 @@ from typing import (
)
from e2b.envd.rpc import ahandle_rpc_exception_with_health
-from e2b.envd.process import process_pb2
+from protobuf import Oneof
+
+from e2b.envd.process import process_pb
from e2b.exceptions import SandboxException
from e2b.sandbox.commands.command_handle import (
CommandExitException,
@@ -81,7 +83,7 @@ class AsyncCommandHandle:
pid: int,
handle_kill: Callable[[], Coroutine[Any, Any, bool]],
events: AsyncGenerator[
- Union[process_pb2.StartResponse, process_pb2.ConnectResponse], Any
+ Union[process_pb.StartResponse, process_pb.ConnectResponse], Any
],
on_stdout: Optional[OutputHandler[Stdout]] = None,
on_stderr: Optional[OutputHandler[Stderr]] = None,
@@ -148,33 +150,40 @@ class AsyncCommandHandle:
]:
try:
async for event in self._events:
- if event.event.HasField("data"):
- if event.event.data.stdout:
- out = self._stdout_decoder.decode(event.event.data.stdout)
- if out:
- self._stdout_chunks.append(out)
- yield out, None, None
- if event.event.data.stderr:
- out = self._stderr_decoder.decode(event.event.data.stderr)
- if out:
- self._stderr_chunks.append(out)
- yield None, out, None
- if event.event.data.pty:
- yield None, None, event.event.data.pty
- if event.event.HasField("end"):
- # Flush trailing decoder bytes into the accumulators and
- # record the result before yielding the flushed chunks, so a
- # consumer that stops iterating on the first flushed chunk
- # still observes the exit code.
- flushed = list(self._flush_decoders())
- self._result = CommandResult(
- stdout="".join(self._stdout_chunks),
- stderr="".join(self._stderr_chunks),
- exit_code=event.event.end.exit_code,
- error=event.event.end.error,
- )
- for f in flushed:
- yield f
+ # `event.event` is the ProcessEvent; its `event` oneof holds the
+ # actual payload (start/data/end/keepalive).
+ oneof = event.event.event if event.event is not None else None
+ match oneof:
+ case Oneof(field="data", value=data):
+ match data.output:
+ case Oneof(field="stdout", value=chunk) if chunk:
+ out = self._stdout_decoder.decode(chunk)
+ if out:
+ self._stdout_chunks.append(out)
+ yield out, None, None
+ case Oneof(field="stderr", value=chunk) if chunk:
+ out = self._stderr_decoder.decode(chunk)
+ if out:
+ self._stderr_chunks.append(out)
+ yield None, out, None
+ case Oneof(field="pty", value=chunk) if chunk:
+ yield None, None, chunk
+ case Oneof(field="end", value=end):
+ # Flush trailing decoder bytes into the accumulators and
+ # record the result before yielding the flushed chunks, so a
+ # consumer that stops iterating on the first flushed chunk
+ # still observes the exit code.
+ flushed = list(self._flush_decoders())
+ self._result = CommandResult(
+ stdout="".join(self._stdout_chunks),
+ stderr="".join(self._stderr_chunks),
+ exit_code=end.exit_code,
+ # Optional scalar: unset reads as "" — the presence
+ # check keeps it None, matching the JS SDK
+ error=end.error if end.has_field("error") else None,
+ )
+ for f in flushed:
+ yield f
except Exception:
# The stream raised before an end event (e.g. disconnect or RPC
# failure). Flush any bytes still buffered in the decoders so
diff --git a/packages/python-sdk/e2b/sandbox_async/commands/pty.py b/packages/python-sdk/e2b/sandbox_async/commands/pty.py
index db793f2d0..15d75b1bb 100644
--- a/packages/python-sdk/e2b/sandbox_async/commands/pty.py
+++ b/packages/python-sdk/e2b/sandbox_async/commands/pty.py
@@ -1,20 +1,27 @@
from typing import Dict, Optional
-import e2b_connect
-import httpcore
import httpx
+from connectrpc.code import Code
+from connectrpc.errors import ConnectError
from packaging.version import Version
-from e2b.envd.process import process_connect, process_pb2
+from protobuf import Oneof
+
+from e2b.envd.process import process_connect, process_pb
from e2b.connection_config import (
Username,
ConnectionConfig,
KEEPALIVE_PING_HEADER,
KEEPALIVE_PING_INTERVAL_SEC,
)
-from e2b.exceptions import SandboxException
from e2b.envd.api import acheck_sandbox_health
-from e2b.envd.rpc import authentication_header, ahandle_rpc_exception_with_health
+from e2b.envd.rpc import ahandle_rpc_exception_with_health
+from e2b.envd.utils import (
+ authentication_header,
+ extract_start_pid,
+ timeout_to_ms,
+)
+from e2b.envd.client_async import as_stream, create_rpc_client, first_event
from e2b.sandbox.commands.command_handle import PtySize
from e2b.sandbox_async.commands.command_handle import (
AsyncCommandHandle,
@@ -32,21 +39,16 @@ class Pty:
self,
envd_api_url: str,
connection_config: ConnectionConfig,
- pool: httpcore.AsyncConnectionPool,
envd_version: Version,
envd_api: httpx.AsyncClient,
) -> None:
self._connection_config = connection_config
self._envd_version = envd_version
self._check_health = lambda: acheck_sandbox_health(envd_api)
- self._rpc = process_connect.ProcessClient(
+ self._rpc = create_rpc_client(
+ process_connect.ProcessClient,
envd_api_url,
- # TODO: Fix and enable compression again — the headers compression is not solved for streaming.
- # compressor=e2b_connect.GzipCompressor,
- async_pool=pool,
- json=True,
- headers=connection_config.sandbox_headers,
- logger=connection_config.logger,
+ connection_config,
)
async def kill(
@@ -63,19 +65,19 @@ class Pty:
:return: `true` if the PTY was killed, `false` if the PTY was not found
"""
try:
- await self._rpc.asend_signal(
- process_pb2.SendSignalRequest(
- process=process_pb2.ProcessSelector(pid=pid),
- signal=process_pb2.Signal.SIGNAL_SIGKILL,
+ await self._rpc.send_signal(
+ process_pb.SendSignalRequest(
+ process=process_pb.ProcessSelector(selector=Oneof("pid", pid)),
+ signal=process_pb.Signal.SIGKILL,
),
- request_timeout=self._connection_config.get_request_timeout(
- request_timeout
+ timeout_ms=timeout_to_ms(
+ self._connection_config.get_request_timeout(request_timeout)
),
)
return True
except Exception as e:
- if isinstance(e, e2b_connect.ConnectException):
- if e.status == e2b_connect.Code.not_found:
+ if isinstance(e, ConnectError):
+ if e.code == Code.NOT_FOUND:
return False
raise await ahandle_rpc_exception_with_health(e, self._check_health)
@@ -93,15 +95,15 @@ class Pty:
:param request_timeout: Timeout for the request in **seconds**
"""
try:
- await self._rpc.asend_input(
- process_pb2.SendInputRequest(
- process=process_pb2.ProcessSelector(pid=pid),
- input=process_pb2.ProcessInput(
- pty=data,
+ await self._rpc.send_input(
+ process_pb.SendInputRequest(
+ process=process_pb.ProcessSelector(selector=Oneof("pid", pid)),
+ input=process_pb.ProcessInput(
+ input=Oneof("pty", data),
),
),
- request_timeout=self._connection_config.get_request_timeout(
- request_timeout
+ timeout_ms=timeout_to_ms(
+ self._connection_config.get_request_timeout(request_timeout)
),
)
except Exception as e:
@@ -126,7 +128,7 @@ class Pty:
:param cwd: Working directory for the PTY
:param envs: Environment variables for the PTY
:param timeout: Timeout for the PTY in **seconds**
- :param request_timeout: Timeout for the request in **seconds**
+ :param request_timeout: Timeout for opening the stream in **seconds** — the wait until envd confirms with a start event. The running stream is bounded by `timeout`
:return: Handle to interact with the PTY
"""
@@ -134,39 +136,36 @@ class Pty:
envs.setdefault("TERM", "xterm-256color")
envs.setdefault("LANG", "C.UTF-8")
envs.setdefault("LC_ALL", "C.UTF-8")
- events = self._rpc.astart(
- process_pb2.StartRequest(
- process=process_pb2.ProcessConfig(
- cmd="/bin/bash",
- envs=envs,
- args=["-i", "-l"],
- cwd=cwd,
- ),
- pty=process_pb2.PTY(
- size=process_pb2.PTY.Size(rows=size.rows, cols=size.cols)
+ events = as_stream(
+ self._rpc.start(
+ process_pb.StartRequest(
+ process=process_pb.ProcessConfig(
+ cmd="/bin/bash",
+ envs=envs,
+ args=["-i", "-l"],
+ cwd=cwd,
+ ),
+ pty=process_pb.PTY(
+ size=process_pb.PTY.Size(rows=size.rows, cols=size.cols)
+ ),
),
- ),
- headers={
- **authentication_header(self._envd_version, user),
- KEEPALIVE_PING_HEADER: str(KEEPALIVE_PING_INTERVAL_SEC),
- },
- timeout=timeout,
- request_timeout=self._connection_config.get_request_timeout(
- request_timeout
- ),
+ headers={
+ **authentication_header(self._envd_version, user),
+ KEEPALIVE_PING_HEADER: str(KEEPALIVE_PING_INTERVAL_SEC),
+ },
+ timeout_ms=timeout_to_ms(timeout),
+ )
)
try:
- start_event = await events.__anext__()
-
- if not start_event.HasField("event"):
- raise SandboxException(
- f"Failed to start process: expected start event, got {start_event}"
- )
+ start_event = await first_event(
+ events, self._connection_config.get_request_timeout(request_timeout)
+ )
+ pid = extract_start_pid(start_event, "start process")
return AsyncCommandHandle(
- pid=start_event.event.start.pid,
- handle_kill=lambda: self.kill(start_event.event.start.pid),
+ pid=pid,
+ handle_kill=lambda: self.kill(pid),
events=events,
on_pty=on_data,
check_health=self._check_health,
@@ -191,34 +190,31 @@ class Pty:
:param pid: Process ID of the PTY to connect to. You can get the list of running PTYs using `sandbox.pty.list()`.
:param on_data: Callback to handle PTY data
:param timeout: Timeout for the PTY connection in **seconds**. Using `0` will not limit the connection time
- :param request_timeout: Timeout for the request in **seconds**
+ :param request_timeout: Timeout for opening the stream in **seconds** — the wait until envd confirms with a start event. The running stream is bounded by `timeout`
:return: Handle to interact with the PTY
"""
- events = self._rpc.aconnect(
- process_pb2.ConnectRequest(
- process=process_pb2.ProcessSelector(pid=pid),
- ),
- timeout=timeout,
- request_timeout=self._connection_config.get_request_timeout(
- request_timeout
- ),
- headers={
- KEEPALIVE_PING_HEADER: str(KEEPALIVE_PING_INTERVAL_SEC),
- },
+ events = as_stream(
+ self._rpc.connect(
+ process_pb.ConnectRequest(
+ process=process_pb.ProcessSelector(selector=Oneof("pid", pid)),
+ ),
+ timeout_ms=timeout_to_ms(timeout),
+ headers={
+ KEEPALIVE_PING_HEADER: str(KEEPALIVE_PING_INTERVAL_SEC),
+ },
+ )
)
try:
- start_event = await events.__anext__()
-
- if not start_event.HasField("event"):
- raise SandboxException(
- f"Failed to connect to process: expected start event, got {start_event}"
- )
+ start_event = await first_event(
+ events, self._connection_config.get_request_timeout(request_timeout)
+ )
+ pid = extract_start_pid(start_event, "connect to process")
return AsyncCommandHandle(
- pid=start_event.event.start.pid,
- handle_kill=lambda: self.kill(start_event.event.start.pid),
+ pid=pid,
+ handle_kill=lambda: self.kill(pid),
events=events,
on_pty=on_data,
check_health=self._check_health,
@@ -244,14 +240,17 @@ class Pty:
:param size: New size of the PTY
:param request_timeout: Timeout for the request in **seconds**
"""
- await self._rpc.aupdate(
- process_pb2.UpdateRequest(
- process=process_pb2.ProcessSelector(pid=pid),
- pty=process_pb2.PTY(
- size=process_pb2.PTY.Size(rows=size.rows, cols=size.cols),
+ try:
+ await self._rpc.update(
+ process_pb.UpdateRequest(
+ process=process_pb.ProcessSelector(selector=Oneof("pid", pid)),
+ pty=process_pb.PTY(
+ size=process_pb.PTY.Size(rows=size.rows, cols=size.cols),
+ ),
),
- ),
- request_timeout=self._connection_config.get_request_timeout(
- request_timeout
- ),
- )
+ timeout_ms=timeout_to_ms(
+ self._connection_config.get_request_timeout(request_timeout)
+ ),
+ )
+ except Exception as e:
+ raise await ahandle_rpc_exception_with_health(e, self._check_health)
diff --git a/packages/python-sdk/e2b/sandbox_async/filesystem/filesystem.py b/packages/python-sdk/e2b/sandbox_async/filesystem/filesystem.py
index e40be70e8..24d25d933 100644
--- a/packages/python-sdk/e2b/sandbox_async/filesystem/filesystem.py
+++ b/packages/python-sdk/e2b/sandbox_async/filesystem/filesystem.py
@@ -2,11 +2,11 @@ import asyncio
from typing import IO, Dict, List, Literal, Optional, Union, overload
-import httpcore
import httpx
+from connectrpc.code import Code
+from connectrpc.errors import ConnectError
from packaging.version import Version
-import e2b_connect as connect
from e2b.connection_config import (
KEEPALIVE_PING_HEADER,
KEEPALIVE_PING_INTERVAL_SEC,
@@ -20,8 +20,12 @@ from e2b.envd.api import (
ahandle_envd_api_exception,
ahandle_envd_api_transport_exception_with_health,
)
-from e2b.envd.filesystem import filesystem_connect, filesystem_pb2
-from e2b.envd.rpc import authentication_header, ahandle_rpc_exception_with_health
+from protobuf import Oneof
+
+from e2b.envd.filesystem import filesystem_connect, filesystem_pb
+from e2b.envd.rpc import ahandle_rpc_exception_with_health
+from e2b.envd.utils import authentication_header, timeout_to_ms
+from e2b.envd.client_async import as_stream, create_rpc_client, first_event
from e2b.envd.versions import (
ENVD_DEFAULT_USER,
ENVD_FILE_METADATA,
@@ -51,10 +55,9 @@ from e2b.sandbox.filesystem.filesystem import (
from e2b.sandbox.filesystem.watch_handle import FilesystemEvent
from e2b.sandbox_async.filesystem.watch_handle import AsyncWatchHandle
from e2b.sandbox_async.utils import OutputHandler
-from e2b_connect.client import Code
_FILESYSTEM_RPC_ERROR_MAP = {
- Code.not_found: FileNotFoundException,
+ Code.NOT_FOUND: FileNotFoundException,
}
_FILESYSTEM_HTTP_ERROR_MAP = {
@@ -84,23 +87,17 @@ class Filesystem:
envd_api_url: str,
envd_version: Version,
connection_config: ConnectionConfig,
- pool: httpcore.AsyncConnectionPool,
envd_api: httpx.AsyncClient,
) -> None:
self._envd_api_url = envd_api_url
self._envd_version = envd_version
self._connection_config = connection_config
- self._pool = pool
self._envd_api = envd_api
- self._rpc = filesystem_connect.FilesystemClient(
+ self._rpc = create_rpc_client(
+ filesystem_connect.FilesystemClient,
envd_api_url,
- # TODO: Fix and enable compression again — the headers compression is not solved for streaming.
- # compressor=e2b_connect.GzipCompressor,
- async_pool=pool,
- json=True,
- headers=connection_config.sandbox_headers,
- logger=connection_config.logger,
+ connection_config,
)
@overload
@@ -470,10 +467,10 @@ class Filesystem:
raise InvalidArgumentException("depth should be at least 1")
try:
- res = await self._rpc.alist_dir(
- filesystem_pb2.ListDirRequest(path=path, depth=depth),
- request_timeout=self._connection_config.get_request_timeout(
- request_timeout
+ res = await self._rpc.list_dir(
+ filesystem_pb.ListDirRequest(path=path, depth=depth or 0),
+ timeout_ms=timeout_to_ms(
+ self._connection_config.get_request_timeout(request_timeout)
),
headers=authentication_header(self._envd_version, user),
)
@@ -504,10 +501,10 @@ class Filesystem:
:return: `True` if the file or directory exists, `False` otherwise
"""
try:
- await self._rpc.astat(
- filesystem_pb2.StatRequest(path=path),
- request_timeout=self._connection_config.get_request_timeout(
- request_timeout
+ await self._rpc.stat(
+ filesystem_pb.StatRequest(path=path),
+ timeout_ms=timeout_to_ms(
+ self._connection_config.get_request_timeout(request_timeout)
),
headers=authentication_header(self._envd_version, user),
)
@@ -515,8 +512,8 @@ class Filesystem:
return True
except Exception as e:
- if isinstance(e, connect.ConnectException):
- if e.status == connect.Code.not_found:
+ if isinstance(e, ConnectError):
+ if e.code == Code.NOT_FOUND:
return False
raise await _ahandle_filesystem_rpc_exception(e, self._envd_api)
@@ -536,15 +533,15 @@ class Filesystem:
:return: Information about the file or directory like name, type, and path
"""
try:
- r = await self._rpc.astat(
- filesystem_pb2.StatRequest(path=path),
- request_timeout=self._connection_config.get_request_timeout(
- request_timeout
+ r = await self._rpc.stat(
+ filesystem_pb.StatRequest(path=path),
+ timeout_ms=timeout_to_ms(
+ self._connection_config.get_request_timeout(request_timeout)
),
headers=authentication_header(self._envd_version, user),
)
- return map_entry_info(r.entry)
+ return map_entry_info(r.entry or filesystem_pb.EntryInfo())
except Exception as e:
raise await _ahandle_filesystem_rpc_exception(e, self._envd_api)
@@ -562,10 +559,10 @@ class Filesystem:
:param request_timeout: Timeout for the request in **seconds**
"""
try:
- await self._rpc.aremove(
- filesystem_pb2.RemoveRequest(path=path),
- request_timeout=self._connection_config.get_request_timeout(
- request_timeout
+ await self._rpc.remove(
+ filesystem_pb.RemoveRequest(path=path),
+ timeout_ms=timeout_to_ms(
+ self._connection_config.get_request_timeout(request_timeout)
),
headers=authentication_header(self._envd_version, user),
)
@@ -590,18 +587,18 @@ class Filesystem:
:return: Information about the renamed file or directory
"""
try:
- r = await self._rpc.amove(
- filesystem_pb2.MoveRequest(
+ r = await self._rpc.move(
+ filesystem_pb.MoveRequest(
source=old_path,
destination=new_path,
),
- request_timeout=self._connection_config.get_request_timeout(
- request_timeout
+ timeout_ms=timeout_to_ms(
+ self._connection_config.get_request_timeout(request_timeout)
),
headers=authentication_header(self._envd_version, user),
)
- return map_entry_info(r.entry)
+ return map_entry_info(r.entry or filesystem_pb.EntryInfo())
except Exception as e:
raise await _ahandle_filesystem_rpc_exception(e, self._envd_api)
@@ -621,18 +618,18 @@ class Filesystem:
:return: `True` if the directory was created, `False` if the directory already exists
"""
try:
- await self._rpc.amake_dir(
- filesystem_pb2.MakeDirRequest(path=path),
- request_timeout=self._connection_config.get_request_timeout(
- request_timeout
+ await self._rpc.make_dir(
+ filesystem_pb.MakeDirRequest(path=path),
+ timeout_ms=timeout_to_ms(
+ self._connection_config.get_request_timeout(request_timeout)
),
headers=authentication_header(self._envd_version, user),
)
return True
except Exception as e:
- if isinstance(e, connect.ConnectException):
- if e.status == connect.Code.already_exists:
+ if isinstance(e, ConnectError):
+ if e.code == Code.ALREADY_EXISTS:
return False
raise await _ahandle_filesystem_rpc_exception(e, self._envd_api)
@@ -655,7 +652,7 @@ class Filesystem:
:param on_event: Callback to call on each event in the directory
:param on_exit: Callback to call when the watching ends. It receives the error that ended the watch, or `None` on a clean end or when `stop()` is called
:param user: Run the operation as this user
- :param request_timeout: Timeout for the request in **seconds**
+ :param request_timeout: Timeout for opening the stream in **seconds** — the wait until envd confirms with a start event. The running watch is bounded by `timeout`
:param timeout: Timeout for the watch operation in **seconds**. Using `0` will not limit the watch time
:param recursive: Watch directory recursively
:param include_entry: Include the `EntryInfo` of the affected entry in each event, when available. Requires envd 0.6.3 or later
@@ -681,30 +678,37 @@ class Filesystem:
"You need to update the template to watch directories on network mounts."
)
- events = self._rpc.awatch_dir(
- filesystem_pb2.WatchDirRequest(
- path=path,
- recursive=recursive,
- include_entry=include_entry,
- allow_network_mounts=allow_network_mounts,
- ),
- request_timeout=self._connection_config.get_request_timeout(
- request_timeout
- ),
- timeout=timeout,
- headers={
- **authentication_header(self._envd_version, user),
- KEEPALIVE_PING_HEADER: str(KEEPALIVE_PING_INTERVAL_SEC),
- },
+ events = as_stream(
+ self._rpc.watch_dir(
+ filesystem_pb.WatchDirRequest(
+ path=path,
+ recursive=recursive,
+ include_entry=include_entry,
+ allow_network_mounts=allow_network_mounts,
+ ),
+ # The watch `timeout` bounds the whole stream;
+ # `request_timeout` bounds opening it (the wait for the
+ # start event below).
+ timeout_ms=timeout_to_ms(timeout),
+ headers={
+ **authentication_header(self._envd_version, user),
+ KEEPALIVE_PING_HEADER: str(KEEPALIVE_PING_INTERVAL_SEC),
+ },
+ )
)
try:
- start_event = await events.__anext__()
+ start_event = await first_event(
+ events, self._connection_config.get_request_timeout(request_timeout)
+ )
- if not start_event.HasField("start"):
- raise SandboxException(
- f"Failed to start watch: expected start event, got {start_event}",
- )
+ match start_event.event:
+ case Oneof(field="start"):
+ pass
+ case _:
+ raise SandboxException(
+ f"Failed to start watch: expected start event, got {start_event}",
+ )
return AsyncWatchHandle(
events=events,
diff --git a/packages/python-sdk/e2b/sandbox_async/filesystem/watch_handle.py b/packages/python-sdk/e2b/sandbox_async/filesystem/watch_handle.py
index 814b46508..30d70889d 100644
--- a/packages/python-sdk/e2b/sandbox_async/filesystem/watch_handle.py
+++ b/packages/python-sdk/e2b/sandbox_async/filesystem/watch_handle.py
@@ -4,7 +4,9 @@ import inspect
from typing import Any, AsyncGenerator, Awaitable, Callable, Optional
from e2b.envd.rpc import ahandle_rpc_exception_with_health
-from e2b.envd.filesystem.filesystem_pb2 import WatchDirResponse
+from protobuf import Oneof
+
+from e2b.envd.filesystem.filesystem_pb import WatchDirResponse
from e2b.sandbox.filesystem.filesystem import map_entry_info
from e2b.sandbox.filesystem.watch_handle import FilesystemEvent, map_event_type
from e2b.sandbox_async.utils import OutputHandler
@@ -45,18 +47,19 @@ class AsyncWatchHandle:
async def _iterate_events(self):
try:
async for event in self._events:
- if event.HasField("filesystem"):
- event_type = map_event_type(event.filesystem.type)
- if event_type:
- yield FilesystemEvent(
- name=event.filesystem.name,
- type=event_type,
- entry=(
- map_entry_info(event.filesystem.entry)
- if event.filesystem.HasField("entry")
- else None
- ),
- )
+ match event.event:
+ case Oneof(field="filesystem", value=fs_event):
+ event_type = map_event_type(fs_event.type)
+ if event_type:
+ yield FilesystemEvent(
+ name=fs_event.name,
+ type=event_type,
+ entry=(
+ map_entry_info(fs_event.entry)
+ if fs_event.entry is not None
+ else None
+ ),
+ )
except Exception as e:
raise await ahandle_rpc_exception_with_health(e, self._check_health)
diff --git a/packages/python-sdk/e2b/sandbox_async/main.py b/packages/python-sdk/e2b/sandbox_async/main.py
index 3cbc490f1..40ff5a2e1 100644
--- a/packages/python-sdk/e2b/sandbox_async/main.py
+++ b/packages/python-sdk/e2b/sandbox_async/main.py
@@ -116,20 +116,17 @@ class AsyncSandbox(SandboxApi):
self.envd_api_url,
self._envd_version,
self.connection_config,
- self._transport.pool,
self._envd_api,
)
self._commands = Commands(
self.envd_api_url,
self.connection_config,
- self._transport.pool,
self._envd_version,
self._envd_api,
)
self._pty = Pty(
self.envd_api_url,
self.connection_config,
- self._transport.pool,
self._envd_version,
self._envd_api,
)
diff --git a/packages/python-sdk/e2b/sandbox_sync/commands/command.py b/packages/python-sdk/e2b/sandbox_sync/commands/command.py
index 971d79293..d1cf6e0fe 100644
--- a/packages/python-sdk/e2b/sandbox_sync/commands/command.py
+++ b/packages/python-sdk/e2b/sandbox_sync/commands/command.py
@@ -1,8 +1,9 @@
import threading
from typing import Callable, Dict, List, Literal, Optional, Union, overload
-import e2b_connect
import httpx
+from connectrpc.code import Code
+from connectrpc.errors import ConnectError
from packaging.version import Version
from e2b.api import make_logging_event_hooks
from e2b.api.client_sync import get_envd_transport
@@ -12,9 +13,17 @@ from e2b.connection_config import (
KEEPALIVE_PING_HEADER,
KEEPALIVE_PING_INTERVAL_SEC,
)
-from e2b.envd.process import process_connect, process_pb2
+from protobuf import Oneof
+
+from e2b.envd.process import process_connect, process_pb
from e2b.envd.api import check_sandbox_health
-from e2b.envd.rpc import authentication_header, handle_rpc_exception_with_health
+from e2b.envd.rpc import handle_rpc_exception_with_health
+from e2b.envd.utils import (
+ authentication_header,
+ extract_start_pid,
+ timeout_to_ms,
+)
+from e2b.envd.client_sync import as_stream, create_rpc_client
from e2b.envd.versions import ENVD_COMMANDS_STDIN, ENVD_ENVD_CLOSE
from e2b.exceptions import SandboxException
from e2b.sandbox.commands.main import ProcessInfo
@@ -37,6 +46,11 @@ class Commands:
self._connection_config = connection_config
self._envd_version = envd_version
self._thread_local = threading.local()
+ self._rpc = create_rpc_client(
+ process_connect.ProcessClientSync,
+ envd_api_url,
+ connection_config,
+ )
def _create_envd_api(self) -> httpx.Client:
transport = get_envd_transport(self._connection_config)
@@ -47,34 +61,16 @@ class Commands:
event_hooks=make_logging_event_hooks(self._connection_config.logger),
)
- def _create_rpc(self) -> process_connect.ProcessClient:
- transport = get_envd_transport(self._connection_config)
- return process_connect.ProcessClient(
- self._envd_api_url,
- # TODO: Fix and enable compression again — the headers compression is not solved for streaming.
- # compressor=e2b_connect.GzipCompressor,
- pool=transport.pool,
- json=True,
- headers=self._connection_config.sandbox_headers,
- logger=self._connection_config.logger,
- )
-
@property
def _envd_api(self) -> httpx.Client:
+ # Unlike the shared RPC client, the httpx transports are per-thread
+ # (see e2b.api.client_sync), so the client wrapping them is too.
envd_api = getattr(self._thread_local, "envd_api", None)
if envd_api is None:
envd_api = self._create_envd_api()
self._thread_local.envd_api = envd_api
return envd_api
- @property
- def _rpc(self) -> process_connect.ProcessClient:
- rpc = getattr(self._thread_local, "rpc", None)
- if rpc is None:
- rpc = self._create_rpc()
- self._thread_local.rpc = rpc
- return rpc
-
def _check_health(self) -> Optional[bool]:
return check_sandbox_health(self._envd_api)
@@ -91,21 +87,24 @@ class Commands:
"""
try:
res = self._rpc.list(
- process_pb2.ListRequest(),
- request_timeout=self._connection_config.get_request_timeout(
- request_timeout
+ process_pb.ListRequest(),
+ timeout_ms=timeout_to_ms(
+ self._connection_config.get_request_timeout(request_timeout)
),
)
return [
ProcessInfo(
pid=p.pid,
- tag=p.tag if p.HasField("tag") else None,
- cmd=p.config.cmd,
- args=list(p.config.args),
- envs=dict(p.config.envs),
- cwd=p.config.cwd if p.config.HasField("cwd") else None,
+ # Optional scalars: unset reads as "" — presence checks keep
+ # them None
+ tag=p.tag if p.has_field("tag") else None,
+ cmd=config.cmd,
+ args=list(config.args),
+ envs=dict(config.envs),
+ cwd=config.cwd if config.has_field("cwd") else None,
)
for p in res.processes
+ for config in (p.config or process_pb.ProcessConfig(),)
]
except Exception as e:
raise handle_rpc_exception_with_health(e, self._check_health)
@@ -126,18 +125,18 @@ class Commands:
"""
try:
self._rpc.send_signal(
- process_pb2.SendSignalRequest(
- process=process_pb2.ProcessSelector(pid=pid),
- signal=process_pb2.Signal.SIGNAL_SIGKILL,
+ process_pb.SendSignalRequest(
+ process=process_pb.ProcessSelector(selector=Oneof("pid", pid)),
+ signal=process_pb.Signal.SIGKILL,
),
- request_timeout=self._connection_config.get_request_timeout(
- request_timeout
+ timeout_ms=timeout_to_ms(
+ self._connection_config.get_request_timeout(request_timeout)
),
)
return True
except Exception as e:
- if isinstance(e, e2b_connect.ConnectException):
- if e.status == e2b_connect.Code.not_found:
+ if isinstance(e, ConnectError):
+ if e.code == Code.NOT_FOUND:
return False
raise handle_rpc_exception_with_health(e, self._check_health)
@@ -156,14 +155,16 @@ class Commands:
"""
try:
self._rpc.send_input(
- process_pb2.SendInputRequest(
- process=process_pb2.ProcessSelector(pid=pid),
- input=process_pb2.ProcessInput(
- stdin=data.encode() if isinstance(data, str) else data,
+ process_pb.SendInputRequest(
+ process=process_pb.ProcessSelector(selector=Oneof("pid", pid)),
+ input=process_pb.ProcessInput(
+ input=Oneof(
+ "stdin", data.encode() if isinstance(data, str) else data
+ ),
),
),
- request_timeout=self._connection_config.get_request_timeout(
- request_timeout
+ timeout_ms=timeout_to_ms(
+ self._connection_config.get_request_timeout(request_timeout)
),
)
except Exception as e:
@@ -190,11 +191,11 @@ class Commands:
try:
self._rpc.close_stdin(
- process_pb2.CloseStdinRequest(
- process=process_pb2.ProcessSelector(pid=pid),
+ process_pb.CloseStdinRequest(
+ process=process_pb.ProcessSelector(selector=Oneof("pid", pid)),
),
- request_timeout=self._connection_config.get_request_timeout(
- request_timeout
+ timeout_ms=timeout_to_ms(
+ self._connection_config.get_request_timeout(request_timeout)
),
)
except Exception as e:
@@ -226,7 +227,7 @@ class Commands:
:param on_stderr: Callback for command stderr output
:param stdin: If `True`, the command will have a stdin stream that you can send data to using `sandbox.commands.send_stdin()`
:param timeout: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time
- :param request_timeout: Timeout for the request in **seconds**
+ :param request_timeout: Not applied to this streaming call — both opening the stream and the stream itself are bounded by `timeout` (unlimited when `0`)
:return: `CommandResult` result of the command execution
"""
@@ -256,7 +257,7 @@ class Commands:
:param cwd: Working directory to run the command
:param stdin: If `True`, the command will have a stdin stream that you can send data to using `sandbox.commands.send_stdin()`
:param timeout: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time
- :param request_timeout: Timeout for the request in **seconds**
+ :param request_timeout: Not applied to this streaming call — both opening the stream and the stream itself are bounded by `timeout` (unlimited when `0`)
:return: `CommandHandle` handle to interact with the running command
"""
@@ -314,35 +315,32 @@ class Commands:
timeout: Optional[float],
request_timeout: Optional[float],
):
- events = self._rpc.start(
- process_pb2.StartRequest(
- process=process_pb2.ProcessConfig(
- cmd="/bin/bash",
- envs=envs,
- args=["-l", "-c", cmd],
- cwd=cwd,
+ events = as_stream(
+ self._rpc.start(
+ process_pb.StartRequest(
+ process=process_pb.ProcessConfig(
+ cmd="/bin/bash",
+ envs=envs,
+ args=["-l", "-c", cmd],
+ cwd=cwd,
+ ),
+ stdin=stdin,
),
- stdin=stdin,
- ),
- headers={
- **authentication_header(self._envd_version, user),
- KEEPALIVE_PING_HEADER: str(KEEPALIVE_PING_INTERVAL_SEC),
- },
- timeout=timeout,
- request_timeout=self._connection_config.get_request_timeout(
- request_timeout
- ),
+ headers={
+ **authentication_header(self._envd_version, user),
+ KEEPALIVE_PING_HEADER: str(KEEPALIVE_PING_INTERVAL_SEC),
+ },
+ # The command `timeout` bounds the whole stream; `request_timeout`
+ # has no per-call equivalent here — connection setup is bounded by
+ # the transport's connect timeout instead.
+ timeout_ms=timeout_to_ms(timeout),
+ )
)
try:
start_event = events.__next__()
- if not start_event.HasField("event"):
- raise SandboxException(
- f"Failed to start process: expected start event, got {start_event}"
- )
-
- pid = start_event.event.start.pid
+ pid = extract_start_pid(start_event, "start process")
return CommandHandle(
pid=pid,
handle_kill=lambda: self.kill(pid),
@@ -374,32 +372,26 @@ class Commands:
:param pid: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()`
:param timeout: Timeout for the connection in **seconds**. Using `0` will not limit the connection time
- :param request_timeout: Timeout for the request in **seconds**
+ :param request_timeout: Not applied to this streaming call — both opening the stream and the stream itself are bounded by `timeout` (unlimited when `0`)
:return: `CommandHandle` handle to interact with the running command
"""
- events = self._rpc.connect(
- process_pb2.ConnectRequest(
- process=process_pb2.ProcessSelector(pid=pid),
- ),
- headers={
- KEEPALIVE_PING_HEADER: str(KEEPALIVE_PING_INTERVAL_SEC),
- },
- timeout=timeout,
- request_timeout=self._connection_config.get_request_timeout(
- request_timeout
- ),
+ events = as_stream(
+ self._rpc.connect(
+ process_pb.ConnectRequest(
+ process=process_pb.ProcessSelector(selector=Oneof("pid", pid)),
+ ),
+ headers={
+ KEEPALIVE_PING_HEADER: str(KEEPALIVE_PING_INTERVAL_SEC),
+ },
+ timeout_ms=timeout_to_ms(timeout),
+ )
)
try:
start_event = events.__next__()
- if not start_event.HasField("event"):
- raise SandboxException(
- f"Failed to connect to process: expected start event, got {start_event}"
- )
-
- pid = start_event.event.start.pid
+ pid = extract_start_pid(start_event, "connect to process")
return CommandHandle(
pid=pid,
handle_kill=lambda: self.kill(pid),
diff --git a/packages/python-sdk/e2b/sandbox_sync/commands/command_handle.py b/packages/python-sdk/e2b/sandbox_sync/commands/command_handle.py
index a9cf5fc79..ea2b3fdad 100644
--- a/packages/python-sdk/e2b/sandbox_sync/commands/command_handle.py
+++ b/packages/python-sdk/e2b/sandbox_sync/commands/command_handle.py
@@ -3,7 +3,9 @@ import codecs
from typing import Optional, Callable, Any, Generator, List, Union, Tuple
from e2b.envd.rpc import handle_rpc_exception_with_health
-from e2b.envd.process import process_pb2
+from protobuf import Oneof
+
+from e2b.envd.process import process_pb
from e2b.exceptions import SandboxException
from e2b.sandbox.commands.command_handle import (
CommandExitException,
@@ -33,7 +35,7 @@ class CommandHandle:
pid: int,
handle_kill: Callable[[], bool],
events: Generator[
- Union[process_pb2.StartResponse, process_pb2.ConnectResponse], Any, None
+ Union[process_pb.StartResponse, process_pb.ConnectResponse], Any, None
],
handle_send_stdin: Optional[
Callable[[Union[str, bytes], Optional[float]], None]
@@ -98,32 +100,39 @@ class CommandHandle:
]:
try:
for event in self._events:
- if event.event.HasField("data"):
- if event.event.data.stdout:
- out = self._stdout_decoder.decode(event.event.data.stdout)
- if out:
- self._stdout_chunks.append(out)
- yield out, None, None
- if event.event.data.stderr:
- out = self._stderr_decoder.decode(event.event.data.stderr)
- if out:
- self._stderr_chunks.append(out)
- yield None, out, None
- if event.event.data.pty:
- yield None, None, event.event.data.pty
- if event.event.HasField("end"):
- # Flush trailing decoder bytes into the accumulators and
- # record the result before yielding the flushed chunks, so a
- # consumer that stops iterating on the first flushed chunk
- # still observes the exit code.
- flushed = list(self._flush_decoders())
- self._result = CommandResult(
- stdout="".join(self._stdout_chunks),
- stderr="".join(self._stderr_chunks),
- exit_code=event.event.end.exit_code,
- error=event.event.end.error,
- )
- yield from flushed
+ # `event.event` is the ProcessEvent; its `event` oneof holds the
+ # actual payload (start/data/end/keepalive).
+ oneof = event.event.event if event.event is not None else None
+ match oneof:
+ case Oneof(field="data", value=data):
+ match data.output:
+ case Oneof(field="stdout", value=chunk) if chunk:
+ out = self._stdout_decoder.decode(chunk)
+ if out:
+ self._stdout_chunks.append(out)
+ yield out, None, None
+ case Oneof(field="stderr", value=chunk) if chunk:
+ out = self._stderr_decoder.decode(chunk)
+ if out:
+ self._stderr_chunks.append(out)
+ yield None, out, None
+ case Oneof(field="pty", value=chunk) if chunk:
+ yield None, None, chunk
+ case Oneof(field="end", value=end):
+ # Flush trailing decoder bytes into the accumulators and
+ # record the result before yielding the flushed chunks, so a
+ # consumer that stops iterating on the first flushed chunk
+ # still observes the exit code.
+ flushed = list(self._flush_decoders())
+ self._result = CommandResult(
+ stdout="".join(self._stdout_chunks),
+ stderr="".join(self._stderr_chunks),
+ exit_code=end.exit_code,
+ # Optional scalar: unset reads as "" — the presence
+ # check keeps it None, matching the JS SDK
+ error=end.error if end.has_field("error") else None,
+ )
+ yield from flushed
# If the stream closed without an end event (e.g. disconnect or a
# dropped connection), flush any bytes still buffered in the
@@ -175,9 +184,10 @@ class CommandHandle:
except StopIteration:
pass
except Exception as e:
- self._iteration_exception = handle_rpc_exception_with_health(
- e, self._check_health
- )
+ # `_handle_events` already maps stream errors (including the
+ # sandbox health probe for transport failures); mapping again here
+ # would probe health a second time.
+ self._iteration_exception = e
if self._iteration_exception:
raise self._iteration_exception
diff --git a/packages/python-sdk/e2b/sandbox_sync/commands/pty.py b/packages/python-sdk/e2b/sandbox_sync/commands/pty.py
index f0de8c0ee..90f2ee4d1 100644
--- a/packages/python-sdk/e2b/sandbox_sync/commands/pty.py
+++ b/packages/python-sdk/e2b/sandbox_sync/commands/pty.py
@@ -1,22 +1,30 @@
-import e2b_connect
import httpx
import threading
from typing import Dict, Optional
+from connectrpc.code import Code
+from connectrpc.errors import ConnectError
from packaging.version import Version
from e2b.api import make_logging_event_hooks
from e2b.api.client_sync import get_envd_transport
-from e2b.envd.process import process_connect, process_pb2
+from protobuf import Oneof
+
+from e2b.envd.process import process_connect, process_pb
from e2b.connection_config import (
Username,
ConnectionConfig,
KEEPALIVE_PING_HEADER,
KEEPALIVE_PING_INTERVAL_SEC,
)
-from e2b.exceptions import SandboxException
from e2b.envd.api import check_sandbox_health
-from e2b.envd.rpc import authentication_header, handle_rpc_exception_with_health
+from e2b.envd.rpc import handle_rpc_exception_with_health
+from e2b.envd.utils import (
+ authentication_header,
+ extract_start_pid,
+ timeout_to_ms,
+)
+from e2b.envd.client_sync import as_stream, create_rpc_client
from e2b.sandbox.commands.command_handle import PtySize
from e2b.sandbox_sync.commands.command_handle import CommandHandle
@@ -36,6 +44,11 @@ class Pty:
self._connection_config = connection_config
self._envd_version = envd_version
self._thread_local = threading.local()
+ self._rpc = create_rpc_client(
+ process_connect.ProcessClientSync,
+ envd_api_url,
+ connection_config,
+ )
def _create_envd_api(self) -> httpx.Client:
transport = get_envd_transport(self._connection_config)
@@ -46,34 +59,16 @@ class Pty:
event_hooks=make_logging_event_hooks(self._connection_config.logger),
)
- def _create_rpc(self) -> process_connect.ProcessClient:
- transport = get_envd_transport(self._connection_config)
- return process_connect.ProcessClient(
- self._envd_api_url,
- # TODO: Fix and enable compression again — the headers compression is not solved for streaming.
- # compressor=e2b_connect.GzipCompressor,
- pool=transport.pool,
- json=True,
- headers=self._connection_config.sandbox_headers,
- logger=self._connection_config.logger,
- )
-
@property
def _envd_api(self) -> httpx.Client:
+ # Unlike the shared RPC client, the httpx transports are per-thread
+ # (see e2b.api.client_sync), so the client wrapping them is too.
envd_api = getattr(self._thread_local, "envd_api", None)
if envd_api is None:
envd_api = self._create_envd_api()
self._thread_local.envd_api = envd_api
return envd_api
- @property
- def _rpc(self) -> process_connect.ProcessClient:
- rpc = getattr(self._thread_local, "rpc", None)
- if rpc is None:
- rpc = self._create_rpc()
- self._thread_local.rpc = rpc
- return rpc
-
def _check_health(self) -> Optional[bool]:
return check_sandbox_health(self._envd_api)
@@ -92,18 +87,18 @@ class Pty:
"""
try:
self._rpc.send_signal(
- process_pb2.SendSignalRequest(
- process=process_pb2.ProcessSelector(pid=pid),
- signal=process_pb2.Signal.SIGNAL_SIGKILL,
+ process_pb.SendSignalRequest(
+ process=process_pb.ProcessSelector(selector=Oneof("pid", pid)),
+ signal=process_pb.Signal.SIGKILL,
),
- request_timeout=self._connection_config.get_request_timeout(
- request_timeout
+ timeout_ms=timeout_to_ms(
+ self._connection_config.get_request_timeout(request_timeout)
),
)
return True
except Exception as e:
- if isinstance(e, e2b_connect.ConnectException):
- if e.status == e2b_connect.Code.not_found:
+ if isinstance(e, ConnectError):
+ if e.code == Code.NOT_FOUND:
return False
raise handle_rpc_exception_with_health(e, self._check_health)
@@ -122,14 +117,14 @@ class Pty:
"""
try:
self._rpc.send_input(
- process_pb2.SendInputRequest(
- process=process_pb2.ProcessSelector(pid=pid),
- input=process_pb2.ProcessInput(
- pty=data,
+ process_pb.SendInputRequest(
+ process=process_pb.ProcessSelector(selector=Oneof("pid", pid)),
+ input=process_pb.ProcessInput(
+ input=Oneof("pty", data),
),
),
- request_timeout=self._connection_config.get_request_timeout(
- request_timeout
+ timeout_ms=timeout_to_ms(
+ self._connection_config.get_request_timeout(request_timeout)
),
)
except Exception as e:
@@ -152,7 +147,7 @@ class Pty:
:param cwd: Working directory for the PTY
:param envs: Environment variables for the PTY
:param timeout: Timeout for the PTY in **seconds**
- :param request_timeout: Timeout for the request in **seconds**
+ :param request_timeout: Not applied to this streaming call — both opening the stream and the stream itself are bounded by `timeout` (unlimited when `0`)
:return: Handle to interact with the PTY
"""
@@ -160,39 +155,34 @@ class Pty:
envs.setdefault("TERM", "xterm-256color")
envs.setdefault("LANG", "C.UTF-8")
envs.setdefault("LC_ALL", "C.UTF-8")
- events = self._rpc.start(
- process_pb2.StartRequest(
- process=process_pb2.ProcessConfig(
- cmd="/bin/bash",
- envs=envs,
- args=["-i", "-l"],
- cwd=cwd,
- ),
- pty=process_pb2.PTY(
- size=process_pb2.PTY.Size(rows=size.rows, cols=size.cols)
+ events = as_stream(
+ self._rpc.start(
+ process_pb.StartRequest(
+ process=process_pb.ProcessConfig(
+ cmd="/bin/bash",
+ envs=envs,
+ args=["-i", "-l"],
+ cwd=cwd,
+ ),
+ pty=process_pb.PTY(
+ size=process_pb.PTY.Size(rows=size.rows, cols=size.cols)
+ ),
),
- ),
- headers={
- **authentication_header(self._envd_version, user),
- KEEPALIVE_PING_HEADER: str(KEEPALIVE_PING_INTERVAL_SEC),
- },
- timeout=timeout,
- request_timeout=self._connection_config.get_request_timeout(
- request_timeout
- ),
+ headers={
+ **authentication_header(self._envd_version, user),
+ KEEPALIVE_PING_HEADER: str(KEEPALIVE_PING_INTERVAL_SEC),
+ },
+ timeout_ms=timeout_to_ms(timeout),
+ )
)
try:
start_event = events.__next__()
- if not start_event.HasField("event"):
- raise SandboxException(
- f"Failed to start process: expected start event, got {start_event}"
- )
-
+ pid = extract_start_pid(start_event, "start process")
return CommandHandle(
- pid=start_event.event.start.pid,
- handle_kill=lambda: self.kill(start_event.event.start.pid),
+ pid=pid,
+ handle_kill=lambda: self.kill(pid),
events=events,
check_health=self._check_health,
)
@@ -214,34 +204,29 @@ class Pty:
:param pid: Process ID of the PTY to connect to. You can get the list of running PTYs using `sandbox.pty.list()`.
:param timeout: Timeout for the PTY connection in **seconds**. Using `0` will not limit the connection time
- :param request_timeout: Timeout for the request in **seconds**
+ :param request_timeout: Not applied to this streaming call — both opening the stream and the stream itself are bounded by `timeout` (unlimited when `0`)
:return: Handle to interact with the PTY
"""
- events = self._rpc.connect(
- process_pb2.ConnectRequest(
- process=process_pb2.ProcessSelector(pid=pid),
- ),
- headers={
- KEEPALIVE_PING_HEADER: str(KEEPALIVE_PING_INTERVAL_SEC),
- },
- timeout=timeout,
- request_timeout=self._connection_config.get_request_timeout(
- request_timeout
- ),
+ events = as_stream(
+ self._rpc.connect(
+ process_pb.ConnectRequest(
+ process=process_pb.ProcessSelector(selector=Oneof("pid", pid)),
+ ),
+ headers={
+ KEEPALIVE_PING_HEADER: str(KEEPALIVE_PING_INTERVAL_SEC),
+ },
+ timeout_ms=timeout_to_ms(timeout),
+ )
)
try:
start_event = events.__next__()
- if not start_event.HasField("event"):
- raise SandboxException(
- f"Failed to connect to process: expected start event, got {start_event}"
- )
-
+ pid = extract_start_pid(start_event, "connect to process")
return CommandHandle(
- pid=start_event.event.start.pid,
- handle_kill=lambda: self.kill(start_event.event.start.pid),
+ pid=pid,
+ handle_kill=lambda: self.kill(pid),
events=events,
check_health=self._check_health,
)
@@ -266,14 +251,17 @@ class Pty:
:param size: New size of the PTY
:param request_timeout: Timeout for the request in **seconds**
"""
- self._rpc.update(
- process_pb2.UpdateRequest(
- process=process_pb2.ProcessSelector(pid=pid),
- pty=process_pb2.PTY(
- size=process_pb2.PTY.Size(rows=size.rows, cols=size.cols),
+ try:
+ self._rpc.update(
+ process_pb.UpdateRequest(
+ process=process_pb.ProcessSelector(selector=Oneof("pid", pid)),
+ pty=process_pb.PTY(
+ size=process_pb.PTY.Size(rows=size.rows, cols=size.cols),
+ ),
),
- ),
- request_timeout=self._connection_config.get_request_timeout(
- request_timeout
- ),
- )
+ timeout_ms=timeout_to_ms(
+ self._connection_config.get_request_timeout(request_timeout)
+ ),
+ )
+ except Exception as e:
+ raise handle_rpc_exception_with_health(e, self._check_health)
diff --git a/packages/python-sdk/e2b/sandbox_sync/filesystem/filesystem.py b/packages/python-sdk/e2b/sandbox_sync/filesystem/filesystem.py
index 0b9028ad7..aaecb07cf 100644
--- a/packages/python-sdk/e2b/sandbox_sync/filesystem/filesystem.py
+++ b/packages/python-sdk/e2b/sandbox_sync/filesystem/filesystem.py
@@ -2,9 +2,10 @@ import threading
from typing import IO, Dict, List, Literal, Optional, Union, overload
import httpx
+from connectrpc.code import Code
+from connectrpc.errors import ConnectError
from packaging.version import Version
-import e2b_connect
from e2b.api import make_logging_event_hooks
from e2b.api.client_sync import get_envd_transport
from e2b.connection_config import (
@@ -14,7 +15,6 @@ from e2b.connection_config import (
Username,
default_username,
)
-from e2b_connect.client import Code
from e2b.envd.api import (
ENVD_API_FILES_ROUTE,
@@ -22,8 +22,10 @@ from e2b.envd.api import (
handle_envd_api_exception,
handle_envd_api_transport_exception_with_health,
)
-from e2b.envd.filesystem import filesystem_connect, filesystem_pb2
-from e2b.envd.rpc import authentication_header, handle_rpc_exception_with_health
+from e2b.envd.filesystem import filesystem_connect, filesystem_pb
+from e2b.envd.rpc import handle_rpc_exception_with_health
+from e2b.envd.utils import authentication_header, timeout_to_ms
+from e2b.envd.client_sync import create_rpc_client
from e2b.envd.versions import (
ENVD_DEFAULT_USER,
ENVD_FILE_METADATA,
@@ -54,7 +56,7 @@ from e2b.sandbox_sync.filesystem.watch_handle import WatchHandle
_FILESYSTEM_RPC_ERROR_MAP = {
- Code.not_found: FileNotFoundException,
+ Code.NOT_FOUND: FileNotFoundException,
}
_FILESYSTEM_HTTP_ERROR_MAP = {
@@ -87,6 +89,11 @@ class Filesystem:
self._envd_version = envd_version
self._connection_config = connection_config
self._thread_local = threading.local()
+ self._rpc = create_rpc_client(
+ filesystem_connect.FilesystemClientSync,
+ envd_api_url,
+ connection_config,
+ )
def _create_envd_api(self) -> httpx.Client:
transport = get_envd_transport(self._connection_config)
@@ -97,34 +104,16 @@ class Filesystem:
event_hooks=make_logging_event_hooks(self._connection_config.logger),
)
- def _create_rpc(self) -> filesystem_connect.FilesystemClient:
- transport = get_envd_transport(self._connection_config)
- return filesystem_connect.FilesystemClient(
- self._envd_api_url,
- # TODO: Fix and enable compression again — the headers compression is not solved for streaming.
- # compressor=e2b_connect.GzipCompressor,
- pool=transport.pool,
- json=True,
- headers=self._connection_config.sandbox_headers,
- logger=self._connection_config.logger,
- )
-
@property
def _envd_api(self) -> httpx.Client:
+ # Unlike the shared RPC client, the httpx transports are per-thread
+ # (see e2b.api.client_sync), so the client wrapping them is too.
envd_api = getattr(self._thread_local, "envd_api", None)
if envd_api is None:
envd_api = self._create_envd_api()
self._thread_local.envd_api = envd_api
return envd_api
- @property
- def _rpc(self) -> filesystem_connect.FilesystemClient:
- rpc = getattr(self._thread_local, "rpc", None)
- if rpc is None:
- rpc = self._create_rpc()
- self._thread_local.rpc = rpc
- return rpc
-
@overload
def read(
self,
@@ -478,9 +467,9 @@ class Filesystem:
try:
res = self._rpc.list_dir(
- filesystem_pb2.ListDirRequest(path=path, depth=depth),
- request_timeout=self._connection_config.get_request_timeout(
- request_timeout
+ filesystem_pb.ListDirRequest(path=path, depth=depth or 0),
+ timeout_ms=timeout_to_ms(
+ self._connection_config.get_request_timeout(request_timeout)
),
headers=authentication_header(self._envd_version, user),
)
@@ -512,17 +501,17 @@ class Filesystem:
"""
try:
self._rpc.stat(
- filesystem_pb2.StatRequest(path=path),
- request_timeout=self._connection_config.get_request_timeout(
- request_timeout
+ filesystem_pb.StatRequest(path=path),
+ timeout_ms=timeout_to_ms(
+ self._connection_config.get_request_timeout(request_timeout)
),
headers=authentication_header(self._envd_version, user),
)
return True
except Exception as e:
- if isinstance(e, e2b_connect.ConnectException):
- if e.status == e2b_connect.Code.not_found:
+ if isinstance(e, ConnectError):
+ if e.code == Code.NOT_FOUND:
return False
raise _handle_filesystem_rpc_exception(e, self._envd_api)
@@ -543,14 +532,14 @@ class Filesystem:
"""
try:
r = self._rpc.stat(
- filesystem_pb2.StatRequest(path=path),
- request_timeout=self._connection_config.get_request_timeout(
- request_timeout
+ filesystem_pb.StatRequest(path=path),
+ timeout_ms=timeout_to_ms(
+ self._connection_config.get_request_timeout(request_timeout)
),
headers=authentication_header(self._envd_version, user),
)
- return map_entry_info(r.entry)
+ return map_entry_info(r.entry or filesystem_pb.EntryInfo())
except Exception as e:
raise _handle_filesystem_rpc_exception(e, self._envd_api)
@@ -569,9 +558,9 @@ class Filesystem:
"""
try:
self._rpc.remove(
- filesystem_pb2.RemoveRequest(path=path),
- request_timeout=self._connection_config.get_request_timeout(
- request_timeout
+ filesystem_pb.RemoveRequest(path=path),
+ timeout_ms=timeout_to_ms(
+ self._connection_config.get_request_timeout(request_timeout)
),
headers=authentication_header(self._envd_version, user),
)
@@ -597,17 +586,17 @@ class Filesystem:
"""
try:
r = self._rpc.move(
- filesystem_pb2.MoveRequest(
+ filesystem_pb.MoveRequest(
source=old_path,
destination=new_path,
),
- request_timeout=self._connection_config.get_request_timeout(
- request_timeout
+ timeout_ms=timeout_to_ms(
+ self._connection_config.get_request_timeout(request_timeout)
),
headers=authentication_header(self._envd_version, user),
)
- return map_entry_info(r.entry)
+ return map_entry_info(r.entry or filesystem_pb.EntryInfo())
except Exception as e:
raise _handle_filesystem_rpc_exception(e, self._envd_api)
@@ -628,17 +617,17 @@ class Filesystem:
"""
try:
self._rpc.make_dir(
- filesystem_pb2.MakeDirRequest(path=path),
- request_timeout=self._connection_config.get_request_timeout(
- request_timeout
+ filesystem_pb.MakeDirRequest(path=path),
+ timeout_ms=timeout_to_ms(
+ self._connection_config.get_request_timeout(request_timeout)
),
headers=authentication_header(self._envd_version, user),
)
return True
except Exception as e:
- if isinstance(e, e2b_connect.ConnectException):
- if e.status == e2b_connect.Code.already_exists:
+ if isinstance(e, ConnectError):
+ if e.code == Code.ALREADY_EXISTS:
return False
raise _handle_filesystem_rpc_exception(e, self._envd_api)
@@ -683,14 +672,14 @@ class Filesystem:
try:
r = self._rpc.create_watcher(
- filesystem_pb2.CreateWatcherRequest(
+ filesystem_pb.CreateWatcherRequest(
path=path,
recursive=recursive,
include_entry=include_entry,
allow_network_mounts=allow_network_mounts,
),
- request_timeout=self._connection_config.get_request_timeout(
- request_timeout
+ timeout_ms=timeout_to_ms(
+ self._connection_config.get_request_timeout(request_timeout)
),
headers={
**authentication_header(self._envd_version, user),
@@ -701,7 +690,7 @@ class Filesystem:
raise _handle_filesystem_rpc_exception(e, self._envd_api)
return WatchHandle(
- lambda: self._rpc,
+ self._rpc,
r.watcher_id,
self._connection_config,
self._envd_version,
diff --git a/packages/python-sdk/e2b/sandbox_sync/filesystem/watch_handle.py b/packages/python-sdk/e2b/sandbox_sync/filesystem/watch_handle.py
index 7d14b25f0..69e0205e8 100644
--- a/packages/python-sdk/e2b/sandbox_sync/filesystem/watch_handle.py
+++ b/packages/python-sdk/e2b/sandbox_sync/filesystem/watch_handle.py
@@ -5,11 +5,12 @@ from packaging.version import Version
from e2b import SandboxException
from e2b.connection_config import ConnectionConfig, Username
from e2b.envd.filesystem import filesystem_connect
-from e2b.envd.filesystem.filesystem_pb2 import (
+from e2b.envd.filesystem.filesystem_pb import (
GetWatcherEventsRequest,
RemoveWatcherRequest,
)
-from e2b.envd.rpc import authentication_header, handle_rpc_exception_with_health
+from e2b.envd.rpc import handle_rpc_exception_with_health
+from e2b.envd.utils import authentication_header, timeout_to_ms
from e2b.sandbox.filesystem.filesystem import map_entry_info
from e2b.sandbox.filesystem.watch_handle import FilesystemEvent, map_event_type
@@ -24,14 +25,14 @@ class WatchHandle:
def __init__(
self,
- get_rpc: Callable[[], filesystem_connect.FilesystemClient],
+ rpc: filesystem_connect.FilesystemClientSync,
watcher_id: str,
connection_config: ConnectionConfig,
envd_version: Version,
user: Optional[Username] = None,
check_health: Optional[Callable[[], Optional[bool]]] = None,
):
- self._get_rpc = get_rpc
+ self._rpc = rpc
self._watcher_id = watcher_id
self._connection_config = connection_config
self._envd_version = envd_version
@@ -47,10 +48,10 @@ class WatchHandle:
:param request_timeout: Timeout for the request in **seconds**
"""
try:
- self._get_rpc().remove_watcher(
+ self._rpc.remove_watcher(
RemoveWatcherRequest(watcher_id=self._watcher_id),
- request_timeout=self._connection_config.get_request_timeout(
- request_timeout
+ timeout_ms=timeout_to_ms(
+ self._connection_config.get_request_timeout(request_timeout)
),
headers=authentication_header(self._envd_version, self._user),
)
@@ -73,10 +74,10 @@ class WatchHandle:
raise SandboxException("The watcher is already stopped")
try:
- r = self._get_rpc().get_watcher_events(
+ r = self._rpc.get_watcher_events(
GetWatcherEventsRequest(watcher_id=self._watcher_id),
- request_timeout=self._connection_config.get_request_timeout(
- request_timeout
+ timeout_ms=timeout_to_ms(
+ self._connection_config.get_request_timeout(request_timeout)
),
headers=authentication_header(self._envd_version, self._user),
)
@@ -93,7 +94,7 @@ class WatchHandle:
type=event_type,
entry=(
map_entry_info(event.entry)
- if event.HasField("entry")
+ if event.entry is not None
else None
),
)
diff --git a/packages/python-sdk/e2b/volume/client_async/__init__.py b/packages/python-sdk/e2b/volume/client_async/__init__.py
index db4fe8411..132bc43a7 100644
--- a/packages/python-sdk/e2b/volume/client_async/__init__.py
+++ b/packages/python-sdk/e2b/volume/client_async/__init__.py
@@ -14,9 +14,9 @@ from e2b.volume.client.client import AuthenticatedClient as AsyncVolumeApiClient
from e2b.volume.connection_config import VolumeConnectionConfig
limits = Limits(
- max_keepalive_connections=int(os.getenv("E2B_MAX_KEEPALIVE_CONNECTIONS", "20")),
- max_connections=int(os.getenv("E2B_MAX_CONNECTIONS", "2000")),
- keepalive_expiry=int(os.getenv("E2B_KEEPALIVE_EXPIRY", "300")),
+ max_keepalive_connections=int(os.getenv("E2B_MAX_KEEPALIVE_CONNECTIONS") or "20"),
+ max_connections=int(os.getenv("E2B_MAX_CONNECTIONS") or "2000"),
+ keepalive_expiry=int(os.getenv("E2B_KEEPALIVE_EXPIRY") or "300"),
)
TransportKey = Optional[ProxyTypes]
diff --git a/packages/python-sdk/e2b/volume/client_sync/__init__.py b/packages/python-sdk/e2b/volume/client_sync/__init__.py
index d5dff2839..c6a55cb37 100644
--- a/packages/python-sdk/e2b/volume/client_sync/__init__.py
+++ b/packages/python-sdk/e2b/volume/client_sync/__init__.py
@@ -13,9 +13,9 @@ from e2b.volume.client.client import AuthenticatedClient as VolumeApiClient
from e2b.volume.connection_config import VolumeConnectionConfig
limits = Limits(
- max_keepalive_connections=int(os.getenv("E2B_MAX_KEEPALIVE_CONNECTIONS", "20")),
- max_connections=int(os.getenv("E2B_MAX_CONNECTIONS", "2000")),
- keepalive_expiry=int(os.getenv("E2B_KEEPALIVE_EXPIRY", "300")),
+ max_keepalive_connections=int(os.getenv("E2B_MAX_KEEPALIVE_CONNECTIONS") or "20"),
+ max_connections=int(os.getenv("E2B_MAX_CONNECTIONS") or "2000"),
+ keepalive_expiry=int(os.getenv("E2B_KEEPALIVE_EXPIRY") or "300"),
)
TransportKey = Optional[ProxyTypes]
diff --git a/packages/python-sdk/e2b_connect/__init__.py b/packages/python-sdk/e2b_connect/__init__.py
deleted file mode 100644
index 6f31c8cee..000000000
--- a/packages/python-sdk/e2b_connect/__init__.py
+++ /dev/null
@@ -1 +0,0 @@
-from .client import Client, GzipCompressor, ConnectException, Code # noqa: F401
diff --git a/packages/python-sdk/e2b_connect/client.py b/packages/python-sdk/e2b_connect/client.py
deleted file mode 100644
index 83d006bcb..000000000
--- a/packages/python-sdk/e2b_connect/client.py
+++ /dev/null
@@ -1,534 +0,0 @@
-import gzip
-import inspect
-import json
-import logging
-import struct
-import typing
-
-from httpcore import (
- ConnectionPool,
- AsyncConnectionPool,
- RemoteProtocolError,
- Response,
-)
-from enum import Flag, Enum
-from typing import Callable, Optional, Dict, Any, Generator, Tuple
-from google.protobuf import json_format
-
-
-class EnvelopeFlags(Flag):
- compressed = 0b00000001
- end_stream = 0b00000010
-
-
-class Code(Enum):
- canceled = "canceled"
- unknown = "unknown"
- invalid_argument = "invalid_argument"
- deadline_exceeded = "deadline_exceeded"
- not_found = "not_found"
- already_exists = "already_exists"
- permission_denied = "permission_denied"
- resource_exhausted = "resource_exhausted"
- failed_precondition = "failed_precondition"
- aborted = "aborted"
- out_of_range = "out_of_range"
- unimplemented = "unimplemented"
- internal = "internal"
- unavailable = "unavailable"
- data_loss = "data_loss"
- unauthenticated = "unauthenticated"
-
-
-def make_error_from_http_code(http_code: int):
- error_code_map = {
- 400: Code.invalid_argument,
- 401: Code.unauthenticated,
- 403: Code.permission_denied,
- 404: Code.not_found,
- 409: Code.already_exists,
- 413: Code.resource_exhausted,
- 429: Code.resource_exhausted,
- 499: Code.canceled,
- 500: Code.internal,
- 501: Code.unimplemented,
- 502: Code.unavailable,
- 503: Code.unavailable,
- 504: Code.deadline_exceeded,
- 505: Code.unimplemented,
- }
-
- return error_code_map.get(http_code, Code.unknown)
-
-
-class ConnectException(Exception):
- def __init__(self, status: Code, message: str):
- self.status = status
- self.message = message
-
-
-envelope_header_length = 5
-envelope_header_pack = ">BI"
-
-
-def encode_envelope(*, flags: EnvelopeFlags, data):
- return encode_envelope_header(flags=flags.value, data=data) + data
-
-
-def encode_envelope_header(*, flags, data):
- return struct.pack(envelope_header_pack, flags, len(data))
-
-
-def decode_envelope_header(header):
- flags, data_len = struct.unpack(envelope_header_pack, header)
- return EnvelopeFlags(flags), data_len
-
-
-def error_for_response(http_resp: Response):
- try:
- error = json.loads(http_resp.content)
- return make_error(error)
- except (json.decoder.JSONDecodeError, KeyError):
- error = {"code": http_resp.status, "message": http_resp.content.decode("utf-8")}
- return make_error(error)
-
-
-def make_error(error):
- status = None
- try:
- code_value = error.get("code")
- # return error code from http status code
- if isinstance(code_value, int):
- status = make_error_from_http_code(code_value)
- else:
- status = Code(code_value)
- except (KeyError, ValueError):
- status = Code.unknown
-
- return ConnectException(status, error.get("message", ""))
-
-
-def _sync_retry(func, exc, retries):
- def retry(*args, **kwargs):
- for _ in range(retries):
- try:
- return func(*args, **kwargs)
- except exc:
- continue
-
- return func(*args, **kwargs)
-
- return retry
-
-
-def _async_retry(func, exc, retries):
- async def retry(*args, **kwargs):
- for _ in range(retries):
- try:
- return await func(*args, **kwargs)
- except exc:
- continue
-
- return await func(*args, **kwargs)
-
- return retry
-
-
-def _retry(exc: typing.Type[Exception], retries: int):
- def decorator(func):
- if inspect.iscoroutinefunction(func):
- return _async_retry(func, exc, retries)
-
- return _sync_retry(func, exc, retries)
-
- return decorator
-
-
-class GzipCompressor:
- name = "gzip"
- decompress = gzip.decompress
- compress = gzip.compress
-
-
-class JSONCodec:
- content_type = "json"
-
- @staticmethod
- def encode(msg):
- return json_format.MessageToJson(msg).encode("utf8")
-
- @staticmethod
- def decode(data, *, msg_type):
- msg = msg_type()
- json_format.Parse(data.decode("utf8"), msg, ignore_unknown_fields=True)
- return msg
-
-
-class ProtobufCodec:
- content_type = "proto"
-
- @staticmethod
- def encode(msg):
- return msg.SerializeToString()
-
- @staticmethod
- def decode(data, *, msg_type):
- msg = msg_type()
- msg.ParseFromString(data)
- return msg
-
-
-class Client:
- def __init__(
- self,
- *,
- pool: Optional[ConnectionPool] = None,
- async_pool: Optional[AsyncConnectionPool] = None,
- url: str,
- response_type,
- compressor=None,
- json: Optional[bool] = False,
- headers: Optional[Dict[str, str]] = None,
- logger: Optional[logging.Logger] = None,
- ):
- if headers is None:
- headers = {}
-
- self.pool = pool
- self.async_pool = async_pool
- self.url = url
- self._codec = JSONCodec if json else ProtobufCodec
- self._response_type = response_type
- self._compressor = compressor
- self._headers = headers
- self._connection_retries = 3
- self._logger = logger
-
- def _log_request(self) -> None:
- if self._logger is not None:
- self._logger.info(f"Request: POST {self.url}")
-
- def _log_response(self, status: int) -> None:
- if self._logger is None:
- return
- if status >= 400:
- self._logger.error(f"Response: {status} {self.url}")
- else:
- self._logger.info(f"Response: {status} {self.url}")
-
- def _log_stream_message(self) -> None:
- if self._logger is not None:
- self._logger.debug(f"Response stream: {self.url}")
-
- def _prepare_unary_request(
- self,
- req,
- request_timeout=None,
- headers: Optional[dict] = None,
- **opts,
- ) -> dict:
- data = self._codec.encode(req)
-
- if self._compressor is not None:
- data = self._compressor.compress(data)
-
- if headers is None:
- headers = {}
-
- extensions = (
- None
- if request_timeout is None
- else {
- "timeout": {
- "connect": request_timeout,
- "pool": request_timeout,
- "read": request_timeout,
- "write": request_timeout,
- }
- }
- )
-
- return {
- "method": "POST",
- "url": self.url,
- "content": data,
- "extensions": extensions,
- "headers": {
- **self._headers,
- **headers,
- **opts.get("headers", {}),
- "connect-protocol-version": "1",
- "content-encoding": (
- "identity" if self._compressor is None else self._compressor.name
- ),
- "content-type": f"application/{self._codec.content_type}",
- },
- }
-
- def _process_unary_response(
- self,
- http_resp: Response,
- ):
- self._log_response(http_resp.status)
-
- if http_resp.status != 200:
- raise error_for_response(http_resp)
-
- content = http_resp.content
-
- if self._compressor is not None:
- content = self._compressor.decompress(content)
-
- return self._codec.decode(
- content,
- msg_type=self._response_type,
- )
-
- @_retry(RemoteProtocolError, 3)
- async def acall_unary(
- self,
- req,
- request_timeout=None,
- headers: Optional[dict] = None,
- **opts,
- ):
- if self.async_pool is None:
- raise ValueError("async_pool is required")
-
- req_data = self._prepare_unary_request(
- req,
- request_timeout,
- headers,
- **opts,
- )
-
- self._log_request()
- res = await self.async_pool.request(**req_data)
- return self._process_unary_response(res)
-
- @_retry(RemoteProtocolError, 3)
- def call_unary(
- self,
- req,
- request_timeout=None,
- headers: Optional[dict] = None,
- **opts,
- ):
- if self.pool is None:
- raise ValueError("pool is required")
-
- req_data = self._prepare_unary_request(
- req,
- request_timeout,
- headers,
- **opts,
- )
-
- self._log_request()
- res = self.pool.request(**req_data)
- return self._process_unary_response(res)
-
- def _create_stream_timeout(self, timeout: Optional[float]):
- if timeout:
- return {"connect-timeout-ms": str(int(timeout * 1000))}
- return {}
-
- def _prepare_server_stream_request(
- self,
- req,
- request_timeout=None,
- timeout=None,
- headers: Optional[dict] = None,
- **opts,
- ) -> dict:
- headers = headers or {}
- data = self._codec.encode(req)
- flags = EnvelopeFlags(0)
-
- # `request_timeout` bounds connection setup and request sending, but NOT the
- # stream read: a stream can stay open for the whole command `timeout` (minutes
- # or, when disabled, indefinitely), so we deliberately leave `read` unset.
- # The command `timeout` is enforced server-side via the `connect-timeout-ms`
- # header (see `_create_stream_timeout`), which returns a clean `deadline_exceeded`.
- # This mirrors the JS SDK, which has no per-chunk read timeout either — setting
- # `read` to the command `timeout` would race that server response and surface a
- # raw transport `ReadTimeout` instead.
- timeout_ext = {}
- if request_timeout is not None:
- timeout_ext["connect"] = request_timeout
- timeout_ext["pool"] = request_timeout
- timeout_ext["write"] = request_timeout
- extensions = {"timeout": timeout_ext} if timeout_ext else None
-
- if self._compressor is not None:
- data = self._compressor.compress(data)
- flags |= EnvelopeFlags.compressed
-
- stream_timeout = self._create_stream_timeout(timeout)
-
- return {
- "method": "POST",
- "url": self.url,
- "content": encode_envelope(
- flags=flags,
- data=data,
- ),
- "extensions": extensions,
- "headers": {
- **self._headers,
- **headers,
- **opts.get("headers", {}),
- **stream_timeout,
- "connect-protocol-version": "1",
- "connect-content-encoding": (
- "identity" if self._compressor is None else self._compressor.name
- ),
- "content-type": f"application/connect+{self._codec.content_type}",
- },
- }
-
- # Note: no retry here — generator functions don't execute until iterated, so a
- # call-level retry never fires, and retrying mid-stream would replay delivered events.
- async def acall_server_stream(
- self,
- req,
- request_timeout=None,
- timeout=None,
- headers: Optional[dict] = None,
- **opts,
- ):
- if self.async_pool is None:
- raise ValueError("async_pool is required")
-
- req_data = self._prepare_server_stream_request(
- req,
- request_timeout,
- timeout,
- headers,
- **opts,
- )
-
- parser = ServerStreamParser(
- decode=self._codec.decode,
- response_type=self._response_type,
- )
-
- self._log_request()
- async with self.async_pool.stream(**req_data) as http_resp:
- if http_resp.status != 200:
- self._log_response(http_resp.status)
- await http_resp.aread()
- raise error_for_response(http_resp)
-
- async for chunk in http_resp.aiter_stream():
- for parsed in parser.parse(chunk):
- self._log_stream_message()
- yield parsed
-
- def call_server_stream(
- self,
- req,
- request_timeout=None,
- timeout=None,
- headers: Optional[dict] = None,
- **opts,
- ):
- if self.pool is None:
- raise ValueError("pool is required")
-
- req_data = self._prepare_server_stream_request(
- req,
- request_timeout,
- timeout,
- headers,
- **opts,
- )
-
- parser = ServerStreamParser(
- decode=self._codec.decode,
- response_type=self._response_type,
- )
-
- self._log_request()
- with self.pool.stream(**req_data) as http_resp:
- if http_resp.status != 200:
- self._log_response(http_resp.status)
- http_resp.read()
- raise error_for_response(http_resp)
-
- for chunk in http_resp.iter_stream():
- for parsed in parser.parse(chunk):
- self._log_stream_message()
- yield parsed
-
- def call_client_stream(self, req, **opts):
- raise NotImplementedError("client stream not supported")
-
- def acall_client_stream(self, req, **opts):
- raise NotImplementedError("client stream not supported")
-
- def call_bidi_stream(self, req, **opts):
- raise NotImplementedError("bidi stream not supported")
-
- def acall_bidi_stream(self, req, **opts):
- raise NotImplementedError("bidi stream not supported")
-
-
-DataLen = int
-
-
-class ServerStreamParser:
- def __init__(
- self,
- decode: Callable,
- response_type: Any,
- ):
- self.decode = decode
- self.response_type = response_type
-
- self.buffer: bytes = b""
- self._header: Optional[tuple[EnvelopeFlags, DataLen]] = None
-
- def shift_buffer(self, size: int):
- buffer = self.buffer[:size]
- self.buffer = self.buffer[size:]
- return buffer
-
- @property
- def header(self) -> Tuple[EnvelopeFlags, DataLen]:
- if self._header:
- return self._header
-
- header_data = self.shift_buffer(envelope_header_length)
- self._header = decode_envelope_header(header_data)
-
- return self._header
-
- @header.deleter
- def header(self):
- self._header = None
-
- def parse(self, chunk: bytes) -> Generator[Any, None, None]:
- self.buffer += chunk
-
- # Once the header is consumed, the remaining payload can be shorter
- # than the header length, so only require a full header when we still
- # need to read one.
- while self._header is not None or len(self.buffer) >= envelope_header_length:
- flags, data_len = self.header
-
- if data_len > len(self.buffer):
- break
-
- data = self.shift_buffer(data_len)
-
- if EnvelopeFlags.end_stream in flags:
- data = json.loads(data)
-
- if "error" in data:
- raise make_error(data["error"])
-
- return
-
- yield self.decode(data, msg_type=self.response_type)
- del self.header
diff --git a/packages/python-sdk/e2b_connect/py.typed b/packages/python-sdk/e2b_connect/py.typed
deleted file mode 100644
index e69de29bb..000000000
diff --git a/packages/python-sdk/pyproject.toml b/packages/python-sdk/pyproject.toml
index 538409d52..6b15c608a 100644
--- a/packages/python-sdk/pyproject.toml
+++ b/packages/python-sdk/pyproject.toml
@@ -9,8 +9,7 @@ requires-python = ">=3.10"
dependencies = [
"python-dateutil>=2.8.2",
"wcmatch>=10.1,<11",
- "protobuf>=4.21.0",
- "httpcore>=1.0.5,<2",
+ "protobuf-py>=0.1.1,<0.2",
"httpx>=0.27.0,<1.0.0",
"h2>=4,<5",
"attrs>=23.2.0",
@@ -18,6 +17,8 @@ dependencies = [
"typing-extensions>=4.1.0",
"dockerfile-parse>=2.0.1,<3",
"rich>=14.0.0",
+ "connectrpc>=0.11.1,<0.12",
+ "pyqwest>=0.7.0,<0.8",
]
[project.urls]
@@ -39,12 +40,14 @@ dev = [
# Tools for local code generation (`make init` && `uv run make generate-*`).
# Pins mirror codegen.Dockerfile so local output matches CI. `generate-envd`
-# additionally needs Go tooling (buf) and only runs via `make codegen` (Docker).
+# additionally needs `buf` on the PATH.
codegen = [
"black==26.3.1",
"pyyaml==6.0.2",
"e2b-openapi-python-client==0.26.2",
"datamodel-code-generator==0.34.0",
+ "protoc-gen-connectrpc==0.11.1",
+ "protoc-gen-py==0.1.1",
]
[build-system]
@@ -52,7 +55,7 @@ requires = ["uv_build>=0.10.0,<0.11.0"]
build-backend = "uv_build"
[tool.uv.build-backend]
-module-name = ["e2b", "e2b_connect"]
+module-name = ["e2b"]
module-root = ""
[tool.basedpyright]
@@ -66,15 +69,6 @@ no-matching-overload = "ignore"
include = ["e2b/api/client/models/**"]
rules = { invalid-argument-type = "ignore" }
-[[tool.ty.overrides]]
-include = ["e2b/envd/**/*.pyi"]
-rules = { conflicting-metaclass = "ignore", unresolved-attribute = "ignore" }
-
[[tool.ty.overrides]]
include = ["e2b/volume/**"]
rules = { unresolved-attribute = "ignore" }
-
-[tool.ruff]
-exclude = [
- "e2b/envd/filesystem/filesystem_pb2.py"
-]
diff --git a/packages/python-sdk/pytest.ini b/packages/python-sdk/pytest.ini
index 00dc77b05..bb043ba0a 100644
--- a/packages/python-sdk/pytest.ini
+++ b/packages/python-sdk/pytest.ini
@@ -7,6 +7,8 @@ asyncio_mode=auto
asyncio_default_fixture_loop_scope=session
asyncio_default_test_loop_scope=session
addopts = "--import-mode=importlib"
+# Makes shared test helpers (e.g. envd_frame_server) importable under importlib mode.
+pythonpath = tests
timeout = 30
filterwarnings =
ignore:'asyncio\.iscoroutinefunction' is deprecated.*:DeprecationWarning:pytest_asyncio\.plugin
diff --git a/packages/python-sdk/scripts/fix-python-pb.sh b/packages/python-sdk/scripts/fix-python-pb.sh
index 7bdea385a..ed2dc1828 100755
--- a/packages/python-sdk/scripts/fix-python-pb.sh
+++ b/packages/python-sdk/scripts/fix-python-pb.sh
@@ -3,9 +3,3 @@
rm -rf e2b/envd/__pycache__
rm -rf e2b/envd/filesystem/__pycache__
rm -rf e2b/envd/process/__pycache__
-
-sed -i.bak 's/from\ process\ import/from e2b.envd.process import/g' e2b/envd/process/* e2b/envd/filesystem/*
-sed -i.bak 's/from\ filesystem\ import/from e2b.envd.filesystem import/g' e2b/envd/process/* e2b/envd/filesystem/*
-
-rm -f e2b/envd/process/*.bak
-rm -f e2b/envd/filesystem/*.bak
diff --git a/packages/python-sdk/tests/e2b_connect/__init__.py b/packages/python-sdk/tests/e2b_connect/__init__.py
deleted file mode 100644
index e69de29bb..000000000
diff --git a/packages/python-sdk/tests/e2b_connect/test_client.py b/packages/python-sdk/tests/e2b_connect/test_client.py
deleted file mode 100644
index 58004a318..000000000
--- a/packages/python-sdk/tests/e2b_connect/test_client.py
+++ /dev/null
@@ -1,171 +0,0 @@
-import asyncio
-
-import pytest
-
-from e2b_connect.client import (
- EnvelopeFlags,
- ServerStreamParser,
- _retry,
- encode_envelope,
-)
-
-
-class GoodError(Exception):
- pass
-
-
-class BadError(Exception):
- pass
-
-
-def test_sync_retry_after_expected_exception():
- total = 0
-
- @_retry(GoodError, 1)
- def f():
- nonlocal total
- total += 1
- raise GoodError()
-
- with pytest.raises(GoodError):
- f()
-
- assert total == 2
-
-
-def test_sync_do_not_retry_on_unexpected_exception():
- total = 0
-
- @_retry(GoodError, 1)
- def f():
- nonlocal total
- total += 1
- raise BadError()
-
- with pytest.raises(BadError):
- f()
-
- assert total == 1
-
-
-def test_sync_do_not_throw_when_retry_works():
- total = 0
-
- @_retry(GoodError, 1)
- def f():
- nonlocal total
- total += 1
-
- if total < 2:
- raise GoodError()
-
- return True
-
- result = f()
- assert result is True
- assert total == 2
-
-
-async def test_async_retry_after_expected_exception():
- total = 0
-
- @_retry(GoodError, 1)
- async def f():
- nonlocal total
- total += 1
- raise GoodError()
-
- with pytest.raises(GoodError):
- await f()
-
- assert total == 2
-
-
-async def test_async_do_not_retry_on_unexpected_exception():
- total = 0
-
- @_retry(GoodError, 1)
- async def f():
- nonlocal total
- total += 1
- raise BadError()
-
- with pytest.raises(BadError):
- await f()
-
- assert total == 1
-
-
-async def test_async_do_not_throw_when_retry_works():
- total = 0
-
- @_retry(GoodError, 1)
- async def f():
- nonlocal total
- total += 1
-
- if total < 2:
- raise GoodError()
-
- return True
-
- result = await f()
- assert result is True
- assert total == 2
-
-
-async def test_async_with_multiple_await_calls():
- total = 0
-
- async def a():
- await asyncio.sleep(0.001)
-
- @_retry(GoodError, 1)
- async def f():
- nonlocal total
- total += 1
-
- await a()
-
- if total < 2:
- raise GoodError()
-
- await a()
-
- return True
-
- result = await f()
- assert result is True
- assert total == 2
-
-
-def make_parser():
- return ServerStreamParser(
- decode=lambda data, msg_type: data,
- response_type=None,
- )
-
-
-def test_parser_yields_messages_from_single_chunk():
- parser = make_parser()
- envelope = encode_envelope(flags=EnvelopeFlags(0), data=b"abc")
-
- assert list(parser.parse(envelope)) == [b"abc"]
-
-
-def test_parser_handles_payload_split_after_header():
- parser = make_parser()
- envelope = encode_envelope(flags=EnvelopeFlags(0), data=b"abc")
-
- # The header plus one payload byte arrive first; the remaining payload
- # (shorter than a header) arrives in a later chunk.
- assert list(parser.parse(envelope[:6])) == []
- assert list(parser.parse(envelope[6:])) == [b"abc"]
-
-
-def test_parser_handles_end_stream_payload_shorter_than_header():
- parser = make_parser()
- envelope = encode_envelope(flags=EnvelopeFlags.end_stream, data=b"{}")
-
- assert list(parser.parse(envelope[:5])) == []
- assert list(parser.parse(envelope[5:])) == []
diff --git a/packages/python-sdk/tests/envd_frame_server.py b/packages/python-sdk/tests/envd_frame_server.py
new file mode 100644
index 000000000..df7f33447
--- /dev/null
+++ b/packages/python-sdk/tests/envd_frame_server.py
@@ -0,0 +1,232 @@
+"""Frame-level HTTP/2 test harness for the envd RPC stack.
+
+A real plaintext HTTP/2 server that records the frames the client sends
+(notably ``RST_STREAM``), serving a Connect server stream the way envd's
+process ``connect`` does, plus client factories mirroring the
+``e2b.envd.client_sync``/``client_async`` wiring over a plaintext
+transport. Tests drive it with the actual generated stubs wired with the
+SDK's codec and interceptors. Not a test module itself — imported by the
+``test_envd_*`` transport and stream test modules (``pythonpath = tests``
+in pytest.ini makes it importable under ``--import-mode=importlib``).
+"""
+
+import contextlib
+import logging
+import socket
+import struct
+import threading
+import time
+from typing import Iterator, Optional
+
+import h2.config
+import h2.connection
+import h2.events
+from protobuf import Oneof
+from pyqwest import (
+ Client,
+ HTTPTransport,
+ HTTPVersion,
+ SyncClient,
+ SyncHTTPTransport,
+ SyncTransport,
+ Transport,
+)
+
+from e2b.connection_config import ConnectionConfig
+from e2b.envd.client_shared import ENVD_JSON_CODEC, ENVD_RPC_COMPRESSION
+from e2b.envd.interceptors import build_interceptors
+from e2b.envd.process.process_connect import ProcessClient, ProcessClientSync
+from e2b.envd.process.process_pb import ConnectResponse, ProcessEvent
+
+H2_CANCEL = 0x8
+CONNECT_END_STREAM_FLAG = 0x02
+
+
+def envelope(flags: int, data: bytes) -> bytes:
+ return struct.pack(">BI", flags, len(data)) + data
+
+
+def event_envelope() -> bytes:
+ msg = ConnectResponse(
+ event=ProcessEvent(
+ event=Oneof("data", ProcessEvent.DataEvent(output=Oneof("stdout", b"hi")))
+ )
+ )
+ return envelope(0, ENVD_JSON_CODEC.encode(msg))
+
+
+class FrameRecordingServer(threading.Thread):
+ """One-connection plaintext HTTP/2 server that records RST_STREAM frames.
+
+ Replies to the first request with a single Connect message envelope and,
+ when ``server_ends_stream`` is set, a Connect end-of-stream envelope with
+ the HTTP/2 END_STREAM flag; otherwise it leaves the stream open the way a
+ still-running process does. With ``respond=False`` it accepts the request
+ but never answers, the way an unresponsive envd does. With
+ ``plain_error=(status, content_type, body)`` it answers every request
+ with that plain HTTP response, the way a gateway answering for envd does.
+ """
+
+ def __init__(
+ self,
+ server_ends_stream: bool,
+ respond: bool = True,
+ plain_error: Optional[tuple[int, str, bytes]] = None,
+ ):
+ super().__init__(daemon=True)
+ self.server_ends_stream = server_ends_stream
+ self.respond = respond
+ self.plain_error = plain_error
+ self.listener = socket.create_server(("127.0.0.1", 0))
+ self.listener.settimeout(10)
+ self.port = self.listener.getsockname()[1]
+ self.resets: list[tuple[int, int]] = []
+ self.reset_event = threading.Event()
+ self.errors: list[str] = []
+
+ def run(self):
+ try:
+ sock, _ = self.listener.accept()
+ except socket.timeout:
+ self.errors.append("client never connected")
+ return
+ sock.settimeout(0.1)
+ conn = h2.connection.H2Connection(
+ config=h2.config.H2Configuration(client_side=False)
+ )
+ conn.initiate_connection()
+ sock.sendall(conn.data_to_send())
+ deadline = time.monotonic() + 10
+ try:
+ while time.monotonic() < deadline:
+ try:
+ data = sock.recv(65535)
+ except socket.timeout:
+ continue
+ except OSError:
+ break
+ if not data:
+ break
+ for event in conn.receive_data(data):
+ if isinstance(event, h2.events.StreamEnded) and self.plain_error:
+ status, content_type, body = self.plain_error
+ conn.send_headers(
+ event.stream_id,
+ [
+ (":status", str(status)),
+ ("content-type", content_type),
+ ],
+ )
+ conn.send_data(event.stream_id, body, end_stream=True)
+ elif isinstance(event, h2.events.StreamEnded) and self.respond:
+ # The client finished sending the request: respond.
+ conn.send_headers(
+ event.stream_id,
+ [
+ (":status", "200"),
+ ("content-type", "application/connect+json"),
+ ],
+ )
+ conn.send_data(event.stream_id, event_envelope())
+ if self.server_ends_stream:
+ conn.send_data(
+ event.stream_id,
+ envelope(CONNECT_END_STREAM_FLAG, b"{}"),
+ end_stream=True,
+ )
+ elif isinstance(event, h2.events.DataReceived):
+ conn.acknowledge_received_data(
+ event.flow_controlled_length, event.stream_id
+ )
+ elif isinstance(event, h2.events.StreamReset):
+ self.resets.append((event.stream_id, int(event.error_code)))
+ self.reset_event.set()
+ elif isinstance(event, h2.events.ConnectionTerminated):
+ return
+ out = conn.data_to_send()
+ if out:
+ sock.sendall(out)
+ except Exception as e: # noqa: BLE001 — surfaced via assert_no_errors
+ self.errors.append(repr(e))
+ finally:
+ sock.close()
+
+ def assert_reset_sent(self):
+ assert not self.errors, self.errors
+ assert self.reset_event.wait(3), "no RST_STREAM within 3s"
+ assert self.resets == [(1, H2_CANCEL)]
+
+ def assert_no_reset_sent(self):
+ # Grace period: a spurious reset would arrive within this window.
+ self.reset_event.wait(0.5)
+ assert not self.errors, self.errors
+ assert self.resets == []
+
+
+def frame_recording_server(
+ server_ends_stream: bool,
+ respond: bool = True,
+ plain_error: Optional[tuple[int, str, bytes]] = None,
+) -> Iterator[FrameRecordingServer]:
+ server = FrameRecordingServer(server_ends_stream, respond, plain_error)
+ server.start()
+ try:
+ yield server
+ finally:
+ server.listener.close()
+
+
+def assert_stdout_event(event: ConnectResponse):
+ assert event.event is not None
+ match event.event.event:
+ case Oneof(field="data", value=data):
+ assert data.output == Oneof("stdout", b"hi")
+ case other:
+ raise AssertionError(f"expected a data event, got {other}")
+
+
+def make_config(logger: Optional[logging.Logger] = None) -> ConnectionConfig:
+ """A ``ConnectionConfig`` with a syntactically valid dummy API key."""
+ return ConnectionConfig(api_key="e2b_" + "0" * 40, logger=logger)
+
+
+# The factories in e2b.envd.client_sync/client_async use the shared TLS
+# transports, which negotiate HTTP/2 via ALPN. The test server is plaintext,
+# so these mirror the factories with an HTTP/2-prior-knowledge transport —
+# pass `transport` to interpose a custom stack (retry middleware, plain-error
+# normalization, ...). Return types stay unannotated on purpose: the stubs
+# type server streams as Iterator/AsyncIterator, but the tests pin the
+# close()/aclose() behavior of the real generators connectrpc returns.
+
+
+def make_sync_client(
+ port: int,
+ transport: Optional[SyncTransport] = None,
+ logger: Optional[logging.Logger] = None,
+):
+ base_url = f"http://127.0.0.1:{port}"
+ return ProcessClientSync(
+ base_url,
+ codec=ENVD_JSON_CODEC,
+ **ENVD_RPC_COMPRESSION,
+ interceptors=build_interceptors(make_config(logger), base_url),
+ http_client=SyncClient(
+ transport or SyncHTTPTransport(http_version=HTTPVersion.HTTP2)
+ ),
+ )
+
+
+def make_async_client(
+ port: int,
+ transport: Optional[Transport] = None,
+ logger: Optional[logging.Logger] = None,
+):
+ base_url = f"http://127.0.0.1:{port}"
+ return ProcessClient(
+ base_url,
+ codec=ENVD_JSON_CODEC,
+ **ENVD_RPC_COMPRESSION,
+ interceptors=build_interceptors(make_config(logger), base_url),
+ http_client=Client(transport or HTTPTransport(http_version=HTTPVersion.HTTP2)),
+ )
diff --git a/packages/python-sdk/tests/sync/sandbox_sync/test_sync_client_lifecycle.py b/packages/python-sdk/tests/sync/sandbox_sync/test_sync_client_lifecycle.py
new file mode 100644
index 000000000..f8b0ddba0
--- /dev/null
+++ b/packages/python-sdk/tests/sync/sandbox_sync/test_sync_client_lifecycle.py
@@ -0,0 +1,99 @@
+"""Client lifecycle in the sync sandbox modules: the httpx `envd_api` clients
+wrap per-thread transports (see `e2b.api.client_sync`) and are bound per
+calling thread, while the connectrpc RPC clients are stateless over a
+process-global transport and are built once per module and shared across
+threads."""
+
+from concurrent.futures import ThreadPoolExecutor
+import threading
+from types import SimpleNamespace
+from unittest.mock import Mock, sentinel
+
+import httpx
+from packaging.version import Version
+
+from e2b.connection_config import ConnectionConfig
+from e2b.sandbox_sync.filesystem import filesystem as filesystem_sync
+from e2b.sandbox_sync.filesystem.filesystem import Filesystem
+import e2b.sandbox_sync.main as sandbox_sync_main
+
+
+ENVD_API_URL = "https://sandbox.e2b.app"
+ENVD_VERSION = Version("0.6.2")
+
+
+def run_in_worker_thread(fn):
+ with ThreadPoolExecutor(max_workers=1) as executor:
+ return executor.submit(fn).result()
+
+
+def test_sync_sandbox_envd_api_is_bound_per_calling_thread(monkeypatch, test_api_key):
+ config = ConnectionConfig(api_key=test_api_key)
+ main_api = Mock(spec=httpx.Client)
+ filesystem = SimpleNamespace(_envd_api=main_api)
+
+ monkeypatch.setattr(
+ sandbox_sync_main, "Filesystem", lambda *args, **kwargs: filesystem
+ )
+ monkeypatch.setattr(sandbox_sync_main, "Commands", lambda *args, **kwargs: object())
+ monkeypatch.setattr(sandbox_sync_main, "Pty", lambda *args, **kwargs: object())
+ monkeypatch.setattr(sandbox_sync_main, "Git", lambda *args, **kwargs: object())
+
+ sandbox = sandbox_sync_main.Sandbox(
+ sandbox_id="sbx-test",
+ sandbox_domain="e2b.app",
+ envd_version=ENVD_VERSION,
+ envd_access_token="tok",
+ traffic_access_token="tok",
+ connection_config=config,
+ )
+
+ assert sandbox._envd_api is main_api
+ assert sandbox._envd_api is sandbox.files._envd_api
+ assert not hasattr(sandbox, "_transport")
+
+
+def test_sync_filesystem_envd_api_per_thread_rpc_shared(monkeypatch, test_api_key):
+ config = ConnectionConfig(api_key=test_api_key)
+ main_thread_id = threading.get_ident()
+ main_transport = object()
+ worker_transport = object()
+ main_api = Mock(spec=httpx.Client)
+ worker_api = Mock(spec=httpx.Client)
+ shared_rpc = sentinel.filesystem_rpc
+
+ monkeypatch.setattr(
+ filesystem_sync,
+ "get_envd_transport",
+ lambda *_args, **_kwargs: main_transport
+ if threading.get_ident() == main_thread_id
+ else worker_transport,
+ )
+ monkeypatch.setattr(
+ filesystem_sync.httpx,
+ "Client",
+ lambda *args, **kwargs: main_api
+ if kwargs["transport"] is main_transport
+ else worker_api,
+ )
+ monkeypatch.setattr(
+ filesystem_sync,
+ "create_rpc_client",
+ lambda *_args, **_kwargs: shared_rpc,
+ )
+
+ fs = Filesystem(
+ ENVD_API_URL,
+ ENVD_VERSION,
+ config,
+ )
+
+ assert fs._envd_api is main_api
+ assert fs._rpc is shared_rpc
+
+ worker_api_result, worker_rpc_result = run_in_worker_thread(
+ lambda: (fs._envd_api, fs._rpc)
+ )
+ assert worker_api_result is worker_api
+ assert worker_rpc_result is shared_rpc
+ assert fs._envd_api is main_api
diff --git a/packages/python-sdk/tests/sync/sandbox_sync/test_thread_local_clients.py b/packages/python-sdk/tests/sync/sandbox_sync/test_thread_local_clients.py
deleted file mode 100644
index d447087cd..000000000
--- a/packages/python-sdk/tests/sync/sandbox_sync/test_thread_local_clients.py
+++ /dev/null
@@ -1,300 +0,0 @@
-from collections import Counter
-from concurrent.futures import ThreadPoolExecutor
-import threading
-from types import SimpleNamespace
-from unittest.mock import Mock, sentinel
-
-import httpx
-from packaging.version import Version
-
-from e2b.connection_config import ConnectionConfig
-from e2b.sandbox_sync.commands.command import Commands
-from e2b.sandbox_sync.commands.pty import Pty
-from e2b.sandbox_sync.filesystem import filesystem as filesystem_sync
-from e2b.sandbox_sync.filesystem.filesystem import Filesystem
-from e2b.sandbox_sync.filesystem.watch_handle import WatchHandle
-import e2b.sandbox_sync.commands.command as command_sync
-import e2b.sandbox_sync.commands.pty as pty_sync
-import e2b.sandbox_sync.main as sandbox_sync_main
-
-
-ENVD_API_URL = "https://sandbox.e2b.app"
-ENVD_VERSION = Version("0.6.2")
-
-
-def run_in_worker_thread(fn):
- with ThreadPoolExecutor(max_workers=1) as executor:
- return executor.submit(fn).result()
-
-
-def fake_transport():
- return SimpleNamespace(pool=object())
-
-
-def test_sync_sandbox_envd_api_is_bound_per_calling_thread(monkeypatch, test_api_key):
- config = ConnectionConfig(api_key=test_api_key)
- main_api = Mock(spec=httpx.Client)
- filesystem = SimpleNamespace(_envd_api=main_api)
-
- monkeypatch.setattr(
- sandbox_sync_main, "Filesystem", lambda *args, **kwargs: filesystem
- )
- monkeypatch.setattr(sandbox_sync_main, "Commands", lambda *args, **kwargs: object())
- monkeypatch.setattr(sandbox_sync_main, "Pty", lambda *args, **kwargs: object())
- monkeypatch.setattr(sandbox_sync_main, "Git", lambda *args, **kwargs: object())
-
- sandbox = sandbox_sync_main.Sandbox(
- sandbox_id="sbx-test",
- sandbox_domain="e2b.app",
- envd_version=ENVD_VERSION,
- envd_access_token="tok",
- traffic_access_token="tok",
- connection_config=config,
- )
-
- assert sandbox._envd_api is main_api
- assert sandbox._envd_api is sandbox.files._envd_api
- assert not hasattr(sandbox, "_transport")
-
-
-def test_sync_sandbox_clients_are_created_once_per_calling_thread(
- monkeypatch, test_api_key
-):
- config = ConnectionConfig(api_key=test_api_key)
- created = []
- transports = {}
- lock = threading.Lock()
-
- def get_transport(*_args, **_kwargs):
- thread_id = threading.get_ident()
- with lock:
- transport = transports.get(thread_id)
- if transport is None:
- transport = fake_transport()
- transports[thread_id] = transport
- return transport
-
- def record(kind):
- with lock:
- created.append((kind, threading.get_ident()))
-
- class FakeHttpClient:
- def __init__(self, *args, **kwargs):
- self.transport = kwargs["transport"]
- record("http")
-
- class FakeFilesystemClient:
- def __init__(self, *args, **kwargs):
- self.pool = kwargs["pool"]
- record("filesystem_rpc")
-
- class FakeProcessClient:
- def __init__(self, *args, **kwargs):
- self.pool = kwargs["pool"]
- record("process_rpc")
-
- monkeypatch.setattr(filesystem_sync, "get_envd_transport", get_transport)
- monkeypatch.setattr(command_sync, "get_envd_transport", get_transport)
- monkeypatch.setattr(pty_sync, "get_envd_transport", get_transport)
- monkeypatch.setattr(filesystem_sync.httpx, "Client", FakeHttpClient)
- monkeypatch.setattr(
- filesystem_sync.filesystem_connect, "FilesystemClient", FakeFilesystemClient
- )
- monkeypatch.setattr(
- command_sync.process_connect, "ProcessClient", FakeProcessClient
- )
- monkeypatch.setattr(pty_sync.process_connect, "ProcessClient", FakeProcessClient)
-
- main_thread_id = threading.get_ident()
- sandbox = sandbox_sync_main.Sandbox(
- sandbox_id="sbx-test",
- sandbox_domain="e2b.app",
- envd_version=ENVD_VERSION,
- envd_access_token="tok",
- traffic_access_token="tok",
- connection_config=config,
- )
-
- assert Counter(kind for kind, thread in created if thread == main_thread_id) == {}
-
- worker_count = 10
- barrier = threading.Barrier(worker_count + 1)
-
- def worker():
- barrier.wait()
- envd_api = sandbox._envd_api
- files_envd_api = sandbox.files._envd_api
- files_rpc = sandbox.files._rpc
- commands_rpc = sandbox.commands._rpc
- pty_rpc = sandbox.pty._rpc
-
- return {
- "thread": threading.get_ident(),
- "same_envd_api": envd_api is files_envd_api,
- "stable": (
- envd_api is sandbox._envd_api
- and files_envd_api is sandbox.files._envd_api
- and files_rpc is sandbox.files._rpc
- and commands_rpc is sandbox.commands._rpc
- and pty_rpc is sandbox.pty._rpc
- ),
- }
-
- with ThreadPoolExecutor(max_workers=worker_count) as executor:
- futures = [executor.submit(worker) for _ in range(worker_count)]
- barrier.wait()
- results = [future.result() for future in futures]
-
- worker_threads = {result["thread"] for result in results}
- worker_created = [
- (kind, thread) for kind, thread in created if thread in worker_threads
- ]
-
- assert Counter(result["same_envd_api"] for result in results) == {
- True: worker_count
- }
- assert Counter(result["stable"] for result in results) == {True: worker_count}
- assert Counter(kind for kind, _thread in worker_created) == {
- "http": worker_count,
- "filesystem_rpc": worker_count,
- "process_rpc": worker_count * 2,
- }
-
-
-def test_sync_filesystem_envd_clients_are_bound_per_calling_thread(
- monkeypatch, test_api_key
-):
- config = ConnectionConfig(api_key=test_api_key)
- main_thread_id = threading.get_ident()
- main_transport = fake_transport()
- worker_transport = fake_transport()
- main_api = Mock(spec=httpx.Client)
- worker_api = Mock(spec=httpx.Client)
- main_rpc = sentinel.main_filesystem_rpc
- worker_rpc = sentinel.worker_filesystem_rpc
-
- monkeypatch.setattr(
- filesystem_sync,
- "get_envd_transport",
- lambda *_args, **_kwargs: main_transport
- if threading.get_ident() == main_thread_id
- else worker_transport,
- )
- monkeypatch.setattr(
- filesystem_sync.httpx,
- "Client",
- lambda *args, **kwargs: main_api
- if kwargs["transport"] is main_transport
- else worker_api,
- )
- monkeypatch.setattr(
- filesystem_sync.filesystem_connect,
- "FilesystemClient",
- lambda *args, **kwargs: main_rpc
- if kwargs["pool"] is main_transport.pool
- else worker_rpc,
- )
-
- fs = Filesystem(
- ENVD_API_URL,
- ENVD_VERSION,
- config,
- )
-
- assert fs._envd_api is main_api
- assert fs._rpc is main_rpc
-
- worker_api_result, worker_rpc_result = run_in_worker_thread(
- lambda: (fs._envd_api, fs._rpc)
- )
- assert worker_api_result is worker_api
- assert worker_rpc_result is worker_rpc
- assert fs._envd_api is main_api
- assert fs._rpc is main_rpc
-
-
-def test_sync_command_rpc_clients_are_bound_per_calling_thread(
- monkeypatch, test_api_key
-):
- config = ConnectionConfig(api_key=test_api_key)
- main_thread_id = threading.get_ident()
- main_transport = fake_transport()
- worker_transport = fake_transport()
- main_rpc = sentinel.main_command_rpc
- worker_rpc = sentinel.worker_command_rpc
-
- monkeypatch.setattr(
- command_sync,
- "get_envd_transport",
- lambda *_args, **_kwargs: main_transport
- if threading.get_ident() == main_thread_id
- else worker_transport,
- )
- monkeypatch.setattr(
- command_sync.process_connect,
- "ProcessClient",
- lambda *args, **kwargs: main_rpc
- if kwargs["pool"] is main_transport.pool
- else worker_rpc,
- )
-
- commands = Commands(ENVD_API_URL, config, ENVD_VERSION)
-
- assert commands._rpc is main_rpc
- worker_rpc_result = run_in_worker_thread(lambda: commands._rpc)
- assert worker_rpc_result is worker_rpc
- assert commands._rpc is main_rpc
-
-
-def test_sync_pty_rpc_clients_are_bound_per_calling_thread(monkeypatch, test_api_key):
- config = ConnectionConfig(api_key=test_api_key)
- main_thread_id = threading.get_ident()
- main_transport = fake_transport()
- worker_transport = fake_transport()
- main_rpc = sentinel.main_pty_rpc
- worker_rpc = sentinel.worker_pty_rpc
-
- monkeypatch.setattr(
- pty_sync,
- "get_envd_transport",
- lambda *_args, **_kwargs: main_transport
- if threading.get_ident() == main_thread_id
- else worker_transport,
- )
- monkeypatch.setattr(
- pty_sync.process_connect,
- "ProcessClient",
- lambda *args, **kwargs: main_rpc
- if kwargs["pool"] is main_transport.pool
- else worker_rpc,
- )
-
- pty = Pty(ENVD_API_URL, config, ENVD_VERSION)
-
- assert pty._rpc is main_rpc
- worker_rpc_result = run_in_worker_thread(lambda: pty._rpc)
- assert worker_rpc_result is worker_rpc
- assert pty._rpc is main_rpc
-
-
-def test_sync_watch_handle_uses_calling_thread_rpc(test_api_key):
- class FakeRpc:
- def __init__(self, name):
- self.name = name
- self.calls = []
-
- def remove_watcher(self, request, **opts):
- self.calls.append(("remove", request.watcher_id))
-
- config = ConnectionConfig(api_key=test_api_key)
-
- main_rpc = FakeRpc("main")
- worker_rpc = FakeRpc("worker")
- handle = WatchHandle(lambda: main_rpc, "watcher-id", config, ENVD_VERSION)
-
- handle.stop()
- assert main_rpc.calls == [("remove", "watcher-id")]
-
- handle = WatchHandle(lambda: worker_rpc, "watcher-id", config, ENVD_VERSION)
- run_in_worker_thread(handle.stop)
- assert worker_rpc.calls == [("remove", "watcher-id")]
diff --git a/packages/python-sdk/tests/test_command_handle.py b/packages/python-sdk/tests/test_command_handle.py
index c8cf957c4..6a2f81c1a 100644
--- a/packages/python-sdk/tests/test_command_handle.py
+++ b/packages/python-sdk/tests/test_command_handle.py
@@ -3,7 +3,9 @@ from typing import Any, cast
import pytest
-from e2b.envd.process import process_pb2
+from protobuf import Oneof
+
+from e2b.envd.process import process_pb
from e2b.sandbox_async.commands.command_handle import AsyncCommandHandle
from e2b.sandbox_sync.commands.command_handle import CommandHandle
@@ -11,27 +13,34 @@ EMOJI = "😀"
EMOJI_BYTES = EMOJI.encode("utf-8") # 4 bytes
-def _stdout_event(data: bytes) -> process_pb2.StartResponse:
- return process_pb2.StartResponse(
- event=process_pb2.ProcessEvent(
- data=process_pb2.ProcessEvent.DataEvent(stdout=data)
+def _stdout_event(data: bytes) -> process_pb.StartResponse:
+ return process_pb.StartResponse(
+ event=process_pb.ProcessEvent(
+ event=Oneof(
+ "data", process_pb.ProcessEvent.DataEvent(output=Oneof("stdout", data))
+ )
)
)
-def _stderr_event(data: bytes) -> process_pb2.StartResponse:
- return process_pb2.StartResponse(
- event=process_pb2.ProcessEvent(
- data=process_pb2.ProcessEvent.DataEvent(stderr=data)
+def _stderr_event(data: bytes) -> process_pb.StartResponse:
+ return process_pb.StartResponse(
+ event=process_pb.ProcessEvent(
+ event=Oneof(
+ "data", process_pb.ProcessEvent.DataEvent(output=Oneof("stderr", data))
+ )
)
)
-def _end_event(exit_code: int = 0) -> process_pb2.StartResponse:
- return process_pb2.StartResponse(
- event=process_pb2.ProcessEvent(
- end=process_pb2.ProcessEvent.EndEvent(
- exit_code=exit_code, exited=True, status="exited"
+def _end_event(exit_code: int = 0) -> process_pb.StartResponse:
+ return process_pb.StartResponse(
+ event=process_pb.ProcessEvent(
+ event=Oneof(
+ "end",
+ process_pb.ProcessEvent.EndEvent(
+ exit_code=exit_code, exited=True, status="exited"
+ ),
)
)
)
diff --git a/packages/python-sdk/tests/test_env_var_parsing.py b/packages/python-sdk/tests/test_env_var_parsing.py
new file mode 100644
index 000000000..8089f16c4
--- /dev/null
+++ b/packages/python-sdk/tests/test_env_var_parsing.py
@@ -0,0 +1,50 @@
+"""Numeric E2B_* env vars are parsed at import time; an empty-string value
+(e.g. `E2B_MAX_CONNECTIONS=` in a dotenv file) must fall back to the default
+instead of raising ValueError when the module is imported."""
+
+import importlib
+
+import e2b.api
+import e2b.envd.client_shared
+
+_ENV_VARS = (
+ "E2B_KEEPALIVE_EXPIRY",
+ "E2B_MAX_KEEPALIVE_CONNECTIONS",
+ "E2B_MAX_CONNECTIONS",
+ "E2B_CONNECTION_RETRIES",
+)
+
+
+def _reload():
+ return (
+ importlib.reload(e2b.envd.client_shared),
+ importlib.reload(e2b.api),
+ )
+
+
+def test_empty_env_vars_fall_back_to_defaults(monkeypatch):
+ for var in _ENV_VARS:
+ monkeypatch.setenv(var, "")
+ try:
+ client_shared, api = _reload()
+ assert client_shared.pool_idle_timeout == 300
+ assert client_shared.pool_max_idle_per_host == 20
+ assert api.connection_retries == 3
+ assert api.limits.max_keepalive_connections == 20
+ assert api.limits.max_connections == 2000
+ assert api.limits.keepalive_expiry == 300
+ finally:
+ monkeypatch.undo()
+ _reload()
+
+
+def test_set_env_vars_are_honored(monkeypatch):
+ monkeypatch.setenv("E2B_KEEPALIVE_EXPIRY", "42")
+ monkeypatch.setenv("E2B_CONNECTION_RETRIES", "5")
+ try:
+ client_shared, api = _reload()
+ assert client_shared.pool_idle_timeout == 42
+ assert api.connection_retries == 5
+ finally:
+ monkeypatch.undo()
+ _reload()
diff --git a/packages/python-sdk/tests/test_envd_client_transport.py b/packages/python-sdk/tests/test_envd_client_transport.py
new file mode 100644
index 000000000..844ec50a2
--- /dev/null
+++ b/packages/python-sdk/tests/test_envd_client_transport.py
@@ -0,0 +1,104 @@
+import httpx
+import pytest
+
+from e2b.envd import client_async, client_sync
+from e2b.envd.client_shared import proxy_to_url
+from e2b.exceptions import InvalidArgumentException
+
+
[email protected](autouse=True)
+def reset_transport_caches():
+ client_sync._transports.clear()
+ client_async._transports.clear()
+ yield
+ client_sync._transports.clear()
+ client_async._transports.clear()
+
+
+def test_proxy_to_url_none():
+ assert proxy_to_url(None) is None
+
+
+def test_proxy_to_url_str():
+ assert proxy_to_url("http://127.0.0.1:8080") == "http://127.0.0.1:8080"
+
+
+def test_proxy_to_url_keeps_credentials_from_url():
+ assert proxy_to_url("http://user:pass@localhost:8030") == (
+ "http://user:pass@localhost:8030"
+ )
+
+
+def test_proxy_to_url_converts_httpx_url():
+ assert proxy_to_url(httpx.URL("http://localhost:8030")) == "http://localhost:8030"
+
+
+def test_proxy_to_url_converts_httpx_proxy_with_auth():
+ proxy = httpx.Proxy("http://localhost:8030", auth=("user@x", "p@ss"))
+ assert proxy_to_url(proxy) == "http://user%40x:p%40ss@localhost:8030"
+
+
+def test_proxy_to_url_keeps_credentials_from_httpx_proxy_url():
+ # httpx.Proxy pulls userinfo out of the URL into `.auth`; conversion
+ # has to fold it back in.
+ proxy = httpx.Proxy("http://user:pass@localhost:8030")
+ assert proxy_to_url(proxy) == "http://user:pass@localhost:8030"
+
+
+def test_proxy_to_url_rejects_httpx_proxy_headers():
+ # Typed so `except SandboxException` handlers catch it at the RPC call.
+ proxy = httpx.Proxy("http://localhost:8030", headers={"X-Custom": "1"})
+ with pytest.raises(InvalidArgumentException, match="headers"):
+ proxy_to_url(proxy)
+
+
+def test_proxy_to_url_rejects_httpx_proxy_ssl_context():
+ import ssl
+
+ proxy = httpx.Proxy(
+ "https://localhost:8030", ssl_context=ssl.create_default_context()
+ )
+ with pytest.raises(InvalidArgumentException, match="ssl_context"):
+ proxy_to_url(proxy)
+
+
+def test_proxy_to_url_rejects_unknown_types():
+ with pytest.raises(InvalidArgumentException, match="URL-string"):
+ proxy_to_url(object())
+
+
+def test_sync_transport_is_cached_per_proxy():
+ transport_a = client_sync.get_transport(None)
+ transport_b = client_sync.get_transport(None)
+ transport_c = client_sync.get_transport("http://127.0.0.1:8080")
+ transport_d = client_sync.get_transport("http://127.0.0.1:8080")
+
+ assert transport_a is transport_b
+ assert transport_c is transport_d
+ assert transport_a is not transport_c
+
+
+def test_async_transport_is_cached_per_proxy():
+ transport_a = client_async.get_transport(None)
+ transport_b = client_async.get_transport(None)
+ transport_c = client_async.get_transport("http://127.0.0.1:8080")
+
+ assert transport_a is transport_b
+ assert transport_a is not transport_c
+ assert client_sync.get_transport(None) is not transport_a
+
+
+def test_transport_stack_normalizes_plain_errors_and_retries_connects():
+ # The shared transports are the plain-HTTP-error normalization wrapping
+ # the connection retries; `E2B_CONNECTION_RETRIES` must flow into the
+ # retry layer the way it does into the httpx REST transports.
+ from e2b.api import connection_retries
+
+ sync_transport = client_sync.get_transport(None)
+ async_transport = client_async.get_transport(None)
+ assert isinstance(sync_transport, client_sync.PlainHTTPErrorTransport)
+ assert isinstance(async_transport, client_async.PlainHTTPErrorTransport)
+ assert isinstance(sync_transport._inner, client_sync.ConnectionRetryTransport)
+ assert isinstance(async_transport._inner, client_async.ConnectionRetryTransport)
+ assert sync_transport._inner._max_retries == connection_retries
+ assert async_transport._inner._max_retries == connection_retries
diff --git a/packages/python-sdk/tests/test_envd_codec.py b/packages/python-sdk/tests/test_envd_codec.py
new file mode 100644
index 000000000..f9398a51f
--- /dev/null
+++ b/packages/python-sdk/tests/test_envd_codec.py
@@ -0,0 +1,41 @@
+"""The envd JSON codec must tolerate unknown response fields (newer envd,
+older SDK) and raise decode failures as ``ConnectError(INTERNAL)`` itself —
+a raw error would hit connectrpc's catch-all and end up a misleading
+sandbox-timeout message in rpc.py.
+"""
+
+import pytest
+from connectrpc.code import Code
+from connectrpc.errors import ConnectError
+
+from e2b.envd.client_shared import ENVD_JSON_CODEC
+from e2b.envd.process.process_pb import ProcessConfig
+from e2b.envd.rpc import handle_rpc_exception, is_transport_failure
+from e2b.exceptions import SandboxException, TimeoutException
+
+
+def test_decodes_and_ignores_unknown_fields():
+ config = ENVD_JSON_CODEC.decode(
+ b'{"cmd": "echo", "notYetInThisSdk": true}', ProcessConfig
+ )
+ assert config.cmd == "echo"
+
+
+def test_decode_failure_raises_typed_connect_error():
+ with pytest.raises(ConnectError) as excinfo:
+ ENVD_JSON_CODEC.decode(b"<html>not json</html>", ProcessConfig)
+ assert excinfo.value.code is Code.INTERNAL
+ assert "ProcessConfig" in excinfo.value.message
+ assert isinstance(excinfo.value.__cause__, Exception)
+
+
+def test_decode_failure_maps_to_sandbox_exception_not_timeout():
+ # INTERNAL has no special mapping in rpc.py: a SandboxException with the
+ # codec's message, never the sandbox-timeout path, and no health probe.
+ with pytest.raises(ConnectError) as excinfo:
+ ENVD_JSON_CODEC.decode(b"not json", ProcessConfig)
+ assert not is_transport_failure(excinfo.value)
+ err = handle_rpc_exception(excinfo.value)
+ assert isinstance(err, SandboxException)
+ assert not isinstance(err, TimeoutException)
+ assert "could not be decoded" in str(err)
diff --git a/packages/python-sdk/tests/test_envd_interceptors.py b/packages/python-sdk/tests/test_envd_interceptors.py
new file mode 100644
index 000000000..0cd9a099e
--- /dev/null
+++ b/packages/python-sdk/tests/test_envd_interceptors.py
@@ -0,0 +1,115 @@
+"""Interceptor behavior the SDK relies on but connectrpc doesn't guarantee:
+closing a server stream early must reach the innermost (transport) generator
+synchronously — hyper only sends RST_STREAM when its generator is closed, and
+a stranded inner generator defers that to GC.
+"""
+
+import logging
+from functools import partial
+
+from connectrpc._interceptor_async import (
+ MetadataInterceptor,
+ resolve_interceptors as resolve_interceptors_async,
+)
+from connectrpc._interceptor_sync import (
+ MetadataInterceptorSync,
+ resolve_interceptors as resolve_interceptors_sync,
+)
+from unittest.mock import MagicMock
+
+from e2b.connection_config import ConnectionConfig
+from e2b.envd.interceptors import (
+ DefaultHeadersInterceptor,
+ build_interceptors,
+)
+
+
+def _ctx():
+ ctx = MagicMock()
+ ctx.request_headers = {}
+ ctx.method.service_name = "svc"
+ ctx.method.name = "method"
+ return ctx
+
+
+def _compose_sync(interceptors, base):
+ execute = base
+ for interceptor in reversed(resolve_interceptors_sync(interceptors)):
+ method = getattr(interceptor, "intercept_server_stream_sync", None)
+ if method is not None:
+ execute = partial(method, execute)
+ return execute
+
+
+def _compose_async(interceptors, base):
+ execute = base
+ for interceptor in reversed(resolve_interceptors_async(interceptors)):
+ method = getattr(interceptor, "intercept_server_stream", None)
+ if method is not None:
+ execute = partial(method, execute)
+ return execute
+
+
+def test_headers_interceptor_is_not_a_metadata_interceptor():
+ # connectrpc wraps metadata interceptors around server streams in a
+ # generator that doesn't propagate close()/aclose() to the inner stream —
+ # the headers interceptor must resolve as a direct interceptor instead.
+ interceptor = DefaultHeadersInterceptor({})
+ assert not isinstance(interceptor, MetadataInterceptor)
+ assert not isinstance(interceptor, MetadataInterceptorSync)
+
+
+def test_headers_interceptor_applies_defaults_and_keeps_per_call_headers():
+ interceptor = DefaultHeadersInterceptor({"User-Agent": "sdk", "X-Token": "t"})
+ ctx = _ctx()
+ ctx.request_headers = {"X-Token": "per-call"}
+ result = interceptor.intercept_server_stream_sync(
+ lambda request, ctx: iter(["ok"]), None, ctx
+ )
+ assert ctx.request_headers == {"X-Token": "per-call", "User-Agent": "sdk"}
+ assert list(result) == ["ok"]
+
+
+def _full_chain_config() -> ConnectionConfig:
+ # The logger is the worst case: it adds a generator interceptor layer
+ # around every server stream.
+ return ConnectionConfig(api_key="k", logger=logging.getLogger("test"))
+
+
+def test_sync_stream_close_reaches_transport_generator():
+ closed = []
+
+ def transport(request, ctx):
+ try:
+ for i in range(10):
+ yield i
+ finally:
+ closed.append(True)
+
+ stream = _compose_sync(
+ build_interceptors(_full_chain_config(), "http://base"), transport
+ )(None, _ctx())
+ assert next(stream) == 0
+ stream.close()
+ assert closed == [True]
+
+
+async def test_async_stream_close_reaches_transport_generator():
+ # Before the interceptors propagated aclose(), the transport generator
+ # was only finalized by the event loop's async-generator GC hook, several
+ # loop iterations after aclose() returned.
+ closed = []
+
+ async def transport(request, ctx):
+ try:
+ for i in range(10):
+ yield i
+ finally:
+ closed.append(True)
+
+ stream = _compose_async(
+ build_interceptors(_full_chain_config(), "http://base"), transport
+ )(None, _ctx())
+ assert await stream.__anext__() == 0
+ await stream.aclose()
+ assert closed == [True]
diff --git a/packages/python-sdk/tests/test_envd_plain_http_errors.py b/packages/python-sdk/tests/test_envd_plain_http_errors.py
new file mode 100644
index 000000000..7962fbd3e
--- /dev/null
+++ b/packages/python-sdk/tests/test_envd_plain_http_errors.py
@@ -0,0 +1,228 @@
+"""Plain (non-Connect-encoded) HTTP error responses — e.g. an edge proxy
+answering for envd — must surface with the vendored client's status mapping
+(#806) and the response body as the message. ``PlainHTTPErrorTransport``
+raises them as ``ConnectError`` below connectrpc, before connectrpc would
+collapse them into Connect-spec codes with synthesized reason phrases
+(404 → UNIMPLEMENTED "Not Found"); connectrpc re-raises transport
+``ConnectError`` unchanged, which the end-to-end tests pin through the real
+generated stubs.
+"""
+
+import httpx
+import pytest
+from connectrpc.code import Code
+from connectrpc.errors import ConnectError
+from envd_frame_server import (
+ frame_recording_server,
+ make_async_client,
+ make_sync_client,
+ make_config,
+)
+from packaging.version import Version
+from pyqwest import (
+ Headers,
+ HTTPTransport,
+ HTTPVersion,
+ Request,
+ Response,
+ SyncHTTPTransport,
+ SyncRequest,
+ SyncResponse,
+)
+
+import e2b.sandbox_async.commands.command as command_async
+from e2b.envd.client_async import (
+ ConnectionRetryTransport,
+ PlainHTTPErrorTransport,
+)
+from e2b.envd.client_sync import (
+ ConnectionRetryTransport as SyncConnectionRetryTransport,
+ PlainHTTPErrorTransport as SyncPlainHTTPErrorTransport,
+)
+from e2b.envd.process.process_pb import ConnectRequest
+from e2b.sandbox_async.commands.command import Commands
+
+
+class RespondingTransport:
+ """Inner async transport answering every request with a fixed response."""
+
+ def __init__(self, status: int, content_type: str, body: bytes):
+ self.status = status
+ self.content_type = content_type
+ self.body = body
+
+ async def execute(self, request) -> Response:
+ return Response(
+ status=self.status,
+ headers=Headers({"content-type": self.content_type}),
+ content=self.body,
+ )
+
+
+class RespondingSyncTransport:
+ def __init__(self, status: int, content_type: str, body: bytes):
+ self.status = status
+ self.content_type = content_type
+ self.body = body
+
+ def execute_sync(self, request) -> SyncResponse:
+ return SyncResponse(
+ status=self.status,
+ headers=Headers({"content-type": self.content_type}),
+ content=self.body,
+ )
+
+
+def _sync_request() -> SyncRequest:
+ return SyncRequest("POST", "http://sandbox.test/rpc")
+
+
+async def _executed(status: int, content_type: str, body: bytes):
+ transport = PlainHTTPErrorTransport(RespondingTransport(status, content_type, body))
+ return await transport.execute(Request("POST", "http://sandbox.test/rpc"))
+
+
+async def _raised(status: int, content_type: str, body: bytes) -> ConnectError:
+ with pytest.raises(ConnectError) as excinfo:
+ await _executed(status, content_type, body)
+ return excinfo.value
+
+
+async def test_async_maps_plain_statuses_to_vendored_codes():
+ assert (await _raised(404, "text/plain", b"x")).code is Code.NOT_FOUND
+ assert (await _raised(409, "text/plain", b"x")).code is Code.ALREADY_EXISTS
+ assert (await _raised(429, "text/plain", b"x")).code is Code.RESOURCE_EXHAUSTED
+ assert (await _raised(502, "text/html", b"x")).code is Code.UNAVAILABLE
+ # Statuses outside the vendored table stay unknown, as before.
+ assert (await _raised(418, "text/plain", b"x")).code is Code.UNKNOWN
+
+
+async def test_async_uses_body_as_message():
+ error = await _raised(404, "text/plain", b"sandbox not found")
+ assert error.message == "sandbox not found"
+
+
+async def test_async_empty_body_falls_back_to_status():
+ error = await _raised(404, "text/plain", b"")
+ assert error.message == "HTTP 404"
+
+
+async def test_async_leaves_connect_encoded_errors_to_connectrpc():
+ # A valid Connect error (JSON body with a string `code`) is left to
+ # connectrpc, rebuilt with the validity-checked body restored.
+ for content_type in ("application/json", "application/json; charset=utf-8"):
+ response = await _executed(404, content_type, b'{"code": "not_found"}')
+ assert response.status == 404
+ body = bytearray()
+ async for chunk in response.content:
+ body.extend(chunk)
+ assert bytes(body) == b'{"code": "not_found"}'
+
+
+async def test_async_maps_json_errors_without_a_valid_connect_code():
+ # A gateway answering with a JSON body that is not Connect-encoded (#806):
+ # an int `code` is treated as the HTTP status, like the vendored client.
+ error = await _raised(
+ 429, "application/json", b'{"code": 429, "message": "rate limited"}'
+ )
+ assert error.code is Code.RESOURCE_EXHAUSTED
+ assert error.message == "rate limited"
+
+ # No `code` at all falls back to the response status, body as message.
+ error = await _raised(404, "application/json", b'{"error": "no such route"}')
+ assert error.code is Code.NOT_FOUND
+ assert error.message == '{"error": "no such route"}'
+
+ # Unparseable JSON falls back to the response status too.
+ error = await _raised(502, "application/json", b"<html>bad gateway</html>")
+ assert error.code is Code.UNAVAILABLE
+
+ # An invalid code string is not a Connect error either.
+ error = await _raised(429, "application/json", b'{"code": "TOO_MANY"}')
+ assert error.code is Code.RESOURCE_EXHAUSTED
+
+
+async def test_async_leaves_successful_responses_untouched():
+ response = await _executed(200, "application/json", b"{}")
+ assert response.status == 200
+
+
+def test_sync_maps_plain_statuses_to_vendored_codes():
+ transport = SyncPlainHTTPErrorTransport(
+ RespondingSyncTransport(404, "text/plain", b"sandbox not found")
+ )
+ with pytest.raises(ConnectError) as excinfo:
+ transport.execute_sync(_sync_request())
+ assert excinfo.value.code is Code.NOT_FOUND
+ assert excinfo.value.message == "sandbox not found"
+
+
+def test_sync_leaves_connect_encoded_errors_to_connectrpc():
+ transport = SyncPlainHTTPErrorTransport(
+ RespondingSyncTransport(404, "application/json", b'{"code": "not_found"}')
+ )
+ response = transport.execute_sync(_sync_request())
+ assert response.status == 404
+ assert b"".join(response.content) == b'{"code": "not_found"}'
+
+
+def test_sync_maps_json_errors_without_a_valid_connect_code():
+ transport = SyncPlainHTTPErrorTransport(
+ RespondingSyncTransport(
+ 429, "application/json", b'{"code": 429, "message": "rate limited"}'
+ )
+ )
+ with pytest.raises(ConnectError) as excinfo:
+ transport.execute_sync(_sync_request())
+ assert excinfo.value.code is Code.RESOURCE_EXHAUSTED
+ assert excinfo.value.message == "rate limited"
+
+
+# End-to-end through the generated stubs against a real HTTP/2 server
+# answering with a plain 404: pins that connectrpc re-raises the transport's
+# ConnectError unchanged (`except ConnectError: raise`) on both the unary
+# and the server-stream paths.
+
+_PLAIN_404 = (404, "text/plain", b"sandbox not found")
+
+
+def _stack(transport) -> PlainHTTPErrorTransport:
+ # The factories' transport stack, minus TLS (the test server is
+ # plaintext, so HTTP/2 by prior knowledge instead of ALPN).
+ return PlainHTTPErrorTransport(ConnectionRetryTransport(transport))
+
+
+async def test_async_kill_returns_false_on_plain_http_404(monkeypatch):
+ with frame_recording_server(server_ends_stream=False, plain_error=_PLAIN_404) as (
+ server
+ ):
+ base_url = f"http://127.0.0.1:{server.port}"
+ rpc = make_async_client(
+ server.port,
+ transport=_stack(HTTPTransport(http_version=HTTPVersion.HTTP2)),
+ )
+ # Hand Commands the plaintext test client; the real factory would
+ # also register a pooled TLS transport in the process-global cache.
+ monkeypatch.setattr(
+ command_async, "create_rpc_client", lambda *_args, **_kwargs: rpc
+ )
+ commands = Commands(
+ base_url, make_config(), Version("0.5.0"), httpx.AsyncClient()
+ )
+ assert await commands.kill(pid=1) is False
+
+
+def test_sync_stream_surfaces_plain_http_404_with_vendored_code():
+ with frame_recording_server(server_ends_stream=False, plain_error=_PLAIN_404) as (
+ server
+ ):
+ sync_stack = SyncPlainHTTPErrorTransport(
+ SyncConnectionRetryTransport(
+ SyncHTTPTransport(http_version=HTTPVersion.HTTP2)
+ )
+ )
+ client = make_sync_client(server.port, transport=sync_stack)
+ with pytest.raises(ConnectError) as excinfo:
+ next(iter(client.connect(ConnectRequest())))
+ assert excinfo.value.code is Code.NOT_FOUND
+ assert excinfo.value.message == "sandbox not found"
diff --git a/packages/python-sdk/tests/test_envd_retry_transport.py b/packages/python-sdk/tests/test_envd_retry_transport.py
new file mode 100644
index 000000000..00f20cb66
--- /dev/null
+++ b/packages/python-sdk/tests/test_envd_retry_transport.py
@@ -0,0 +1,183 @@
+"""Connection retries for envd RPCs live in pyqwest's transport middleware
+(``ConnectionRetryTransport``), below connectrpc. The policy retries only the
+builtin ``ConnectionError``, which pyqwest raises solely while establishing
+the connection — before the request could have reached envd — so a retry can
+never replay a delivered request (which could re-run a command or re-deliver
+events), for unary and streaming RPCs alike.
+"""
+
+import pytest
+from pyqwest import (
+ HTTPTransport,
+ HTTPVersion,
+ Request,
+ Response,
+ SyncHTTPTransport,
+ SyncRequest,
+ SyncResponse,
+ WriteError,
+)
+from envd_frame_server import (
+ assert_stdout_event,
+ frame_recording_server,
+ make_async_client,
+ make_sync_client,
+)
+
+from e2b.envd.client_async import ConnectionRetryTransport
+from e2b.envd.client_sync import (
+ ConnectionRetryTransport as SyncConnectionRetryTransport,
+)
+from e2b.envd.process.process_pb import ConnectRequest
+
+
+def _retrying(inner) -> ConnectionRetryTransport:
+ # Keep the exponential backoff out of test wall-clock time.
+ return ConnectionRetryTransport(
+ inner, initial_interval=0.001, max_interval=0.002, max_retries=3
+ )
+
+
+def _retrying_sync(inner) -> SyncConnectionRetryTransport:
+ return SyncConnectionRetryTransport(
+ inner, initial_interval=0.001, max_interval=0.002, max_retries=3
+ )
+
+
+class FakeTransport:
+ """Inner async transport that raises the queued errors, then succeeds."""
+
+ def __init__(self, errors=(), status: int = 200):
+ self.errors = list(errors)
+ self.status = status
+ self.attempts = 0
+
+ async def execute(self, request: Request) -> Response:
+ self.attempts += 1
+ if self.errors:
+ raise self.errors.pop(0)
+ return Response(status=self.status, content=b"ok")
+
+
+class FakeSyncTransport:
+ def __init__(self, errors=(), status: int = 200):
+ self.errors = list(errors)
+ self.status = status
+ self.attempts = 0
+
+ def execute_sync(self, request: SyncRequest) -> SyncResponse:
+ self.attempts += 1
+ if self.errors:
+ raise self.errors.pop(0)
+ return SyncResponse(status=self.status, content=b"ok")
+
+
+def _request() -> Request:
+ return Request("POST", "http://sandbox.test/rpc", content=b"payload")
+
+
+def _sync_request() -> SyncRequest:
+ return SyncRequest("POST", "http://sandbox.test/rpc", content=b"payload")
+
+
+async def test_async_retries_failed_connects():
+ inner = FakeTransport(errors=[ConnectionError("connect"), ConnectionError("dns")])
+ response = await _retrying(inner).execute(_request())
+ assert response.status == 200
+ assert inner.attempts == 3
+
+
+def test_sync_retries_failed_connects():
+ inner = FakeSyncTransport(errors=[ConnectionError("connect")])
+ response = _retrying_sync(inner).execute_sync(_sync_request())
+ assert response.status == 200
+ assert inner.attempts == 2
+
+
+async def test_async_does_not_retry_after_request_was_sent():
+ # A WriteError means the connection was up — the request may have reached
+ # envd and started the command, so replaying it is not safe.
+ inner = FakeTransport(errors=[WriteError("connection closed")])
+ with pytest.raises(WriteError):
+ await _retrying(inner).execute(_request())
+ assert inner.attempts == 1
+
+
+def test_sync_does_not_retry_after_request_was_sent():
+ inner = FakeSyncTransport(errors=[WriteError("connection closed")])
+ with pytest.raises(WriteError):
+ _retrying_sync(inner).execute_sync(_sync_request())
+ assert inner.attempts == 1
+
+
+async def test_async_does_not_retry_error_responses():
+ # An error response is envd (or a proxy) answering — a definitive result.
+ # The middleware's default policy would retry 5xx for idempotent methods.
+ inner = FakeTransport(status=502)
+ response = await _retrying(inner).execute(_request())
+ assert response.status == 502
+ assert inner.attempts == 1
+
+
+async def test_async_raises_last_connect_error_when_exhausted():
+ inner = FakeTransport(errors=[ConnectionError("connect")] * 10)
+ with pytest.raises(ConnectionError):
+ await _retrying(inner).execute(_request())
+ # `max_retries` extra attempts after the first.
+ assert inner.attempts == 4
+
+
+class ConnectFlakyTransport:
+ """Delegating async transport whose first ``failures`` executions fail the
+ way a refused TCP connect does."""
+
+ def __init__(self, inner, failures: int = 1):
+ self.inner = inner
+ self.failures = failures
+ self.attempts = 0
+
+ async def execute(self, request: Request) -> Response:
+ self.attempts += 1
+ if self.attempts <= self.failures:
+ raise ConnectionError("tcp connect error")
+ return await self.inner.execute(request)
+
+
+class ConnectFlakySyncTransport:
+ def __init__(self, inner, failures: int = 1):
+ self.inner = inner
+ self.failures = failures
+ self.attempts = 0
+
+ def execute_sync(self, request: SyncRequest) -> SyncResponse:
+ self.attempts += 1
+ if self.attempts <= self.failures:
+ raise ConnectionError("tcp connect error")
+ return self.inner.execute_sync(request)
+
+
+# End-to-end through the generated stub: verifies streaming RPCs route
+# through the transport middleware (connectrpc opens streams via
+# `Client.stream`, a different client path than unary `post`).
+
+
+async def test_async_stream_setup_retries_failed_connects():
+ with frame_recording_server(server_ends_stream=True) as server:
+ flaky = ConnectFlakyTransport(HTTPTransport(http_version=HTTPVersion.HTTP2))
+ client = make_async_client(server.port, transport=_retrying(flaky))
+ events = [event async for event in client.connect(ConnectRequest())]
+ assert len(events) == 1
+ assert_stdout_event(events[0])
+ assert flaky.attempts == 2
+
+
+def test_sync_stream_setup_retries_failed_connects():
+ with frame_recording_server(server_ends_stream=True) as server:
+ flaky = ConnectFlakySyncTransport(
+ SyncHTTPTransport(http_version=HTTPVersion.HTTP2)
+ )
+ client = make_sync_client(server.port, transport=_retrying_sync(flaky))
+ events = list(client.connect(ConnectRequest()))
+ assert len(events) == 1
+ assert_stdout_event(events[0])
+ assert flaky.attempts == 2
diff --git a/packages/python-sdk/tests/test_envd_rpc_exception.py b/packages/python-sdk/tests/test_envd_rpc_exception.py
index c366f6125..5a911ec28 100644
--- a/packages/python-sdk/tests/test_envd_rpc_exception.py
+++ b/packages/python-sdk/tests/test_envd_rpc_exception.py
@@ -1,10 +1,14 @@
-import httpcore
+import asyncio
+
+from connectrpc.code import Code
+from connectrpc.errors import ConnectError
+from pyqwest import StreamError, StreamErrorCode
-from e2b_connect.client import Code, ConnectException
from e2b.envd.rpc import (
ahandle_rpc_exception_with_health,
handle_rpc_exception,
handle_rpc_exception_with_health,
+ is_transport_failure,
)
from e2b.exceptions import (
AuthenticationException,
@@ -17,72 +21,145 @@ from e2b.exceptions import (
def test_maps_invalid_argument():
- err = handle_rpc_exception(ConnectException(Code.invalid_argument, "bad"))
+ err = handle_rpc_exception(ConnectError(Code.INVALID_ARGUMENT, "bad"))
assert isinstance(err, InvalidArgumentException)
def test_maps_unauthenticated():
- err = handle_rpc_exception(ConnectException(Code.unauthenticated, "nope"))
+ err = handle_rpc_exception(ConnectError(Code.UNAUTHENTICATED, "nope"))
assert isinstance(err, AuthenticationException)
def test_maps_not_found():
- err = handle_rpc_exception(ConnectException(Code.not_found, "missing"))
+ err = handle_rpc_exception(ConnectError(Code.NOT_FOUND, "missing"))
assert isinstance(err, NotFoundException)
def test_maps_resource_exhausted_to_rate_limit():
- err = handle_rpc_exception(ConnectException(Code.resource_exhausted, "too many"))
+ err = handle_rpc_exception(ConnectError(Code.RESOURCE_EXHAUSTED, "too many"))
assert isinstance(err, RateLimitException)
assert "Rate limit" in str(err)
def test_maps_unavailable_to_timeout():
- err = handle_rpc_exception(ConnectException(Code.unavailable, "gone"))
+ err = handle_rpc_exception(ConnectError(Code.UNAVAILABLE, "gone"))
+ assert isinstance(err, TimeoutException)
+
+
+def test_maps_deadline_exceeded_to_timeout():
+ # connectrpc raises DEADLINE_EXCEEDED both for a client-enforced deadline
+ # (`request_timeout` on unary calls, `timeout` on streams) and for the
+ # server-side `connect-timeout-ms` deadline.
+ err = handle_rpc_exception(ConnectError(Code.DEADLINE_EXCEEDED, "timed out"))
assert isinstance(err, TimeoutException)
def test_falls_back_to_sandbox_exception():
- err = handle_rpc_exception(ConnectException(Code.internal, "boom"))
+ err = handle_rpc_exception(ConnectError(Code.INTERNAL, "boom"))
assert isinstance(err, SandboxException)
-def test_returns_raw_remote_protocol_error_without_health_result():
- original = httpcore.RemoteProtocolError(
- "<StreamReset stream_id:1, error_code:2, remote_reset:True>"
- )
+def test_returns_original_when_not_connect_error():
+ original = ValueError("not connect")
err = handle_rpc_exception(original)
assert err is original
-def test_returns_raw_network_errors():
- original = httpcore.ReadError("read failed")
- err = handle_rpc_exception(original)
- assert err is original
+def _stream_reset() -> ConnectError:
+ # connectrpc wraps transport-level failures (e.g. an HTTP/2 RST_STREAM)
+ # in a ConnectError with the original exception as __cause__.
+ try:
+ raise ConnectError(Code.UNAVAILABLE, "stream reset by peer") from OSError(
+ "stream reset"
+ )
+ except ConnectError as e:
+ return e
+
+
+def _cancelled() -> ConnectError:
+ # connectrpc converts asyncio cancellation into ConnectError(CANCELED)
+ # with the CancelledError as __cause__.
+ try:
+ raise ConnectError(Code.CANCELED, "Request was cancelled") from (
+ asyncio.CancelledError()
+ )
+ except ConnectError as e:
+ return e
+
+
+def _wrapped_client_failure() -> ConnectError:
+ # connectrpc's catch-all wraps unexpected client-side exceptions as
+ # ConnectError(UNAVAILABLE) with __cause__ set. Decode failures never
+ # take this path (the codec raises typed, see test_envd_codec.py); what
+ # remains maps by code.
+ try:
+ raise ConnectError(Code.UNAVAILABLE, "bad frame") from ValueError("bad frame")
+ except ConnectError as e:
+ return e
+
+
+def test_transport_failure_detection():
+ assert is_transport_failure(_stream_reset())
+ # An HTTP/2 stream reset surfaces as a pyqwest StreamError cause.
+ try:
+ raise ConnectError(Code.INTERNAL, "reset") from StreamError(
+ "reset", StreamErrorCode.INTERNAL_ERROR
+ )
+ except ConnectError as e:
+ assert is_transport_failure(e)
+ # Errors parsed from an envd response have no cause.
+ assert not is_transport_failure(ConnectError(Code.UNAVAILABLE, "502"))
+ # A wrapped client-side failure carries a cause, but the request was
+ # delivered — probing health would be wrong.
+ assert not is_transport_failure(_wrapped_client_failure())
+ # A client-enforced deadline carries a cause but is a definitive result.
+ try:
+ raise ConnectError(Code.DEADLINE_EXCEEDED, "Request timed out") from (
+ TimeoutError()
+ )
+ except ConnectError as e:
+ assert not is_transport_failure(e)
+ # Asyncio cancellation is not a connection failure — it must not
+ # trigger a health probe.
+ assert not is_transport_failure(_cancelled())
+ assert not is_transport_failure(ValueError("other"))
+
+
+def test_wrapped_client_failure_maps_by_code():
+ # A non-transport cause doesn't change the mapping — the raw exception
+ # must not escape the documented exception surface.
+ err = handle_rpc_exception(_wrapped_client_failure())
+ assert isinstance(err, SandboxException)
+ assert not isinstance(err, ValueError)
-def test_maps_read_timeout_to_timeout():
- # A transport-level read timeout (e.g. a unary call exceeding `request_timeout`)
- # must surface as a TimeoutException rather than leaking the raw httpcore error.
- err = handle_rpc_exception(httpcore.ReadTimeout("the read operation timed out"))
- assert isinstance(err, TimeoutException)
+def test_health_check_not_run_for_wrapped_client_failure():
+ def fail():
+ raise AssertionError("health check should not run")
+ err = handle_rpc_exception_with_health(_wrapped_client_failure(), fail)
+ assert isinstance(err, SandboxException)
-def test_maps_connect_timeout_to_timeout():
- err = handle_rpc_exception(httpcore.ConnectTimeout("connect timed out"))
- assert isinstance(err, TimeoutException)
+def test_cancellation_restores_cancelled_error():
+ err = _cancelled()
+ restored = handle_rpc_exception(err)
+ assert restored is err.__cause__
+ assert isinstance(restored, asyncio.CancelledError)
-def test_returns_original_when_not_connect_exception():
- original = ValueError("not connect")
- err = handle_rpc_exception(original)
- assert err is original
+def test_health_check_not_run_for_cancellation():
+ def fail():
+ raise AssertionError("health check should not run")
+
+ restored = handle_rpc_exception_with_health(_cancelled(), fail)
+ assert isinstance(restored, asyncio.CancelledError)
-def _stream_reset() -> httpcore.RemoteProtocolError:
- return httpcore.RemoteProtocolError(
- "<StreamReset stream_id:1, error_code:2, remote_reset:True>"
- )
+
+def test_returns_raw_transport_failure_without_health_result():
+ original = _stream_reset()
+ err = handle_rpc_exception(original)
+ assert err is original
def test_health_check_confirms_sandbox_killed():
@@ -117,7 +194,7 @@ def test_health_check_not_run_for_other_exceptions():
raise AssertionError("health check should not run")
err = handle_rpc_exception_with_health(
- ConnectException(Code.not_found, "missing"), fail
+ ConnectError(Code.NOT_FOUND, "missing"), fail
)
assert isinstance(err, NotFoundException)
diff --git a/packages/python-sdk/tests/test_envd_stream_request_timeout.py b/packages/python-sdk/tests/test_envd_stream_request_timeout.py
new file mode 100644
index 000000000..82c829ef7
--- /dev/null
+++ b/packages/python-sdk/tests/test_envd_stream_request_timeout.py
@@ -0,0 +1,115 @@
+"""
+`request_timeout` on async streaming calls bounds opening the stream — the
+wait for the start event — mirroring the JS SDK's ``requestTimeoutMs`` timer
+that is disarmed once the stream is open. The stream itself stays bounded by
+`timeout` only.
+
+The tricky part is cancellation: ``asyncio.wait_for`` delivers its expiry as
+a cancellation, which connectrpc converts into ``ConnectError(CANCELED)``
+before ``wait_for`` can turn it into ``TimeoutError``. The helper must
+surface that as ``TimeoutException`` while a caller genuinely cancelling the
+task keeps its cancellation semantics. ``test_envd_stream_reset`` pins the
+frame-level counterpart: a timed-out setup cancels the HTTP/2 stream
+(``RST_STREAM``) instead of leaving it attached to envd.
+"""
+
+import asyncio
+import time
+
+import httpx
+import pytest
+from connectrpc.code import Code
+from connectrpc.errors import ConnectError
+from envd_frame_server import make_config
+from packaging.version import Version
+
+import e2b.sandbox_async.commands.command as command_async
+from e2b.envd.client_async import first_event
+from e2b.envd.rpc import handle_rpc_exception
+from e2b.exceptions import TimeoutException
+from e2b.sandbox_async.commands.command import Commands
+
+
+async def connectrpc_style_stream(delay: float):
+ # connectrpc's stream generator converts the CancelledError delivered by
+ # wait_for's expiry into ConnectError(CANCELED) (see _client_async).
+ try:
+ await asyncio.sleep(delay)
+ yield "start"
+ except asyncio.CancelledError as e:
+ raise ConnectError(Code.CANCELED, "Request was cancelled") from e
+
+
+async def test_returns_first_event():
+ assert await first_event(connectrpc_style_stream(0), 5) == "start"
+
+
+async def test_no_request_timeout_means_unbounded():
+ assert await first_event(connectrpc_style_stream(0.05), None) == "start"
+
+
+async def test_timeout_raises_timeout_exception():
+ start = time.monotonic()
+ with pytest.raises(TimeoutException, match="request_timeout"):
+ await first_event(connectrpc_style_stream(30), 0.1)
+ assert time.monotonic() - start < 5
+
+
+async def test_timeout_when_cancellation_propagates():
+ # A stream cancelled outside connectrpc's conversion scope (e.g. before
+ # the request is sent) lets wait_for raise TimeoutError itself.
+ async def plain_stream():
+ await asyncio.sleep(30)
+ yield "start"
+
+ with pytest.raises(TimeoutException, match="request_timeout"):
+ await first_event(plain_stream(), 0.1)
+
+
+async def test_external_cancellation_is_not_masked():
+ seen: list[BaseException] = []
+
+ async def call():
+ try:
+ await first_event(connectrpc_style_stream(30), 30)
+ except BaseException as e:
+ seen.append(e)
+ raise
+
+ task = asyncio.ensure_future(call())
+ await asyncio.sleep(0.05)
+ task.cancel()
+ with pytest.raises(BaseException):
+ await task
+
+ assert len(seen) == 1
+ # Depending on the Python version the cancellation surfaces directly or
+ # as connectrpc's converted error — either way the call sites'
+ # handle_rpc_exception must restore the CancelledError, never a timeout.
+ err = seen[0]
+ if isinstance(err, ConnectError):
+ err = handle_rpc_exception(err)
+ assert isinstance(err, asyncio.CancelledError)
+
+
+async def test_commands_connect_applies_request_timeout(monkeypatch):
+ class NeverStartingRpc:
+ def connect(self, req, headers=None, timeout_ms=None):
+ return connectrpc_style_stream(30)
+
+ # Hand Commands the stub directly; the real factory would register a
+ # pooled transport in the process-global cache.
+ monkeypatch.setattr(
+ command_async, "create_rpc_client", lambda *_args, **_kwargs: NeverStartingRpc()
+ )
+ commands = Commands(
+ "http://127.0.0.1:1",
+ make_config(),
+ Version("0.5.0"),
+ httpx.AsyncClient(),
+ )
+
+ start = time.monotonic()
+ with pytest.raises(TimeoutException, match="request_timeout"):
+ await commands.connect(pid=1, request_timeout=0.1)
+ assert time.monotonic() - start < 5
diff --git a/packages/python-sdk/tests/test_envd_stream_reset.py b/packages/python-sdk/tests/test_envd_stream_reset.py
new file mode 100644
index 000000000..fa908f08f
--- /dev/null
+++ b/packages/python-sdk/tests/test_envd_stream_reset.py
@@ -0,0 +1,105 @@
+"""
+Server streams closed before the server ends them must cancel the HTTP/2
+stream (``RST_STREAM`` CANCEL) so envd tears the stream down server-side.
+
+A stream that is merely abandoned stays attached to envd's process output
+fan-out and, once its flow-control window fills, blocks output delivery for
+every other consumer of the same process on the shared connection (#1352,
+#1587). The previous httpcore-based transport had exactly that bug; on this
+stack the cancellation comes from pyqwest (hyper), and these tests pin the
+behavior at the frame level: a real plaintext HTTP/2 server records the
+frames the client sends (see ``envd_frame_server``), and the client is the
+actual generated stub wired with the SDK's codec and interceptors, as built
+by the ``e2b.envd.client_sync``/``client_async`` factories.
+"""
+
+import logging
+
+import pytest
+from envd_frame_server import (
+ assert_stdout_event,
+ frame_recording_server,
+ make_async_client,
+ make_sync_client,
+)
+
+from e2b.envd.client_async import first_event
+from e2b.exceptions import TimeoutException
+from e2b.envd.process.process_pb import ConnectRequest
+
+
+def test_sync_early_close_sends_rst_stream():
+ with frame_recording_server(server_ends_stream=False) as server:
+ events = make_sync_client(server.port).connect(ConnectRequest())
+ assert_stdout_event(next(events))
+ assert server.resets == []
+ events.close() # what CommandHandle.disconnect() does
+ server.assert_reset_sent()
+
+
+def test_sync_completed_stream_does_not_send_rst_stream():
+ with frame_recording_server(server_ends_stream=True) as server:
+ events = list(make_sync_client(server.port).connect(ConnectRequest()))
+ assert len(events) == 1
+ server.assert_no_reset_sent()
+
+
+def test_sync_early_close_propagates_through_logging_interceptor():
+ # The logging interceptor wraps the stream in another generator; closing
+ # the outer one must still cancel the underlying HTTP/2 stream.
+ with frame_recording_server(server_ends_stream=False) as server:
+ client = make_sync_client(server.port, logger=logging.getLogger("test.reset"))
+ events = client.connect(ConnectRequest())
+ assert_stdout_event(next(events))
+ events.close()
+ server.assert_reset_sent()
+
+
+def test_sync_abandoned_stream_sends_rst_stream():
+ # No close() at all — dropping the last reference must still cancel the
+ # stream (refcount finalization closes the generator chain).
+ with frame_recording_server(server_ends_stream=False) as server:
+ events = make_sync_client(server.port).connect(ConnectRequest())
+ assert_stdout_event(next(events))
+ del events
+ server.assert_reset_sent()
+
+
+async def test_async_early_close_sends_rst_stream():
+ with frame_recording_server(server_ends_stream=False) as server:
+ events = make_async_client(server.port).connect(ConnectRequest())
+ assert_stdout_event(await events.__anext__())
+ assert server.resets == []
+ await events.aclose() # what AsyncCommandHandle.disconnect() does
+ server.assert_reset_sent()
+
+
+async def test_async_completed_stream_does_not_send_rst_stream():
+ with frame_recording_server(server_ends_stream=True) as server:
+ events = [
+ event
+ async for event in make_async_client(server.port).connect(ConnectRequest())
+ ]
+ assert len(events) == 1
+ server.assert_no_reset_sent()
+
+
+async def test_async_early_close_propagates_through_logging_interceptor():
+ with frame_recording_server(server_ends_stream=False) as server:
+ client = make_async_client(server.port, logger=logging.getLogger("test.reset"))
+ events = client.connect(ConnectRequest())
+ assert_stdout_event(await events.__anext__())
+ await events.aclose()
+ server.assert_reset_sent()
+
+
+async def test_async_setup_timeout_sends_rst_stream():
+ # `request_timeout` expiring while envd never answers (see
+ # test_envd_stream_request_timeout) must tear the HTTP/2 stream down,
+ # not leave it attached to the shared connection.
+ with frame_recording_server(server_ends_stream=False, respond=False) as server:
+ events = make_async_client(server.port).connect(ConnectRequest())
+ with pytest.raises(TimeoutException, match="request_timeout"):
+ await first_event(events, 0.3)
+ await events.aclose() # what the call sites do next; must be a no-op
+ server.assert_reset_sent()
diff --git a/packages/python-sdk/tests/test_envd_utils.py b/packages/python-sdk/tests/test_envd_utils.py
new file mode 100644
index 000000000..25ae0eb4b
--- /dev/null
+++ b/packages/python-sdk/tests/test_envd_utils.py
@@ -0,0 +1,15 @@
+from e2b.envd.utils import timeout_to_ms
+
+
+def test_timeout_to_ms():
+ assert timeout_to_ms(60) == 60_000
+ assert timeout_to_ms(0.5) == 500
+ assert timeout_to_ms(0.1) == 100
+ # A positive sub-millisecond timeout must stay a deadline — a 0 would be
+ # discarded by connectrpc's `timeout_ms or default` fallback, disabling
+ # the deadline entirely.
+ assert timeout_to_ms(0.0005) == 1
+ # Disabled timeouts must map to None — connectrpc treats a non-positive
+ # deadline as already expired.
+ assert timeout_to_ms(0) is None
+ assert timeout_to_ms(None) is None
diff --git a/packages/python-sdk/tests/test_filesystem_models.py b/packages/python-sdk/tests/test_filesystem_models.py
index 315d158c9..dd665bca5 100644
--- a/packages/python-sdk/tests/test_filesystem_models.py
+++ b/packages/python-sdk/tests/test_filesystem_models.py
@@ -1,6 +1,8 @@
import datetime
-from e2b.envd.filesystem import filesystem_pb2
+from protobuf.wkt import Timestamp
+
+from e2b.envd.filesystem import filesystem_pb
from e2b.sandbox.filesystem.filesystem import (
FileType,
WriteInfo,
@@ -40,9 +42,9 @@ def test_map_file_type_str():
def test_map_entry_info_modified_time_is_timezone_aware():
- entry = filesystem_pb2.EntryInfo(
+ entry = filesystem_pb.EntryInfo(
name="a.txt",
- type=filesystem_pb2.FileType.FILE_TYPE_FILE,
+ type=filesystem_pb.FileType.FILE,
path="/home/user/a.txt",
size=4,
mode=0o644,
@@ -50,7 +52,7 @@ def test_map_entry_info_modified_time_is_timezone_aware():
owner="user",
group="user",
)
- entry.modified_time.FromDatetime(
+ entry.modified_time = Timestamp.from_datetime(
datetime.datetime(2026, 1, 2, 3, 4, 5, tzinfo=datetime.timezone.utc)
)
diff --git a/packages/python-sdk/tests/test_logging_option.py b/packages/python-sdk/tests/test_logging_option.py
index dcc39d0ca..c10592075 100644
--- a/packages/python-sdk/tests/test_logging_option.py
+++ b/packages/python-sdk/tests/test_logging_option.py
@@ -1,8 +1,9 @@
import inspect
import logging
+from types import SimpleNamespace
-import e2b_connect as connect
from e2b import AsyncSandbox, ConnectionConfig, Sandbox
+from e2b.envd.interceptors import LoggingInterceptor, build_interceptors
from e2b.api import (
ApiClient,
make_async_logging_event_hooks,
@@ -86,36 +87,76 @@ def test_api_client_without_logger_emits_no_hooks():
client.get_httpx_client().close()
-def test_rpc_client_without_logger_does_not_log(caplog):
- client = connect.Client(url="https://example.com", response_type=object)
- assert client._logger is None
- # The guarded helpers must be safe no-ops when no logger was supplied.
- with caplog.at_level(logging.DEBUG):
- client._log_request()
- client._log_response(200)
- client._log_response(500)
- client._log_stream_message()
- assert caplog.records == []
+def test_rpc_client_without_logger_has_no_logging_interceptor(test_api_key):
+ # With no logger supplied, no logging interceptor is attached to RPC
+ # clients (matching the JS SDK, which only attaches its logging
+ # middleware when a logger is given).
+ config = ConnectionConfig(api_key=test_api_key)
+ interceptors = build_interceptors(config, "https://example.com")
+ assert not any(isinstance(i, LoggingInterceptor) for i in interceptors)
-def test_rpc_client_uses_provided_logger(caplog):
+def test_rpc_clients_get_logging_interceptor_from_config(test_api_key):
custom = logging.getLogger("test.rpc")
- client = connect.Client(
- url="https://example.com", response_type=object, logger=custom
+ config = ConnectionConfig(api_key=test_api_key, logger=custom)
+ interceptors = build_interceptors(config, "https://example.com")
+ logging_interceptors = [
+ i for i in interceptors if isinstance(i, LoggingInterceptor)
+ ]
+ assert len(logging_interceptors) == 1
+ assert logging_interceptors[0]._logger is custom
+
+
+def _fake_ctx():
+ return SimpleNamespace(
+ method=SimpleNamespace(service_name="process.Process", name="List")
)
- assert client._logger is custom
+
+
+def test_logging_interceptor_logs_unary_rpc(caplog):
+ custom = logging.getLogger("test.rpc")
+ interceptor = LoggingInterceptor(custom, "https://example.com")
+ ctx = _fake_ctx()
+
+ with caplog.at_level(logging.DEBUG, logger="test.rpc"):
+ result = interceptor.intercept_unary_sync(
+ lambda request, ctx: "response", "request", ctx
+ )
+ assert result == "response"
+
+ def fail(request, ctx):
+ raise RuntimeError("boom")
+
+ try:
+ interceptor.intercept_unary_sync(fail, "request", ctx)
+ except RuntimeError:
+ pass
+
+ levels = [(r.levelno, r.getMessage()) for r in caplog.records]
+ url = "https://example.com/process.Process/List"
+ assert (logging.INFO, f"Request: POST {url}") in levels
+ assert (logging.INFO, f"Response: ok {url}") in levels
+ assert (logging.ERROR, f"Response: boom {url}") in levels
+
+
+def test_logging_interceptor_logs_stream_messages(caplog):
+ custom = logging.getLogger("test.rpc")
+ interceptor = LoggingInterceptor(custom, "https://example.com")
+ ctx = _fake_ctx()
with caplog.at_level(logging.DEBUG, logger="test.rpc"):
- client._log_request()
- client._log_response(200)
- client._log_response(500)
- client._log_stream_message()
+ messages = list(
+ interceptor.intercept_server_stream_sync(
+ lambda request, ctx: iter(["a", "b"]), "request", ctx
+ )
+ )
+ assert messages == ["a", "b"]
levels = [(r.levelno, r.getMessage()) for r in caplog.records]
- assert (logging.INFO, "Request: POST https://example.com") in levels
- assert (logging.INFO, "Response: 200 https://example.com") in levels
- assert (logging.ERROR, "Response: 500 https://example.com") in levels
- assert (logging.DEBUG, "Response stream: https://example.com") in levels
+ url = "https://example.com/process.Process/List"
+ assert (logging.INFO, f"Request: POST {url}") in levels
+ assert levels.count((logging.DEBUG, f"Response stream: {url}")) == 2
+ assert (logging.INFO, f"Response: ok {url}") in levels
def test_logging_event_hooks_without_logger_are_empty():
diff --git a/packages/python-sdk/tests/test_watch_handle.py b/packages/python-sdk/tests/test_watch_handle.py
index 2e49f4854..4cdfeadee 100644
--- a/packages/python-sdk/tests/test_watch_handle.py
+++ b/packages/python-sdk/tests/test_watch_handle.py
@@ -1,9 +1,13 @@
import asyncio
+from typing import cast
from packaging.version import Version
from e2b.connection_config import ConnectionConfig
-from e2b.envd.filesystem import filesystem_pb2
+from protobuf import Oneof
+
+from e2b.envd.filesystem import filesystem_pb
+from e2b.envd.filesystem.filesystem_connect import FilesystemClientSync
from e2b.envd.versions import ENVD_DEFAULT_USER
from e2b.sandbox_async.filesystem.watch_handle import AsyncWatchHandle
from e2b.sandbox_sync.filesystem.watch_handle import WatchHandle
@@ -11,10 +15,12 @@ from e2b.sandbox_sync.filesystem.watch_handle import WatchHandle
def _fs_event(
name: str,
- event_type=filesystem_pb2.EventType.EVENT_TYPE_WRITE,
-) -> filesystem_pb2.WatchDirResponse:
- return filesystem_pb2.WatchDirResponse(
- filesystem=filesystem_pb2.FilesystemEvent(name=name, type=event_type)
+ event_type=filesystem_pb.EventType.WRITE,
+) -> filesystem_pb.WatchDirResponse:
+ return filesystem_pb.WatchDirResponse(
+ event=Oneof(
+ "filesystem", filesystem_pb.FilesystemEvent(name=name, type=event_type)
+ )
)
@@ -27,16 +33,16 @@ class _FakeSyncRpc:
def get_watcher_events(self, req, **opts):
self.calls.append(("get_watcher_events", req, opts))
- return filesystem_pb2.GetWatcherEventsResponse(events=[])
+ return filesystem_pb.GetWatcherEventsResponse(events=[])
def remove_watcher(self, req, **opts):
self.calls.append(("remove_watcher", req, opts))
- return filesystem_pb2.RemoveWatcherResponse()
+ return filesystem_pb.RemoveWatcherResponse()
def _make_sync_handle(rpc, envd_version: Version, user=None) -> WatchHandle:
return WatchHandle(
- get_rpc=lambda: rpc,
+ rpc=cast(FilesystemClientSync, rpc),
watcher_id="watcher-1",
connection_config=ConnectionConfig(),
envd_version=envd_version,
@@ -54,7 +60,7 @@ def test_sync_get_new_events_passes_request_timeout_and_auth_header():
name, _, opts = rpc.calls[0]
assert name == "get_watcher_events"
# A request timeout is always supplied so a stalled call can't hang forever.
- assert opts["request_timeout"] == 60.0
+ assert opts["timeout_ms"] == 60_000
assert opts["headers"].get("Authorization", "").startswith("Basic ")
@@ -66,7 +72,7 @@ def test_sync_stop_passes_request_timeout_and_auth_header():
name, _, opts = rpc.calls[0]
assert name == "remove_watcher"
- assert opts["request_timeout"] == 60.0
+ assert opts["timeout_ms"] == 60_000
assert opts["headers"].get("Authorization", "").startswith("Basic ")
@@ -77,8 +83,8 @@ def test_sync_caller_supplied_request_timeout_is_forwarded():
handle.get_new_events(request_timeout=5)
handle.stop(request_timeout=7)
- assert rpc.calls[0][2]["request_timeout"] == 5
- assert rpc.calls[1][2]["request_timeout"] == 7
+ assert rpc.calls[0][2]["timeout_ms"] == 5_000
+ assert rpc.calls[1][2]["timeout_ms"] == 7_000
# No explicit user on a recent envd → no auth header forced.
assert "Authorization" not in rpc.calls[0][2]["headers"]
diff --git a/packages/python-sdk/uv.lock b/packages/python-sdk/uv.lock
index 6f0d79c28..6ae1c30b7 100644
--- a/packages/python-sdk/uv.lock
+++ b/packages/python-sdk/uv.lock
@@ -13,25 +13,25 @@ wheels = [
[[package]]
name = "anyio"
-version = "4.14.1"
+version = "4.14.2"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "exceptiongroup", marker = "python_full_version < '3.11'" },
{ name = "idna" },
{ name = "typing-extensions", marker = "python_full_version < '3.13'" },
]
-sdist = { url = "https://files.pythonhosted.org/packages/3b/72/5562aabb8dd7181e8e860622a38bea08d17842b99ecd4c91f84ac95251b0/anyio-4.14.1.tar.gz", hash = "sha256:8d648a3544c1a700e3ff78615cd679e4c5c3f149904287e73687b2596963629e", size = 254831, upload-time = "2026-06-24T20:56:06.017Z" }
+sdist = { url = "https://files.pythonhosted.org/packages/61/cc/a381afa6efea9f496eff839d4a6a1aed3bfafc7b3ab4b0d1b243a12573dd/anyio-4.14.2.tar.gz", hash = "sha256:cfa139f3ed1a23ee8f88a145ddb5ac7605b8bbfd8592baacd7ce3d8bb4313c7f", size = 260176, upload-time = "2026-07-12T20:29:07.082Z" }
wheels = [
- { url = "https://files.pythonhosted.org/packages/b0/7b/90df4a0a816d98d6ea26f559d87836d494a2cf1fcf063be67df50a7bcc30/anyio-4.14.1-py3-none-any.whl", hash = "sha256:4e5533c5b8ff0a24f5d7a176cbe6877129cd183893f66b537f8f227d10527d72", size = 124875, upload-time = "2026-06-24T20:56:04.413Z" },
+ { url = "https://files.pythonhosted.org/packages/da/35/f2287558c17e29fafc8ef3daf819bb9834061cfa43bff8014f7df7f63bdc/anyio-4.14.2-py3-none-any.whl", hash = "sha256:9f505dda5ac9f0c8309b5e8bd445a8c2bf7246f3ce950121e45ea15bc41d1494", size = 125813, upload-time = "2026-07-12T20:29:05.763Z" },
]
[[package]]
name = "argcomplete"
-version = "3.6.3"
+version = "3.7.0"
source = { registry = "https://pypi.org/simple" }
-sdist = { url = "https://files.pythonhosted.org/packages/38/61/0b9ae6399dd4a58d8c1b1dc5a27d6f2808023d0b5dd3104bb99f45a33ff6/argcomplete-3.6.3.tar.gz", hash = "sha256:62e8ed4fd6a45864acc8235409461b72c9a28ee785a2011cc5eb78318786c89c", size = 73754, upload-time = "2025-10-20T03:33:34.741Z" }
+sdist = { url = "https://files.pythonhosted.org/packages/95/c0/c8e94135e66fabf89a120d9b4b123fe6993506beca6c1938a74c24cfa5fd/argcomplete-3.7.0.tar.gz", hash = "sha256:afde224f753f874807b1dc1414e883ab8fe0cda9c04807b6047dcb8e1ac23913", size = 73284, upload-time = "2026-06-30T22:28:22.249Z" }
wheels = [
- { url = "https://files.pythonhosted.org/packages/74/f5/9373290775639cb67a2fce7f629a1c240dce9f12fe927bc32b2736e16dfc/argcomplete-3.6.3-py3-none-any.whl", hash = "sha256:f5007b3a600ccac5d25bbce33089211dfd49eab4a7718da3f10e3082525a92ce", size = 43846, upload-time = "2025-10-20T03:33:33.021Z" },
+ { url = "https://files.pythonhosted.org/packages/12/f6/5b8ec087cd9cfa9449491ec83f76fb6b7006b4dff57d2ba8aaab330fe8e4/argcomplete-3.7.0-py3-none-any.whl", hash = "sha256:d8f0f22d2a8a7caa383be1e22b6caf1ecaf0ebd10d8f83cc125e36540c95830c", size = 42575, upload-time = "2026-06-30T22:28:20.547Z" },
]
[[package]]
@@ -135,6 +135,19 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6", size = 25335, upload-time = "2022-10-25T02:36:20.889Z" },
]
+[[package]]
+name = "connectrpc"
+version = "0.11.1"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "protobuf-py" },
+ { name = "pyqwest" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/8b/b5/63e14ab9d4d4cc58818562db4120a35fa7454e3035633da41bdc6b712abd/connectrpc-0.11.1.tar.gz", hash = "sha256:18277f7838847b4271ca38d40c7d2387b5a2ea6a29f240689c19e1ec84aaff66", size = 46222, upload-time = "2026-07-15T06:33:31.601Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/5c/ac/aa647675812cd075f2cb9acb00d62f4f2cbcbc6736049a62342b7371ce5b/connectrpc-0.11.1-py3-none-any.whl", hash = "sha256:8a52e2e92a485fa9681c1101a79a5ebeb31807e3ea3d5aabd41f484a6398bc7b", size = 64991, upload-time = "2026-07-15T06:33:29.396Z" },
+]
+
[[package]]
name = "datamodel-code-generator"
version = "0.34.0"
@@ -171,12 +184,13 @@ version = "2.34.0"
source = { editable = "." }
dependencies = [
{ name = "attrs" },
+ { name = "connectrpc" },
{ name = "dockerfile-parse" },
{ name = "h2" },
- { name = "httpcore" },
{ name = "httpx" },
{ name = "packaging" },
- { name = "protobuf" },
+ { name = "protobuf-py" },
+ { name = "pyqwest" },
{ name = "python-dateutil" },
{ name = "rich" },
{ name = "typing-extensions" },
@@ -188,6 +202,8 @@ codegen = [
{ name = "black" },
{ name = "datamodel-code-generator" },
{ name = "e2b-openapi-python-client" },
+ { name = "protoc-gen-connectrpc" },
+ { name = "protoc-gen-py" },
{ name = "pyyaml" },
]
dev = [
@@ -204,12 +220,13 @@ dev = [
[package.metadata]
requires-dist = [
{ name = "attrs", specifier = ">=23.2.0" },
+ { name = "connectrpc", specifier = ">=0.11.1,<0.12" },
{ name = "dockerfile-parse", specifier = ">=2.0.1,<3" },
{ name = "h2", specifier = ">=4,<5" },
- { name = "httpcore", specifier = ">=1.0.5,<2" },
{ name = "httpx", specifier = ">=0.27.0,<1.0.0" },
{ name = "packaging", specifier = ">=24.1" },
- { name = "protobuf", specifier = ">=4.21.0" },
+ { name = "protobuf-py", specifier = ">=0.1.1,<0.2" },
+ { name = "pyqwest", specifier = ">=0.7.0,<0.8" },
{ name = "python-dateutil", specifier = ">=2.8.2" },
{ name = "rich", specifier = ">=14.0.0" },
{ name = "typing-extensions", specifier = ">=4.1.0" },
@@ -221,6 +238,8 @@ codegen = [
{ name = "black", specifier = "==26.3.1" },
{ name = "datamodel-code-generator", specifier = "==0.34.0" },
{ name = "e2b-openapi-python-client", specifier = "==0.26.2" },
+ { name = "protoc-gen-connectrpc", specifier = "==0.11.1" },
+ { name = "protoc-gen-py", specifier = "==0.1.1" },
{ name = "pyyaml", specifier = "==6.0.2" },
]
dev = [
@@ -279,11 +298,11 @@ wheels = [
[[package]]
name = "genson"
-version = "1.3.0"
+version = "1.4.0"
source = { registry = "https://pypi.org/simple" }
-sdist = { url = "https://files.pythonhosted.org/packages/c5/cf/2303c8ad276dcf5ee2ad6cf69c4338fd86ef0f471a5207b069adf7a393cf/genson-1.3.0.tar.gz", hash = "sha256:e02db9ac2e3fd29e65b5286f7135762e2cd8a986537c075b06fc5f1517308e37", size = 34919, upload-time = "2024-05-15T22:08:49.123Z" }
+sdist = { url = "https://files.pythonhosted.org/packages/f8/53/de162dc8e03fccd9ebe59d17c7812378fe8bd2b604f6b1b94d00165140ac/genson-1.4.0.tar.gz", hash = "sha256:bc7f1c1bae87a21ca44d81149aec95a3f4468d676de9b8b08caa064f3c50b3da", size = 47908, upload-time = "2026-07-06T08:21:50.331Z" }
wheels = [
- { url = "https://files.pythonhosted.org/packages/f8/5c/e226de133afd8bb267ec27eead9ae3d784b95b39a287ed404caab39a5f50/genson-1.3.0-py3-none-any.whl", hash = "sha256:468feccd00274cc7e4c09e84b08704270ba8d95232aa280f65b986139cec67f7", size = 21470, upload-time = "2024-05-15T22:08:47.056Z" },
+ { url = "https://files.pythonhosted.org/packages/16/02/767f744ab6d4cb7761e5008acc3d534b7a0481af62563d52e391fbcb2140/genson-1.4.0-py3-none-any.whl", hash = "sha256:03bc71bbe52defde70660cc4dcd1ea1097997da5a1cbb90a9dbd3acc7c9e1b65", size = 24484, upload-time = "2026-07-06T08:21:49.046Z" },
]
[[package]]
@@ -530,6 +549,18 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/79/7b/2c79738432f5c924bef5071f933bcc9efd0473bac3b4aa584a6f7c1c8df8/mypy_extensions-1.1.0-py3-none-any.whl", hash = "sha256:1be4cccdb0f2482337c4743e60421de3a356cd97508abadd57d47403e94f5505", size = 4963, upload-time = "2025-04-22T14:54:22.983Z" },
]
+[[package]]
+name = "opentelemetry-api"
+version = "1.44.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "typing-extensions" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/ee/8b/aa9e2d8b8dfa7c946f7dec5d1f8f6ba8eca062f43509a06bdb5ce93d26c0/opentelemetry_api-1.44.0.tar.gz", hash = "sha256:67647e5e9566edcf421166fdf022b3537f818635daa852b289e34604dc6fb33a", size = 72406, upload-time = "2026-07-16T15:25:32.678Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/ca/6f/a04e900f465ff3221ccc395522503e2d10e79fa21f2723c8e177aae1e0d1/opentelemetry_api-1.44.0-py3-none-any.whl", hash = "sha256:94b98c893a91b88657eaac1e3ba89618cdb85be6918196705354f34728b2cdef", size = 60018, upload-time = "2026-07-16T15:25:11.657Z" },
+]
+
[[package]]
name = "packaging"
version = "26.2"
@@ -567,18 +598,74 @@ wheels = [
]
[[package]]
-name = "protobuf"
-version = "7.35.1"
+name = "protobuf-py"
+version = "0.1.1"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "protobuf-py-ext", marker = "(platform_machine == 'arm64' and platform_python_implementation == 'CPython' and sys_platform == 'darwin') or (platform_machine == 'aarch64' and platform_python_implementation == 'CPython' and sys_platform == 'linux') or (platform_machine == 'x86_64' and platform_python_implementation == 'CPython' and sys_platform == 'linux') or (platform_machine == 'AMD64' and platform_python_implementation == 'CPython' and sys_platform == 'win32') or (platform_machine == 'ARM64' and platform_python_implementation == 'CPython' and sys_platform == 'win32')" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/72/ed/02fd902d9c51b7ff53dfc9a745eb11490722edfd30073af889e171f07b8e/protobuf_py-0.1.1.tar.gz", hash = "sha256:6bd08ac4d8f1661965bbe2685429d79043704cdd1ee720a7a89617331742240b", size = 133525, upload-time = "2026-06-24T19:02:15.271Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/fd/00/1b3775aca1c70e3007e06ef5996f6bb9b3a32341eb0cce3ffb6effad8dec/protobuf_py-0.1.1-py3-none-any.whl", hash = "sha256:efc4f50f275ed6dae10a1f30bb81ad1a75368557b3ff22a532b7a472050368f1", size = 181656, upload-time = "2026-06-24T19:01:29.556Z" },
+]
+
+[[package]]
+name = "protobuf-py-ext"
+version = "0.1.1"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/2f/05/6dc9ccff1e8159eb9a144e6d3c4acfd2211cd4fcd20c34fe9155d17d6a7f/protobuf_py_ext-0.1.1.tar.gz", hash = "sha256:e85bfdfdb3ed50634db8ccc7429dd9286520109489c735463971a418707b4fef", size = 31912, upload-time = "2026-06-24T19:02:16.321Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/19/70/2b5d62a60a2e0d88ecde1ae98db3132bcd2672fb39c8d581b82b34ac0bd8/protobuf_py_ext-0.1.1-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:310039e03cb15181781a0b78017419f6d4ee302e988c3c70b87f1facdf05532d", size = 306008, upload-time = "2026-06-24T19:01:31.399Z" },
+ { url = "https://files.pythonhosted.org/packages/2d/d6/73c06bb4cac2e04c0adc154965fe8b6520224bd737fd7e73bba405056321/protobuf_py_ext-0.1.1-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:89ec8348d1ba045f79b2fedd14e40cca36f2a41b52f2c4fdf55a60c58add2353", size = 314769, upload-time = "2026-06-24T19:01:32.89Z" },
+ { url = "https://files.pythonhosted.org/packages/18/c5/e4e6bc6096b66d1c82639a1b501147f16ee65d32567304b987d002e2c666/protobuf_py_ext-0.1.1-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:182798e4861aba72d05855bd06febe4926aa7265e6f444a1b8af5252beee4f7e", size = 328122, upload-time = "2026-06-24T19:01:34.394Z" },
+ { url = "https://files.pythonhosted.org/packages/b0/4b/1d792a40d0f0a0f914f1dfa8bb5e9573ca0ecd5fe5cecf80d77193212abd/protobuf_py_ext-0.1.1-cp310-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:9eb25c3a329c0551cc86b209a5e5d8ecb8d834b9924a3aa019377853a703b6d3", size = 492338, upload-time = "2026-06-24T19:01:36.103Z" },
+ { url = "https://files.pythonhosted.org/packages/52/51/5ad329223c905e5c530cae38ae24cde3584d8ab7e09457f2a01afce80e60/protobuf_py_ext-0.1.1-cp310-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:aaecbde82bef10c7c40578cbb61b7a19896bf7fa450972050a3bb302acb7d5d6", size = 541578, upload-time = "2026-06-24T19:01:37.481Z" },
+ { url = "https://files.pythonhosted.org/packages/ed/c7/01bd8a8bfe2df4b07aafac12ccfb7b7ebe2303f65296a9e02fcafa28ff3e/protobuf_py_ext-0.1.1-cp310-abi3-win_amd64.whl", hash = "sha256:6b0c615c48e95acc53cf33e9310eeaff8b30d2d7555bf93e7bca8fb4f40e9a5c", size = 251319, upload-time = "2026-06-24T19:01:38.946Z" },
+ { url = "https://files.pythonhosted.org/packages/24/dc/914065538b5db54b6a920b5af38c1ef142252ea1eea711820435fa259fac/protobuf_py_ext-0.1.1-cp310-abi3-win_arm64.whl", hash = "sha256:72956cd0af5dee24b41c6f5ba5e42622d17e6d555002b5efc1634e27a1446de2", size = 241635, upload-time = "2026-06-24T19:01:40.301Z" },
+ { url = "https://files.pythonhosted.org/packages/13/a5/0b5d73cab815fd50615cb87a02e04e8332f9e27380c890aba1459cf7e919/protobuf_py_ext-0.1.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:c6f0cd58620f415a3534d195358338f4999a774e12510f91c592b38d13d37388", size = 304903, upload-time = "2026-06-24T19:01:41.796Z" },
+ { url = "https://files.pythonhosted.org/packages/37/a9/14c120b9ac36a0e11bb05e482fa6ae322de583a8e1068e4859035c289947/protobuf_py_ext-0.1.1-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:21572764f625d829604fc4d83635f533f35775f11c6da142345b3f3c8d64bd09", size = 316148, upload-time = "2026-06-24T19:01:43.247Z" },
+ { url = "https://files.pythonhosted.org/packages/35/54/7c00a1a9783c3ba74f6b2f5d2f049f09037bbd489c465c09a34f32fb611b/protobuf_py_ext-0.1.1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:e7f14f00c2678bfbe7ad46f057b9f9938c1677bcf39e405e163e272c6f9814b8", size = 326458, upload-time = "2026-06-24T19:01:44.655Z" },
+ { url = "https://files.pythonhosted.org/packages/0d/0e/81fa50c0d6c4d664e5be6d0a3c4f2c7edfef87ab12d0bac764abca1f2955/protobuf_py_ext-0.1.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:1610865622e2e27568277ca63d8d2d23dcc55eaa767398865c21539ddf4ce24d", size = 493596, upload-time = "2026-06-24T19:01:46.344Z" },
+ { url = "https://files.pythonhosted.org/packages/56/19/3183cf6e4de62846c20549654a1d573dae51ca06aaf7fed06accdfab74f6/protobuf_py_ext-0.1.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:8995efba9476e1ea18ef9873306871dba697308994bc2766558fec3387acc3de", size = 539656, upload-time = "2026-06-24T19:01:48.21Z" },
+ { url = "https://files.pythonhosted.org/packages/a4/6c/09841f3dbe7c3d4b3f2779f8f2832ac23fb96ac8ab71674e91af732cf9ff/protobuf_py_ext-0.1.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:ba61d49dace8f874361583030a7c48139b42eb37c9ffbb1e7e8a227a51576f44", size = 305017, upload-time = "2026-06-24T19:01:49.84Z" },
+ { url = "https://files.pythonhosted.org/packages/52/43/e450b5e202f6715274acc9acd9f9769908cbdeab861a53c798fcbd467d35/protobuf_py_ext-0.1.1-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:9a9c2f026096ca4c595c89a297067ef371e241d3ff8e1f6d7c779aa8419cdca7", size = 316215, upload-time = "2026-06-24T19:01:51.249Z" },
+ { url = "https://files.pythonhosted.org/packages/97/5c/23e79b35f1b5755b9bdc0c0c9b8cd8abababaef1a1639608d8a96bb61a9d/protobuf_py_ext-0.1.1-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:cf78707a040b9294e5e1ec4a1875f0046acfe52e92150cea27de4e9fc9db39bb", size = 326419, upload-time = "2026-06-24T19:01:52.93Z" },
+ { url = "https://files.pythonhosted.org/packages/e8/de/5493de0ec12920a3b1dd72608ce0c1e8cdb7e0eb9e87accaecc5216df29e/protobuf_py_ext-0.1.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:ae4373845cbb85bdade3ef5368cc2f4b5f80bf173383afc1ab063f95644e5599", size = 493734, upload-time = "2026-06-24T19:01:54.301Z" },
+ { url = "https://files.pythonhosted.org/packages/98/89/31da55b414e6332aad11d858e9a86bd36fbb324f52fa3fc6d8f1c57840a9/protobuf_py_ext-0.1.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:2a4cc478eef7a2acc1daaebcde479a3ac2396d47e6bdc7e776ca4c4147ba8b4c", size = 539703, upload-time = "2026-06-24T19:01:55.707Z" },
+ { url = "https://files.pythonhosted.org/packages/1c/71/39f231838ef06476d46ac40dd814894277a732a3688c0a0c994850b3b62f/protobuf_py_ext-0.1.1-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:359dccdc1c3eafed2a913c570bb082b8df848a1d27d548ce8385f246a7d68be2", size = 302145, upload-time = "2026-06-24T19:01:57.116Z" },
+ { url = "https://files.pythonhosted.org/packages/87/f1/01c81ff5f420600366a0e6a613ce2af20834534d2b3d7523f4f3b4ddb54f/protobuf_py_ext-0.1.1-cp314-cp314-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:91c38b4a10a306366443273ee03ca554537a0965bf05b7ada8e7dbdee04cc93e", size = 314541, upload-time = "2026-06-24T19:01:58.745Z" },
+ { url = "https://files.pythonhosted.org/packages/86/d8/1cbf5a0298ceddc0cdbb28bf1ecaf8bd3cff54ed4ced6a1392d5226172fc/protobuf_py_ext-0.1.1-cp314-cp314-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:79eee3bcbb289d6ea114eb8fe3a1469c5b59bf53e207238469f567d9c53ba56f", size = 325092, upload-time = "2026-06-24T19:02:00.382Z" },
+ { url = "https://files.pythonhosted.org/packages/af/23/8b1694616044cbfec2d18d4c6fffb03e05089c8bdb5970c6bafd60cc7fd5/protobuf_py_ext-0.1.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:10992141a8282a71ac3e3530d1a489efb27618d84000b9a47918cf70e5816d9b", size = 491684, upload-time = "2026-06-24T19:02:01.862Z" },
+ { url = "https://files.pythonhosted.org/packages/49/d8/99997a7a6cf6989c944d9183c5deb6a045c27460add0316c7b34763891b3/protobuf_py_ext-0.1.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:4411ffe0e06a774b83c5c71c546ce097640a25f596c45f95f53d3e3148e3f22d", size = 538048, upload-time = "2026-06-24T19:02:03.362Z" },
+ { url = "https://files.pythonhosted.org/packages/15/3c/9e99ecbb68e1d5b46016d821eb1cbba9a91e6b50e71e75faf0c1e6189f0d/protobuf_py_ext-0.1.1-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:55a17d80ea419501ff221a6627523f38a431bb33e6aa3de81ae3a7f271c49c75", size = 296337, upload-time = "2026-06-24T19:02:04.787Z" },
+ { url = "https://files.pythonhosted.org/packages/af/f2/305338a28225fb54b28d6c3f5948109b9088b329a2b6f77ca610c2bdcd34/protobuf_py_ext-0.1.1-cp314-cp314t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:9dbb518b5638403ceaa08ac4fc7dac626f45ed9b856b3517de3906cf3de4d632", size = 308961, upload-time = "2026-06-24T19:02:06.185Z" },
+ { url = "https://files.pythonhosted.org/packages/60/f9/416103c93677ff2ea407704ea64fa6de9e700dc030c48360a182d91ce373/protobuf_py_ext-0.1.1-cp314-cp314t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8a4adc65ab6a5e4885c67fc808bcacb83d755d05b566d312a0e10c2a873f2ad4", size = 321895, upload-time = "2026-06-24T19:02:07.714Z" },
+ { url = "https://files.pythonhosted.org/packages/5a/83/eb3e81bb2f83834b7deff4cee2d56eeb1adcbc847492a56b7f910ab257db/protobuf_py_ext-0.1.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:e97f45c49676efacfb8e95bfcb1a002bc337e618a6780be1e55df2ba5ebd2f1e", size = 486091, upload-time = "2026-06-24T19:02:09.243Z" },
+ { url = "https://files.pythonhosted.org/packages/99/96/bd88fca38556b3105e4dd41d6a176e31dcc583fe979e830aeedd2f8c20ee/protobuf_py_ext-0.1.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:53a6b3590f6aa7f97b8ed60f62fef9b096babfeae82f7283fd3a4c405827d4f8", size = 534582, upload-time = "2026-06-24T19:02:11.227Z" },
+]
+
+[[package]]
+name = "protoc-gen-connectrpc"
+version = "0.11.1"
source = { registry = "https://pypi.org/simple" }
-sdist = { url = "https://files.pythonhosted.org/packages/da/01/9ef0afd7999eb9badb3a768b4aedd78c86d4c65cfaf1958ab276199e76b4/protobuf-7.35.1.tar.gz", hash = "sha256:ce115a26fe0c39a2c29973d914d327e516a6455464489fe3cd1e51a1b354f81a", size = 458717, upload-time = "2026-06-11T21:55:40.257Z" }
+dependencies = [
+ { name = "protobuf-py" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/da/24/4a1f13797a3c0c5b179e4f70e8907a303c28376d3ba88ca095e4d58b750f/protoc_gen_connectrpc-0.11.1.tar.gz", hash = "sha256:99a482ca7c35fd755ee6157a4e0eb09171481b06257144dad4503b83b4ac85a3", size = 9418, upload-time = "2026-07-15T06:33:32.452Z" }
wheels = [
- { url = "https://files.pythonhosted.org/packages/10/03/8aeeb7458d22546bf64b5250ca1daeb5ff757d900e8e4a7476c6f0db843e/protobuf-7.35.1-cp310-abi3-macosx_10_9_universal2.whl", hash = "sha256:24f857477359a85c0c235261b8ba905fd51b2562f4a64ca1df5473f29850cbf6", size = 433226, upload-time = "2026-06-11T21:55:31.719Z" },
- { url = "https://files.pythonhosted.org/packages/37/4b/dfb89eb0e652a1ff073c39a59fb5e3a83cfe9b57a2c83fa6d78270101767/protobuf-7.35.1-cp310-abi3-manylinux2014_aarch64.whl", hash = "sha256:11d6b0ec246892d85215b0a13ca6e0233cf5284b68f0ac02646427f4ff88a799", size = 328847, upload-time = "2026-06-11T21:55:34.035Z" },
- { url = "https://files.pythonhosted.org/packages/0f/58/dc12f2cd484951524af6e3382c785869b9b3fb5e52ee95ae23add53ee8f9/protobuf-7.35.1-cp310-abi3-manylinux2014_s390x.whl", hash = "sha256:b73f9489a4b8b1c9cb1f8ed951c736392592edb24b9d6819f36d2e10b171d5b4", size = 344030, upload-time = "2026-06-11T21:55:34.941Z" },
- { url = "https://files.pythonhosted.org/packages/e4/be/5b3cfe508bfab6761414ff944e3366eb13be4fd71efcd69450f89ba39f43/protobuf-7.35.1-cp310-abi3-manylinux2014_x86_64.whl", hash = "sha256:74758715c53d7158fb76caf4f0cfdacc5329a4b1bb994f865d6cf302d413a1c4", size = 327130, upload-time = "2026-06-11T21:55:35.921Z" },
- { url = "https://files.pythonhosted.org/packages/d8/bc/6d6c7ba8709c85f8f2c390b2b118d6fb08a783676a572271851bf45a7d22/protobuf-7.35.1-cp310-abi3-win32.whl", hash = "sha256:353652e4efd0bca5b5fc2656abf8307ef351f0cf938c9eba09f0e09c20a25c30", size = 428945, upload-time = "2026-06-11T21:55:37.034Z" },
- { url = "https://files.pythonhosted.org/packages/0a/19/8d0cb6f20a1ef7b18f1c8986ad5783f22f84cce39c6ce9a6e645ea55192e/protobuf-7.35.1-cp310-abi3-win_amd64.whl", hash = "sha256:230a75ddfc2de4806e56696ce9640c1cdfdb6543b7cfce98d42a4c0a0e7bdb87", size = 439996, upload-time = "2026-06-11T21:55:38.123Z" },
- { url = "https://files.pythonhosted.org/packages/19/c7/5f7c636ec43e0c545e28d1f1db71990108306f7bdcb89f069ba97e428e7f/protobuf-7.35.1-py3-none-any.whl", hash = "sha256:4bc97768d8fe4ad6743c8a19403e314511ed9f6d13205b687e52421c023ac1b9", size = 171659, upload-time = "2026-06-11T21:55:39.155Z" },
+ { url = "https://files.pythonhosted.org/packages/12/cf/3c6ba9d5b3153e58338c3768eba3637e531e80349e5553f871c9e2ce2643/protoc_gen_connectrpc-0.11.1-py3-none-any.whl", hash = "sha256:a68441702aab8664d1bef3666173dbd1e7717fc27a04fda65c0a9f24ba27dcde", size = 10524, upload-time = "2026-07-15T06:33:30.559Z" },
+]
+
+[[package]]
+name = "protoc-gen-py"
+version = "0.1.1"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "protobuf-py" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/b1/d4/ff2a8219fc7caa8991c64a81ed3ae8cb5aabcf9186bce1955c07d9d5b6b3/protoc_gen_py-0.1.1.tar.gz", hash = "sha256:b67101c6b0493e4deb9eaa47731441eabaac29e4d1248a7b8d0e4b5b098539b3", size = 11012, upload-time = "2026-06-24T19:02:18.062Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/fe/64/1496fa3df28d7100d4c33f9588930cda1dc5c2652031df4f4f433c1558ef/protoc_gen_py-0.1.1-py3-none-any.whl", hash = "sha256:5594044938e1ee8881fce931e9b703fe556f518de6775e4a98d8a50d147a76cc", size = 12551, upload-time = "2026-06-24T19:02:14.077Z" },
]
[[package]]
@@ -721,6 +808,59 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/f4/7e/a72dd26f3b0f4f2bf1dd8923c85f7ceb43172af56d63c7383eb62b332364/pygments-2.20.0-py3-none-any.whl", hash = "sha256:81a9e26dd42fd28a23a2d169d86d7ac03b46e2f8b59ed4698fb4785f946d0176", size = 1231151, upload-time = "2026-03-29T13:29:30.038Z" },
]
+[[package]]
+name = "pyqwest"
+version = "0.7.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "opentelemetry-api" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/01/05/8576f0eeb44d3fe14c70e2bafa77ae6930c5e6f42b93c568719ea4456715/pyqwest-0.7.0.tar.gz", hash = "sha256:ac65f2243f3e814e7f4aad3f2fcfe78f89aad2de2a825eaaabf4c102f1937843", size = 457991, upload-time = "2026-07-19T05:20:06.61Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/86/49/7f26a2c2a3e8bbab4862bcbf4f54b706d9524fa9705cc0127553b81ed161/pyqwest-0.7.0-cp310-abi3-macosx_10_12_x86_64.whl", hash = "sha256:7b2339f3b55ae179e0cb55bbd5792ae1c954d31f80de7b4dde0e95b03576b6be", size = 5159904, upload-time = "2026-07-19T05:18:57.757Z" },
+ { url = "https://files.pythonhosted.org/packages/20/f1/4aba1976566936ca873e1a726a0d9bdf8195a0dc4e4f78122f6050328566/pyqwest-0.7.0-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:2159c7e2eaf2563cdadfda17314e2b1747c30603979bf73db8daef311247db82", size = 5044476, upload-time = "2026-07-19T05:18:59.473Z" },
+ { url = "https://files.pythonhosted.org/packages/fe/06/45908e5cda7fa28ba60df5ed2091056893c394c3217a796bc6577c4bd294/pyqwest-0.7.0-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:0a826f1b492a7497f469c8467bd51faf582733654bb2bc9fcdd4fa502f3e6ca1", size = 5560021, upload-time = "2026-07-19T05:19:01.097Z" },
+ { url = "https://files.pythonhosted.org/packages/f2/3d/603f5c9446e8c13a4970b816246d7928e895408a7ed1778d98de3e25ea43/pyqwest-0.7.0-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:da43c7e86bee9e74ff474d4829cd398fb9220ff0d84d633094ea6797fdfe03a1", size = 5506130, upload-time = "2026-07-19T05:19:02.812Z" },
+ { url = "https://files.pythonhosted.org/packages/33/6d/2984aa02f4d0296dddb5df159e1af6c6e0ddc0b507d592f13d6ccd0b3162/pyqwest-0.7.0-cp310-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:d1c71327c323a19dc90a0dafb1d68fb13f4f775a2498a26bf95f17165e64da9f", size = 5719961, upload-time = "2026-07-19T05:19:04.213Z" },
+ { url = "https://files.pythonhosted.org/packages/19/06/e30c0d31eea17cabf99ef90c7c02e14cc94ca7d59793d397de9359148693/pyqwest-0.7.0-cp310-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:c002e0fc31a96f1c47986299710f49ed4551e4a912a7cdb69aba6fd94db6d544", size = 5908279, upload-time = "2026-07-19T05:19:05.595Z" },
+ { url = "https://files.pythonhosted.org/packages/eb/db/a1368faae1cbd094a0d179b76de69b8d1908bd45898d3bcd29ac98622072/pyqwest-0.7.0-cp310-abi3-win_amd64.whl", hash = "sha256:847e4468b5379a219b91a13dd3c92dd3b7b3d9f59af23e4c6776e663594cb241", size = 4755104, upload-time = "2026-07-19T05:19:07.772Z" },
+ { url = "https://files.pythonhosted.org/packages/b3/38/c493e85ebd17d3a5c56eb53fbea36a1a6f396b999b38173ffde513576eb1/pyqwest-0.7.0-cp312-cp312-macosx_10_12_x86_64.whl", hash = "sha256:4988fa1c368072886dce48f52fcbabe9f25784c6e189a9a6f2b42f6e9f383973", size = 5172962, upload-time = "2026-07-19T05:19:09.229Z" },
+ { url = "https://files.pythonhosted.org/packages/d6/68/1b340fdc7735b5682d308cabc2d65ea76c03a6cc2c30072a0c14c24f716c/pyqwest-0.7.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:dfb61138c802c7317d840a274fa24f9d878301f693268e9186a9896452017a71", size = 5032604, upload-time = "2026-07-19T05:19:10.884Z" },
+ { url = "https://files.pythonhosted.org/packages/4d/52/eecd858568ef6586cbdc3c419a9a0b1e8f891e2968f0f6b2a9fa9bdaac19/pyqwest-0.7.0-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f6fdc0601590bdc547007828627082f0dc0e445e92d900dccb227e51898d7243", size = 5558302, upload-time = "2026-07-19T05:19:12.348Z" },
+ { url = "https://files.pythonhosted.org/packages/c0/8f/b67d0056b18a9f99a1c9253cb983d5c4361e3e102d729df6623b71d6d939/pyqwest-0.7.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:0f82c971810695f5fd7962859a2469616c83b7aca6664d8f147287ee5ff430cd", size = 5501483, upload-time = "2026-07-19T05:19:13.892Z" },
+ { url = "https://files.pythonhosted.org/packages/c0/a6/69b87c4c80ced01645a143679458895dcb5c0e5ca0b3d4a43d979939cce6/pyqwest-0.7.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:9dc2f405803b94525ab030c01cdac7093bcc1a5da6802de3345a868a0f51b3da", size = 5717334, upload-time = "2026-07-19T05:19:15.541Z" },
+ { url = "https://files.pythonhosted.org/packages/26/7b/5891b72b9193b692b50ecdc4e26e7e3687f9763f5f263646bc8f997f5b62/pyqwest-0.7.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:537f71f97a533fa355d02c15ed9f0cc05fb8915996cb921caa87fe7310b457ee", size = 5902447, upload-time = "2026-07-19T05:19:17.273Z" },
+ { url = "https://files.pythonhosted.org/packages/6a/80/1b280618af3f9d36081449d153efc5620f0eea93ac169574fc69208d2b91/pyqwest-0.7.0-cp312-cp312-win_amd64.whl", hash = "sha256:196aa73fb7eee4b6c052d6f4172a4321904a7208331f4322ccee3ee7d0adbc78", size = 4750469, upload-time = "2026-07-19T05:19:18.916Z" },
+ { url = "https://files.pythonhosted.org/packages/c1/9c/64c8df83a152804ac3074fb879c1229c3aca55a12dc33dc73c72e93405e6/pyqwest-0.7.0-cp313-cp313-macosx_10_12_x86_64.whl", hash = "sha256:72d001892ed570df1dcc489ef8b0a03bc7abd4fbdca10625c358a87e66b226ad", size = 5171308, upload-time = "2026-07-19T05:19:20.332Z" },
+ { url = "https://files.pythonhosted.org/packages/14/d1/46e629541a3f7231dd978fa9939e6ddcd075238880395bcfb16544769165/pyqwest-0.7.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:03da0797bac5c2eb1a40f02afccd4b5aad5ad0d375bb993df2f5e0c692fc0c6c", size = 5032449, upload-time = "2026-07-19T05:19:21.967Z" },
+ { url = "https://files.pythonhosted.org/packages/44/3c/132194c747696e41ad5745c51587bd20057d800b6a64fb901ce2ac990149/pyqwest-0.7.0-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:837e18aef4490eed25b4194d49f16732ccf1abf2cdd0845e75d75d2a4428b98c", size = 5556847, upload-time = "2026-07-19T05:19:23.589Z" },
+ { url = "https://files.pythonhosted.org/packages/e6/5d/6726a70e89c60bf3cd30d5d918eff68dc1d1ceb9c911331d7fb57977bfc3/pyqwest-0.7.0-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:418e8c3a67ca6226bfb6147b8668203c74d9c872657117086f4c264a674d7980", size = 5500333, upload-time = "2026-07-19T05:19:25.317Z" },
+ { url = "https://files.pythonhosted.org/packages/49/3f/329df64d3e8778bc311a22e432280cd317619c3f9b7e414f375127bb90b0/pyqwest-0.7.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:31176abbbcbe6d03740967b5c0241deaa60b328792644cb2e317a34d6b076433", size = 5717248, upload-time = "2026-07-19T05:19:26.963Z" },
+ { url = "https://files.pythonhosted.org/packages/2e/93/6670afb97c6ce7b5ba27981e023d9edc7413e509bbe18afebb729834d9e6/pyqwest-0.7.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:e21102f9c13234a0066d42bb5429dc5c311d7fd99401878837d9675a7f6e03b9", size = 5902814, upload-time = "2026-07-19T05:19:28.637Z" },
+ { url = "https://files.pythonhosted.org/packages/51/d3/bf9440a03c97f408743313215d8c7e9875b0b2b0d2ef97f5fbb5066cd57d/pyqwest-0.7.0-cp313-cp313-win_amd64.whl", hash = "sha256:ca19e96b5e902a6d35e18cee7f5e90612fca6ab169378d42242cdcb638578cee", size = 4750510, upload-time = "2026-07-19T05:19:30.587Z" },
+ { url = "https://files.pythonhosted.org/packages/dc/25/8b0919bf504309982857e564e3035ffd799d7aaa23457eb351485573e5ee/pyqwest-0.7.0-cp314-cp314-macosx_10_12_x86_64.whl", hash = "sha256:4e4e79187c3e4ebd07d663d8dc7a7cba865c72020332e41807426a7e3526fda0", size = 5177972, upload-time = "2026-07-19T05:19:32.051Z" },
+ { url = "https://files.pythonhosted.org/packages/52/12/d652213fe336c52b75fb4df710f5cff08f8a1dcc9e385c9120f18476f5c9/pyqwest-0.7.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:1bc2c569481ade1bc0b89b07daf1b49b20a1337a53207ffe0ef325260f509404", size = 5032608, upload-time = "2026-07-19T05:19:33.772Z" },
+ { url = "https://files.pythonhosted.org/packages/82/b0/406c91563140b87ade5c5935410997b26449b8eb2f91511bc52741ae38fb/pyqwest-0.7.0-cp314-cp314-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:5ef1bfbdca9ec9c8a7b223268f5ef8d45694da7226929454b0cb40f2e3d1ddd5", size = 5558937, upload-time = "2026-07-19T05:19:35.174Z" },
+ { url = "https://files.pythonhosted.org/packages/7f/17/a0a09936b5dd5d9d7517289aee3683bbf6554b0853bce5280ead9da27336/pyqwest-0.7.0-cp314-cp314-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:e4c2f6a6830becfa1c5bb94aa169ad854da5749a95a440aee759932d5965c213", size = 5500603, upload-time = "2026-07-19T05:19:37.023Z" },
+ { url = "https://files.pythonhosted.org/packages/00/34/ccec52ca9f14fbe11292fadbe89c771353e0f46d58aa88d8e93d6e018117/pyqwest-0.7.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:0d11128ccc382f64fcdf92d3bce6be7191489c1b3a9a3f0dbdf89e55451638de", size = 5719784, upload-time = "2026-07-19T05:19:38.649Z" },
+ { url = "https://files.pythonhosted.org/packages/16/cc/58dca466c236e497cbb2e75b97a2489225d21f5063d932ab7d1723294112/pyqwest-0.7.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:5832373c7bcccfbc3bb79c44b592e0871631139a2ef5aef771b8fe2b7bd4301d", size = 5901396, upload-time = "2026-07-19T05:19:40.402Z" },
+ { url = "https://files.pythonhosted.org/packages/06/a0/983ea3b859828bef8372896e9c407f62bf426b84526d0b0cf9fd9abce411/pyqwest-0.7.0-cp314-cp314-win_amd64.whl", hash = "sha256:7330070c4497e564007985716ac347cb9a7500eba5c9610500653a2ce4cfe86e", size = 4751036, upload-time = "2026-07-19T05:19:42.159Z" },
+ { url = "https://files.pythonhosted.org/packages/92/1d/e2fe3dfe6d87989017412f394abc45435a3af2526e998c83cf836937b23c/pyqwest-0.7.0-cp314-cp314t-macosx_10_12_x86_64.whl", hash = "sha256:02fd606a35be7803a770071f642a375e55df4c2025e49b10b859430f424c4492", size = 5165801, upload-time = "2026-07-19T05:19:43.82Z" },
+ { url = "https://files.pythonhosted.org/packages/f4/fe/90126ac71fe09c729f36c166cb71b5148dd8a80e47f6f232bf71494604a2/pyqwest-0.7.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:a807835c6a0777f0cc57c321c78c7bf162f6354698844d78db6e03ba9edd83dc", size = 5025128, upload-time = "2026-07-19T05:19:45.391Z" },
+ { url = "https://files.pythonhosted.org/packages/e5/15/ee84ce834705d613c0b113fb4cf9d274011cfcc6c6ededb52d92a38a2367/pyqwest-0.7.0-cp314-cp314t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:86d84871cb0a572700dece3a6c45c294721f655f3d0b85477333209b487ecef1", size = 5551017, upload-time = "2026-07-19T05:19:47.046Z" },
+ { url = "https://files.pythonhosted.org/packages/41/ad/18b4540fb276f9b540018efe024aca0801acfe4209417d4faed85bccdb04/pyqwest-0.7.0-cp314-cp314t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:005ddd2a777d30ca7ce4de12df1336760e14d46394ab56299a9e81626d78b991", size = 5493032, upload-time = "2026-07-19T05:19:49.038Z" },
+ { url = "https://files.pythonhosted.org/packages/6c/91/f25477eb80c375378a876cf2bac80c55ec9ea36b94bd7d4b2b2931860c85/pyqwest-0.7.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:ca02089249c292ab9c148fa86c06927701897090226a13e392a6ec53312380ea", size = 5712503, upload-time = "2026-07-19T05:19:50.542Z" },
+ { url = "https://files.pythonhosted.org/packages/f4/63/c5be988c55c69c87de950e3dabab322f82a78dc7c2ebdf89af32626bd473/pyqwest-0.7.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:da3bc117c1380e9577994da15b8236f7c3bb400111d6be4b57a9b2e4f30c9a79", size = 5893782, upload-time = "2026-07-19T05:19:52.286Z" },
+ { url = "https://files.pythonhosted.org/packages/82/a7/96144e6db9a49eb5e42734562ac5d387c2b78fe1142674d3a284ce188ef7/pyqwest-0.7.0-cp314-cp314t-win_amd64.whl", hash = "sha256:a599ddac7ded32ed62d15ca90bc9c77652ba34b225cf17a404821cec92a189fa", size = 4744187, upload-time = "2026-07-19T05:19:53.921Z" },
+ { url = "https://files.pythonhosted.org/packages/ed/42/26cf547b2e43078b4663e717715a289f31fc873d65d45cf354f364faa744/pyqwest-0.7.0-pp311-pypy311_pp73-macosx_10_12_x86_64.whl", hash = "sha256:bebc51e3c9c6339d81964c6e60516a5f5c9fe793c82da57ef7c2d87a55741829", size = 5170766, upload-time = "2026-07-19T05:19:55.472Z" },
+ { url = "https://files.pythonhosted.org/packages/dc/bc/1aac42f34bd3e5ac4c13a2c267dba6bda4bdea594ff96c7851dff930c8f1/pyqwest-0.7.0-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:37623b492aea7ccd3b6cfe3179110643d28c2cdc83c765aac3d207b4321995d2", size = 5053361, upload-time = "2026-07-19T05:19:56.973Z" },
+ { url = "https://files.pythonhosted.org/packages/0d/59/e3d8cfd2c7be0e12773ee4f767efc03be50ccdd28c6155d0b176bf1d8a9a/pyqwest-0.7.0-pp311-pypy311_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:02ff96a7746de208a4b8c78abe780c413d66576146a4ec64efd348b0c8a8328c", size = 5573900, upload-time = "2026-07-19T05:19:58.536Z" },
+ { url = "https://files.pythonhosted.org/packages/39/a4/7dd4d548be6d54b195d737164dc67c39d9c5df40aa76a873fe1d2d9b4426/pyqwest-0.7.0-pp311-pypy311_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:fd2e9bfa81198db7023202962a94920986a9a3dd12fe2f9d310f0cfcdddc092c", size = 5510692, upload-time = "2026-07-19T05:20:00.015Z" },
+ { url = "https://files.pythonhosted.org/packages/48/13/c070baf81da8653803328b632baddb5647b66cc7c6353c58f024ca82277c/pyqwest-0.7.0-pp311-pypy311_pp73-musllinux_1_2_aarch64.whl", hash = "sha256:e1548708dbeb29a60db199c70b9e93733d6b334e7efa1dfa5e3846a4f890db6d", size = 5735516, upload-time = "2026-07-19T05:20:01.487Z" },
+ { url = "https://files.pythonhosted.org/packages/84/46/e0f2a02ebf504db6bdf4bf343f0d3362eccf8dd5a325382fab1305fa7022/pyqwest-0.7.0-pp311-pypy311_pp73-musllinux_1_2_x86_64.whl", hash = "sha256:4bb3cf0975ee829b6c76e1c42f01863122ce71b1a952e507e260a9d29eb9b183", size = 5916743, upload-time = "2026-07-19T05:20:03.132Z" },
+ { url = "https://files.pythonhosted.org/packages/07/7c/4a35df79a142e5fcb5f46fce2d1d70dd72325a65db4139bbba4fbed0d9b9/pyqwest-0.7.0-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:2ea1ce4d630c92cb2cc6b3bf91ada0053b051dfd5c0662d89957ebd829cfdcce", size = 4759967, upload-time = "2026-07-19T05:20:04.837Z" },
+]
+
[[package]]
name = "pytest"
version = "9.1.1"
@@ -1128,11 +1268,11 @@ wheels = [
[[package]]
name = "typing-extensions"
-version = "4.15.0"
+version = "4.16.0"
source = { registry = "https://pypi.org/simple" }
-sdist = { url = "https://files.pythonhosted.org/packages/72/94/1a15dd82efb362ac84269196e94cf00f187f7ed21c242792a923cdb1c61f/typing_extensions-4.15.0.tar.gz", hash = "sha256:0cea48d173cc12fa28ecabc3b837ea3cf6f38c6d1136f85cbaaf598984861466", size = 109391, upload-time = "2025-08-25T13:49:26.313Z" }
+sdist = { url = "https://files.pythonhosted.org/packages/f6/cc/6253133b5bb138fc3306cebfbda2c520f545d36b5be2c7255cc528bb45d6/typing_extensions-4.16.0.tar.gz", hash = "sha256:dc983d19a509c94dba722ee6abd33940f7c05a89e243c47e907eb4db6f1a43e5", size = 113555, upload-time = "2026-07-02T08:40:05.92Z" }
wheels = [
- { url = "https://files.pythonhosted.org/packages/18/67/36e9267722cc04a6b9f15c7f3441c2363321a3ea07da7ae0c0707beb2a9c/typing_extensions-4.15.0-py3-none-any.whl", hash = "sha256:f0fa19c6845758ab08074a0cfa8b7aecb71c999ca73d62883bc25cc018c4e548", size = 44614, upload-time = "2025-08-25T13:49:24.86Z" },
+ { url = "https://files.pythonhosted.org/packages/49/d3/b8441a820a491ddfc024b0b0cf0393375b75ea13866d9c66727e54c2fc80/typing_extensions-4.16.0-py3-none-any.whl", hash = "sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8", size = 45571, upload-time = "2026-07-02T08:40:04.659Z" },
]
[[package]]
@@ -1149,12 +1289,12 @@ wheels = [
[[package]]
name = "wcmatch"
-version = "10.2"
+version = "10.2.1"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "bracex" },
]
-sdist = { url = "https://files.pythonhosted.org/packages/45/98/eb989c3113908e2ef46d940a53695a1ebb4be5a732c4a4f700be8f8d682b/wcmatch-10.2.tar.gz", hash = "sha256:92204839e3e9c945e1e71d7e1e4edeab2601ed50a5c51ff4f3f97ca711eeb738", size = 132499, upload-time = "2026-06-30T00:50:07.198Z" }
+sdist = { url = "https://files.pythonhosted.org/packages/11/15/dc61746d8c0852f6d711ad09c774b63cf7c8211aa49e30871ac3d342b7e2/wcmatch-10.2.1.tar.gz", hash = "sha256:ecac70a5c70e62ba854b78318d3a1408e8651f8f1c96e5837743b71aa6a4fb92", size = 132497, upload-time = "2026-07-02T17:21:48.484Z" }
wheels = [
- { url = "https://files.pythonhosted.org/packages/d4/73/aef4aaf16b8d785762e2b14cf321a9178cc84a1bf4c40f58320f499a2d65/wcmatch-10.2-py3-none-any.whl", hash = "sha256:f1a79e80ccbe296907b7eaf57d8d3bc49eab0b428d35f7d09986b5079b6e4a5d", size = 39742, upload-time = "2026-06-30T00:50:05.927Z" },
+ { url = "https://files.pythonhosted.org/packages/82/ba/20b48eedeab5316bf9a502bb9eb7e3b1588bd61d0f565822fefa8f06e10b/wcmatch-10.2.1-py3-none-any.whl", hash = "sha256:2d775395b93f233af66690f62cb9d52b084ec159a31cc4084f4069d72f437acd", size = 39763, upload-time = "2026-07-02T17:21:47.134Z" },
]
diff --git a/spec/envd/buf-python.gen.yaml b/spec/envd/buf-python.gen.yaml
index e84a2a852..c09acaaa9 100644
--- a/spec/envd/buf-python.gen.yaml
+++ b/spec/envd/buf-python.gen.yaml
@@ -1,14 +1,16 @@
# buf.gen.yaml defines a local generation template.
# For details, see https://buf.build/docs/configuration/v1/buf-gen-yaml
+# Both plugins are pip-installed from the python-sdk codegen dependency group
+# (`make init`): protoc-gen-py generates the protobuf-py messages and
+# protoc-gen-connectrpc the Connect clients.
version: v1
plugins:
- - plugin: python
+ - name: py
out: ../../packages/python-sdk/e2b/envd
- opt:
- - pyi_out=../../packages/python-sdk/e2b/envd
- - name: connect-python
+ path: protoc-gen-py
+ - name: connectrpc
out: ../../packages/python-sdk/e2b/envd
- path: protoc-gen-connect-python
+ path: protoc-gen-connectrpc
managed:
enabled: true