devzero-sandbox 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. devzero_sandbox-0.1.0/.gitignore +2 -0
  2. devzero_sandbox-0.1.0/LICENSE +202 -0
  3. devzero_sandbox-0.1.0/Makefile +28 -0
  4. devzero_sandbox-0.1.0/PKG-INFO +113 -0
  5. devzero_sandbox-0.1.0/README.md +96 -0
  6. devzero_sandbox-0.1.0/buf.gen.yaml +11 -0
  7. devzero_sandbox-0.1.0/pyproject.toml +48 -0
  8. devzero_sandbox-0.1.0/src/devzero_sandbox/__init__.py +41 -0
  9. devzero_sandbox-0.1.0/src/devzero_sandbox/_bgscript.py +104 -0
  10. devzero_sandbox-0.1.0/src/devzero_sandbox/_proto/__init__.py +1 -0
  11. devzero_sandbox-0.1.0/src/devzero_sandbox/_proto/sandbox/__init__.py +1 -0
  12. devzero_sandbox-0.1.0/src/devzero_sandbox/_proto/sandbox/v1/__init__.py +1 -0
  13. devzero_sandbox-0.1.0/src/devzero_sandbox/_proto/sandbox/v1/error_pb2.py +40 -0
  14. devzero_sandbox-0.1.0/src/devzero_sandbox/_proto/sandbox/v1/error_pb2.pyi +23 -0
  15. devzero_sandbox-0.1.0/src/devzero_sandbox/_proto/sandbox/v1/service_connect.py +381 -0
  16. devzero_sandbox-0.1.0/src/devzero_sandbox/_proto/sandbox/v1/service_pb2.py +227 -0
  17. devzero_sandbox-0.1.0/src/devzero_sandbox/_proto/sandbox/v1/service_pb2.pyi +898 -0
  18. devzero_sandbox-0.1.0/src/devzero_sandbox/auth.py +363 -0
  19. devzero_sandbox-0.1.0/src/devzero_sandbox/commands.py +818 -0
  20. devzero_sandbox-0.1.0/src/devzero_sandbox/connect.py +381 -0
  21. devzero_sandbox-0.1.0/src/devzero_sandbox/errors.py +453 -0
  22. devzero_sandbox-0.1.0/src/devzero_sandbox/files.py +217 -0
  23. devzero_sandbox-0.1.0/src/devzero_sandbox/incluster.py +42 -0
  24. devzero_sandbox-0.1.0/src/devzero_sandbox/mcp/__init__.py +55 -0
  25. devzero_sandbox-0.1.0/src/devzero_sandbox/mcp/__main__.py +7 -0
  26. devzero_sandbox-0.1.0/src/devzero_sandbox/mcp/config.py +132 -0
  27. devzero_sandbox-0.1.0/src/devzero_sandbox/mcp/server.py +259 -0
  28. devzero_sandbox-0.1.0/src/devzero_sandbox/mcp/tools.py +1007 -0
  29. devzero_sandbox-0.1.0/src/devzero_sandbox/py.typed +0 -0
  30. devzero_sandbox-0.1.0/src/devzero_sandbox/redaction.py +78 -0
  31. devzero_sandbox-0.1.0/src/devzero_sandbox/sandbox.py +634 -0
  32. devzero_sandbox-0.1.0/src/devzero_sandbox/terminal.py +428 -0
  33. devzero_sandbox-0.1.0/src/devzero_sandbox/transport.py +546 -0
  34. devzero_sandbox-0.1.0/tests/.gitkeep +0 -0
  35. devzero_sandbox-0.1.0/tests/conftest.py +97 -0
  36. devzero_sandbox-0.1.0/tests/fakecp.py +155 -0
  37. devzero_sandbox-0.1.0/tests/fakegw.py +605 -0
  38. devzero_sandbox-0.1.0/tests/fixtures/incluster/ca.crt +12 -0
  39. devzero_sandbox-0.1.0/tests/fixtures/incluster/gateway.crt +16 -0
  40. devzero_sandbox-0.1.0/tests/fixtures/incluster/gateway.key +5 -0
  41. devzero_sandbox-0.1.0/tests/mcpfakes.py +154 -0
  42. devzero_sandbox-0.1.0/tests/test_auth.py +239 -0
  43. devzero_sandbox-0.1.0/tests/test_commands.py +438 -0
  44. devzero_sandbox-0.1.0/tests/test_connect.py +288 -0
  45. devzero_sandbox-0.1.0/tests/test_errors.py +163 -0
  46. devzero_sandbox-0.1.0/tests/test_files.py +187 -0
  47. devzero_sandbox-0.1.0/tests/test_incluster.py +99 -0
  48. devzero_sandbox-0.1.0/tests/test_incluster_transport.py +299 -0
  49. devzero_sandbox-0.1.0/tests/test_lifecycle.py +479 -0
  50. devzero_sandbox-0.1.0/tests/test_mcp_config.py +107 -0
  51. devzero_sandbox-0.1.0/tests/test_mcp_server.py +650 -0
  52. devzero_sandbox-0.1.0/tests/test_mcp_tools.py +894 -0
  53. devzero_sandbox-0.1.0/tests/test_processes.py +511 -0
  54. devzero_sandbox-0.1.0/tests/test_redaction.py +158 -0
  55. devzero_sandbox-0.1.0/tests/test_sandboxes.py +431 -0
  56. devzero_sandbox-0.1.0/tests/test_terminal.py +658 -0
  57. devzero_sandbox-0.1.0/tests/test_transport.py +447 -0
  58. devzero_sandbox-0.1.0/tools/gen_connect.py +116 -0
@@ -0,0 +1,2 @@
1
+ # make test / make generate-client scratch output
2
+ _output/
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2026 DevZero, Inc.
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,28 @@
1
+ .PHONY: lint test generate-client check-generated build publish clean
2
+ # Tools come from uv, so CI and laptops need nothing on PATH but uv itself.
3
+ # mypy runs in the synced project env (no --no-sync): it type-checks against the package's dependencies (httpx), which a
4
+ # fresh CI venv has only after uv installs them. --no-sync passed locally only where an earlier `uv run` had synced .venv.
5
+ # types-protobuf: the generated *_pb2.pyi stubs import google.protobuf, which ships no type information of its own.
6
+ # --extra mcp: the MCP server (devzero_sandbox.mcp.server, ADR-003-W11) is type-checked and tested with its optional
7
+ # dependency installed; the SDK itself never imports it.
8
+ lint: ; uvx ruff check . && uvx ruff format --check . && uv run --extra mcp --with mypy --with types-protobuf mypy --strict src
9
+ test: ; mkdir -p _output && uv run --extra mcp --with pytest pytest -q --junitxml=_output/junit.xml
10
+ # The SandboxService client (ADR-007-W13): protobuf messages from buf's pinned remote plugins (buf.gen.yaml; versions in
11
+ # the repo's buf.pins.yaml), then the Connect stub from a buf image that keeps the proto comments (tools/gen_connect.py).
12
+ # The proto in dakr/proto/sandbox/v1 is the contract (devzero-inc/services#11988); the output is checked in.
13
+ BUF := $(CURDIR)/../../tools/scripts/buf.sh
14
+ PROTOS := --path proto/sandbox/v1/service.proto --path proto/sandbox/v1/error.proto
15
+ generate-client:
16
+ rm -rf -- src/devzero_sandbox/_proto
17
+ mkdir -p _output
18
+ cd ../../dakr && $(BUF) generate --template $(CURDIR)/buf.gen.yaml -o $(CURDIR) $(PROTOS)
19
+ cd ../../dakr && $(BUF) build -o $(CURDIR)/_output/sandbox.binpb $(PROTOS)
20
+ uv run python tools/gen_connect.py _output/sandbox.binpb src/devzero_sandbox/_proto
21
+ # CI freshness check: the checked-in client is what the current proto generates.
22
+ check-generated: generate-client
23
+ @git diff --exit-code -- src/devzero_sandbox/_proto && test -z "$$(git ls-files --others --exclude-standard -- src/devzero_sandbox/_proto)" \
24
+ || { git ls-files --others --exclude-standard -- src/devzero_sandbox/_proto; \
25
+ echo "stale client: run make generate-client and commit the result" >&2; exit 1; }
26
+ build: ; python -m build
27
+ publish: ; @echo "publish runs in CI (sandbox-sdk-python-publish.yml)"; exit 1
28
+ clean: ; rm -rf dist _output .mypy_cache .ruff_cache
@@ -0,0 +1,113 @@
1
+ Metadata-Version: 2.5
2
+ Name: devzero-sandbox
3
+ Version: 0.1.0
4
+ Summary: DevZero self-hosted sandboxes SDK (control plane + data plane clients) and MCP server
5
+ License-Expression: Apache-2.0
6
+ License-File: LICENSE
7
+ Requires-Python: >=3.11
8
+ Requires-Dist: googleapis-common-protos>=1.63
9
+ Requires-Dist: httpx-sse>=0.4
10
+ Requires-Dist: httpx>=0.27
11
+ Requires-Dist: protobuf>=5.29.3
12
+ Requires-Dist: pydantic>=2
13
+ Requires-Dist: websockets>=13
14
+ Provides-Extra: mcp
15
+ Requires-Dist: mcp<3,>=2.3; extra == 'mcp'
16
+ Description-Content-Type: text/markdown
17
+
18
+ # devzero-sandbox
19
+
20
+ The Python SDK and MCP server for DevZero self-hosted sandboxes: isolated Linux containers that
21
+ run in your own Kubernetes cluster, created through DevZero. Python 3.11+, Apache-2.0.
22
+
23
+ ```bash
24
+ pip install devzero-sandbox # the SDK
25
+ pip install 'devzero-sandbox[mcp]' # the SDK and the sandbox-mcp server
26
+ ```
27
+
28
+ ## A script
29
+
30
+ Set `DEVZERO_TOKEN` to a DevZero personal access token (`dzu-...`) or team service-account token
31
+ (`dzs-...`) of a Developer on the cluster's team. `DEVZERO_DAKR_URL` points at a DevZero API
32
+ other than the default.
33
+
34
+ ```python
35
+ from devzero_sandbox import Client
36
+
37
+ client = Client() # DEVZERO_TOKEN, DEVZERO_DAKR_URL
38
+ sbx = client.sandboxes.create("default", cluster_id="<cluster id>") # waits until ready
39
+
40
+ result = sbx.commands.run("echo hello")
41
+ print(result.exit_code, result.stdout_text)
42
+
43
+ sbx.files.write("data.bin", b"\x00\x01 any bytes")
44
+ assert sbx.files.read("data.bin") == b"\x00\x01 any bytes"
45
+
46
+ sbx.delete()
47
+ ```
48
+
49
+ `cluster_id` is needed only when the policy name exists on more than one cluster;
50
+ `client.policies()` lists the policies you can use. When the cluster's gateway endpoint serves a
51
+ certificate from a private CA (a bring-your-own endpoint), pass it:
52
+ `Client(gateway_options={"ca_bundle": "/path/to/ca.crt"})`.
53
+
54
+ The same calls run against preproduction in `make real-cp-run`
55
+ (`operators/sandbox-operator/hack/lib/real_cp_sdk.py script`).
56
+
57
+ More: `sbx.commands.run(cmd, background=True)` returns a `Process` you can `attach` to again from
58
+ any process, `sbx.terminal()` opens an interactive terminal, `sbx.extend(ttl)` keeps the sandbox
59
+ longer, `sbx.tokens.mint(scope=[...])` / `.revoke(jti)` manage its tokens. Every failure is a
60
+ typed exception from `devzero_sandbox.errors`.
61
+
62
+ ## In the cluster
63
+
64
+ A pod in the cluster reaches a sandbox without a DevZero credential, with its ServiceAccount, when
65
+ the sandbox's policy lists that ServiceAccount in `access.serviceAccounts`. Mount a projected token
66
+ for the gateway's audience and the CA bundle the sandbox operator publishes into the pod's
67
+ namespace:
68
+
69
+ ```yaml
70
+ volumes:
71
+ - name: dz-sandbox
72
+ projected:
73
+ sources:
74
+ - serviceAccountToken: { audience: sandbox-gateway.devzero.io, expirationSeconds: 3600, path: token }
75
+ - configMap: { name: devzero-sandbox-ca, items: [{ key: ca.crt, path: ca.crt }] }
76
+ # containers[].volumeMounts: [{ name: dz-sandbox, mountPath: /var/run/dz-sandbox, readOnly: true }]
77
+ ```
78
+
79
+ ```python
80
+ from devzero_sandbox import Sandbox
81
+
82
+ # reads /var/run/dz-sandbox/{token,ca.crt}
83
+ sbx = Sandbox.in_cluster("<policy>", "<sandbox id>")
84
+ print(sbx.commands.run("echo hello").stdout_text)
85
+ ```
86
+
87
+ The sandbox id is the `sandbox.devzero.io/sandbox-id` label of the `SandboxClaim` the pod's
88
+ ServiceAccount created in the policy's namespace.
89
+
90
+ ## MCP server
91
+
92
+ `sandbox-mcp` is a stdio MCP server with seven tools: `create_sandbox`, `run_command`,
93
+ `read_file`, `write_file`, `list_files`, `upload` and `delete_sandbox`. Sandboxes a session created
94
+ are deleted when it ends, and it writes nothing to disk. It is configured from its environment only:
95
+
96
+ ```json
97
+ {
98
+ "mcpServers": {
99
+ "devzero-sandbox": {
100
+ "command": "sandbox-mcp",
101
+ "env": {
102
+ "DEVZERO_TOKEN": "dzu-...",
103
+ "DEVZERO_SANDBOX_POLICY": "default",
104
+ "DEVZERO_SANDBOX_CLUSTER_ID": "<cluster id>"
105
+ }
106
+ }
107
+ }
108
+ }
109
+ ```
110
+
111
+ The other variables (`DEVZERO_SANDBOX_CA_BUNDLE`, `DEVZERO_SANDBOX_MCP_UPLOAD_ROOT`, which turns
112
+ `upload` on, and the output and timeout limits) are listed by `sandbox-mcp --help` and in
113
+ `devzero_sandbox/mcp/config.py`.
@@ -0,0 +1,96 @@
1
+ # devzero-sandbox
2
+
3
+ The Python SDK and MCP server for DevZero self-hosted sandboxes: isolated Linux containers that
4
+ run in your own Kubernetes cluster, created through DevZero. Python 3.11+, Apache-2.0.
5
+
6
+ ```bash
7
+ pip install devzero-sandbox # the SDK
8
+ pip install 'devzero-sandbox[mcp]' # the SDK and the sandbox-mcp server
9
+ ```
10
+
11
+ ## A script
12
+
13
+ Set `DEVZERO_TOKEN` to a DevZero personal access token (`dzu-...`) or team service-account token
14
+ (`dzs-...`) of a Developer on the cluster's team. `DEVZERO_DAKR_URL` points at a DevZero API
15
+ other than the default.
16
+
17
+ ```python
18
+ from devzero_sandbox import Client
19
+
20
+ client = Client() # DEVZERO_TOKEN, DEVZERO_DAKR_URL
21
+ sbx = client.sandboxes.create("default", cluster_id="<cluster id>") # waits until ready
22
+
23
+ result = sbx.commands.run("echo hello")
24
+ print(result.exit_code, result.stdout_text)
25
+
26
+ sbx.files.write("data.bin", b"\x00\x01 any bytes")
27
+ assert sbx.files.read("data.bin") == b"\x00\x01 any bytes"
28
+
29
+ sbx.delete()
30
+ ```
31
+
32
+ `cluster_id` is needed only when the policy name exists on more than one cluster;
33
+ `client.policies()` lists the policies you can use. When the cluster's gateway endpoint serves a
34
+ certificate from a private CA (a bring-your-own endpoint), pass it:
35
+ `Client(gateway_options={"ca_bundle": "/path/to/ca.crt"})`.
36
+
37
+ The same calls run against preproduction in `make real-cp-run`
38
+ (`operators/sandbox-operator/hack/lib/real_cp_sdk.py script`).
39
+
40
+ More: `sbx.commands.run(cmd, background=True)` returns a `Process` you can `attach` to again from
41
+ any process, `sbx.terminal()` opens an interactive terminal, `sbx.extend(ttl)` keeps the sandbox
42
+ longer, `sbx.tokens.mint(scope=[...])` / `.revoke(jti)` manage its tokens. Every failure is a
43
+ typed exception from `devzero_sandbox.errors`.
44
+
45
+ ## In the cluster
46
+
47
+ A pod in the cluster reaches a sandbox without a DevZero credential, with its ServiceAccount, when
48
+ the sandbox's policy lists that ServiceAccount in `access.serviceAccounts`. Mount a projected token
49
+ for the gateway's audience and the CA bundle the sandbox operator publishes into the pod's
50
+ namespace:
51
+
52
+ ```yaml
53
+ volumes:
54
+ - name: dz-sandbox
55
+ projected:
56
+ sources:
57
+ - serviceAccountToken: { audience: sandbox-gateway.devzero.io, expirationSeconds: 3600, path: token }
58
+ - configMap: { name: devzero-sandbox-ca, items: [{ key: ca.crt, path: ca.crt }] }
59
+ # containers[].volumeMounts: [{ name: dz-sandbox, mountPath: /var/run/dz-sandbox, readOnly: true }]
60
+ ```
61
+
62
+ ```python
63
+ from devzero_sandbox import Sandbox
64
+
65
+ # reads /var/run/dz-sandbox/{token,ca.crt}
66
+ sbx = Sandbox.in_cluster("<policy>", "<sandbox id>")
67
+ print(sbx.commands.run("echo hello").stdout_text)
68
+ ```
69
+
70
+ The sandbox id is the `sandbox.devzero.io/sandbox-id` label of the `SandboxClaim` the pod's
71
+ ServiceAccount created in the policy's namespace.
72
+
73
+ ## MCP server
74
+
75
+ `sandbox-mcp` is a stdio MCP server with seven tools: `create_sandbox`, `run_command`,
76
+ `read_file`, `write_file`, `list_files`, `upload` and `delete_sandbox`. Sandboxes a session created
77
+ are deleted when it ends, and it writes nothing to disk. It is configured from its environment only:
78
+
79
+ ```json
80
+ {
81
+ "mcpServers": {
82
+ "devzero-sandbox": {
83
+ "command": "sandbox-mcp",
84
+ "env": {
85
+ "DEVZERO_TOKEN": "dzu-...",
86
+ "DEVZERO_SANDBOX_POLICY": "default",
87
+ "DEVZERO_SANDBOX_CLUSTER_ID": "<cluster id>"
88
+ }
89
+ }
90
+ }
91
+ }
92
+ ```
93
+
94
+ The other variables (`DEVZERO_SANDBOX_CA_BUNDLE`, `DEVZERO_SANDBOX_MCP_UPLOAD_ROOT`, which turns
95
+ `upload` on, and the output and timeout limits) are listed by `sandbox-mcp --help` and in
96
+ `devzero_sandbox/mcp/config.py`.
@@ -0,0 +1,11 @@
1
+ # Messages for the SandboxService client (ADR-007-W13), generated from
2
+ # dakr/proto/sandbox/v1 by `make generate-client`; versions pinned in the repo's
3
+ # buf.pins.yaml (tools/bufpins checks them). The Connect client on top of these
4
+ # messages (service_connect.py) is written by tools/gen_connect.py from the same
5
+ # descriptors. Never edit the output by hand.
6
+ version: v2
7
+ plugins:
8
+ - remote: buf.build/protocolbuffers/python:v29.3
9
+ out: src/devzero_sandbox/_proto
10
+ - remote: buf.build/protocolbuffers/pyi:v29.3
11
+ out: src/devzero_sandbox/_proto
@@ -0,0 +1,48 @@
1
+ [project]
2
+ name = "devzero-sandbox"
3
+ version = "0.1.0"
4
+ description = "DevZero self-hosted sandboxes SDK (control plane + data plane clients) and MCP server"
5
+ readme = "README.md"
6
+ requires-python = ">=3.11"
7
+ license = "Apache-2.0" # SPDX expression (PEP 639); devzero-inc/services#12006
8
+ license-files = ["LICENSE"]
9
+ # protobuf: the generated sandbox.v1 messages (gencode 5.29.3 needs a runtime at least that new);
10
+ # googleapis-common-protos: google.type.Money, which sandbox/v1/service.proto imports.
11
+ dependencies = [
12
+ "httpx>=0.27",
13
+ "httpx-sse>=0.4",
14
+ "websockets>=13",
15
+ "pydantic>=2",
16
+ "protobuf>=5.29.3",
17
+ "googleapis-common-protos>=1.63",
18
+ ]
19
+ # The stdio MCP server (ADR-003-W11). mcp 2.x: the official MCP Python SDK's current major (low-level Server
20
+ # with on_* handlers, stdio transport that points fd 1 at stderr while serving); 1.x has a different server API.
21
+ [project.optional-dependencies]
22
+ mcp = ["mcp>=2.3,<3"]
23
+ [project.scripts]
24
+ # Without the extra, the command says how to install it (devzero_sandbox.mcp.main imports the server lazily).
25
+ sandbox-mcp = "devzero_sandbox.mcp:main"
26
+ # No other Python package is published from this repo, so there is no backend to align to; hatchling (kit default).
27
+ [build-system]
28
+ requires = ["hatchling>=1.27"] # PEP 639 license / license-files
29
+ build-backend = "hatchling.build"
30
+
31
+ [tool.ruff]
32
+ # Written by `make generate-client` (buf + tools/gen_connect.py); never edited by hand.
33
+ extend-exclude = ["src/devzero_sandbox/_proto"]
34
+
35
+ [tool.pytest.ini_options]
36
+ markers = ["processes: runs real shell processes behind the fake gateway (POSIX only)"]
37
+
38
+ # The protoc pyi plugin writes bare `Mapping` for map-field constructors; the
39
+ # generated stubs are not ours to edit.
40
+ [[tool.mypy.overrides]]
41
+ module = ["devzero_sandbox._proto.*"]
42
+ disallow_any_generics = false
43
+
44
+ # google.type.Money (googleapis-common-protos) ships no type information; only
45
+ # EstimateWarmPoolCost uses it.
46
+ [[tool.mypy.overrides]]
47
+ module = ["google.type.*"]
48
+ ignore_missing_imports = true
@@ -0,0 +1,41 @@
1
+ """DevZero self-hosted sandboxes SDK (control plane + data plane clients).
2
+
3
+ from devzero_sandbox import Client
4
+
5
+ client = Client() # DEVZERO_TOKEN, DEVZERO_DAKR_URL
6
+ sbx = client.sandboxes.create("default") # waits for ready
7
+ print(sbx.commands.run("echo hi").stdout_text)
8
+ proc = sbx.commands.run("make test", background=True)
9
+ sbx.files.write("notes.txt", "hello")
10
+ sbx.delete()
11
+
12
+ In a pod in the cluster, with no DevZero credential:
13
+
14
+ sbx = Sandbox.in_cluster("default", "sb7k2m9q4xz1")
15
+
16
+ Layers: ``sandbox`` (``Client``, ``Sandbox``), ``commands``, ``files``,
17
+ ``terminal`` (data plane, ADR-007-W13) on ``transport`` and ``auth``
18
+ (ADR-005-W11); ``connect`` and the generated ``_proto`` stub for DevZero's
19
+ ``SandboxService``; ``errors`` for every typed exception.
20
+ """
21
+
22
+ __version__ = "0.1.0"
23
+
24
+ from devzero_sandbox.commands import CommandResult, Process
25
+ from devzero_sandbox.errors import (
26
+ DevZeroSandboxError,
27
+ StreamInterrupted,
28
+ )
29
+ from devzero_sandbox.sandbox import Client, Sandbox
30
+ from devzero_sandbox.terminal import PartialSendTimeout
31
+
32
+ __all__ = [
33
+ "Client",
34
+ "CommandResult",
35
+ "DevZeroSandboxError",
36
+ "PartialSendTimeout",
37
+ "Process",
38
+ "Sandbox",
39
+ "StreamInterrupted",
40
+ "__version__",
41
+ ]
@@ -0,0 +1,104 @@
1
+ """The shell side of ``commands.run(background=True)`` (ADR-007-W13).
2
+
3
+ ``sandboxd`` (v1.0.9) kills a ``Start`` stream's process tree when the stream
4
+ closes: ``kill(-pgid)``, then a ``/proc/<pid>/task/*/children`` walk for
5
+ runtimes where group signals miss grandchildren (gVisor), then the pid
6
+ (review/upstream-k8s.md V21). A background command therefore cannot be a
7
+ descendant of the stream's process, nor share its process group, or closing
8
+ the stream (the SDK exiting, a gateway rollout, the 30 min idle limit) kills
9
+ it. The launcher below:
10
+
11
+ 1. reads its own pid from stdin: ``sandboxd`` numbers processes itself, so the
12
+ SDK learns the pid from the stream's ``init`` event and writes it back;
13
+ 2. starts the command with ``setsid`` from a subshell that exits at once, so
14
+ the command leads a new session and process group and is re-parented away
15
+ from the launcher (out of both kill strategies);
16
+ 3. sends the command's stdout and stderr to ``<dir>/<pid>.log``, its pid to
17
+ ``<dir>/<pid>.pid`` and, when it ends, its exit code to ``<dir>/<pid>.exit``
18
+ (written by rename, so a reader never sees half of it);
19
+ 4. stays as the *holder*: a stream that prints ``dz-bg:exit:<code>`` when the
20
+ exit file appears and exits with that code. While it waits it prints an
21
+ empty line every ``<heartbeat>`` seconds. The gateway ends an SSE stream
22
+ after 30 min without stdout or stderr (ADR-007 §Limits; keepalive comments
23
+ do not count, ADR-007-W8), and these lines are real process output, so a
24
+ holder for a quiet command is not cut by the idle limit.
25
+
26
+ ``watch`` mode is the holder alone, for a process another stream launched
27
+ (``attach``, or a holder re-opened after a drain). Every protocol line on
28
+ stdout starts with ``dz-bg:``; a problem is ``dz-bg:error:<code>:<text>``.
29
+ ``kill`` mode SIGKILLs the process tree and group and writes exit code 137.
30
+ """
31
+
32
+ from __future__ import annotations
33
+
34
+ # Runs as: /bin/sh -c SCRIPT dz-bg <launch|watch|kill> <dir> <heartbeat_s> [<pid>] [argv...]
35
+ SCRIPT = r"""
36
+ set -u
37
+ mode=$1 dir=$2 hb=$3
38
+ shift 3
39
+ fail() { printf 'dz-bg:error:%s:%s\n' "$1" "$2"; exit 125; }
40
+ alive() { kill -0 "$1" 2>/dev/null && ! grep -q '^[^)]*) Z' "/proc/$1/stat" 2>/dev/null; }
41
+ tree() {
42
+ for c in $(cat /proc/"$1"/task/*/children 2>/dev/null); do tree "$c"; done
43
+ kill -s KILL "$1" 2>/dev/null
44
+ }
45
+ finish() { printf '%s\n' "$2" >"$1.exit.t" && mv -f "$1.exit.t" "$1.exit"; }
46
+ case $mode in
47
+ launch)
48
+ IFS= read -r id || fail no_pid "stdin closed before the pid arrived"
49
+ case $id in ''|*[!0-9]*) fail bad_pid "not a pid: $id" ;; esac
50
+ base=$dir/$id
51
+ mkdir -p "$dir" || fail no_dir "cannot create $dir"
52
+ command -v setsid >/dev/null 2>&1 || fail no_setsid "setsid is not installed in the sandbox image"
53
+ rm -f "$base.exit" "$base.pid" "$base.exit.t" "$base.pid.t"
54
+ : >"$base.log" || fail no_log "cannot write $base.log"
55
+ ( setsid /bin/sh -c '
56
+ b=$1; shift
57
+ echo $$ >"$b.pid.t" && mv -f "$b.pid.t" "$b.pid"
58
+ "$@" >>"$b.log" 2>&1 </dev/null
59
+ c=$?
60
+ printf "%s\n" "$c" >"$b.exit.t" && mv -f "$b.exit.t" "$b.exit"
61
+ ' dz-bg-run "$base" "$@" </dev/null >/dev/null 2>&1 & )
62
+ i=0
63
+ while [ ! -s "$base.pid" ]; do
64
+ i=$((i + 1))
65
+ [ "$i" -gt 200 ] && fail no_start "the process did not start within 20s"
66
+ sleep 0.1
67
+ done
68
+ echo dz-bg:started
69
+ ;;
70
+ watch)
71
+ id=$1
72
+ base=$dir/$id
73
+ [ -s "$base.pid" ] || fail not_found "no background process $id"
74
+ ;;
75
+ kill)
76
+ id=$1
77
+ base=$dir/$id
78
+ [ -s "$base.pid" ] || exit 3
79
+ [ -e "$base.exit" ] && exit 4
80
+ p=$(cat "$base.pid")
81
+ tree "$p"
82
+ # dash wants "--" before a negative pid, busybox refuses it: try both.
83
+ kill -s KILL -- "-$p" 2>/dev/null || kill -s KILL "-$p" 2>/dev/null
84
+ [ -e "$base.exit" ] || finish "$base" 137
85
+ exit 0
86
+ ;;
87
+ *) fail bad_mode "$mode" ;;
88
+ esac
89
+ p=$(cat "$base.pid")
90
+ n=0
91
+ while [ ! -e "$base.exit" ]; do
92
+ if ! alive "$p"; then
93
+ sleep 1
94
+ [ -e "$base.exit" ] || finish "$base" 137
95
+ break
96
+ fi
97
+ sleep 1
98
+ n=$((n + 1))
99
+ if [ "$n" -ge "$hb" ]; then echo; n=0; fi
100
+ done
101
+ c=$(cat "$base.exit")
102
+ echo "dz-bg:exit:$c"
103
+ exit "$c"
104
+ """
@@ -0,0 +1 @@
1
+ """Generated from dakr/proto/sandbox/v1 by `make generate-client`; do not edit."""
@@ -0,0 +1 @@
1
+ """Generated from dakr/proto/sandbox/v1 by `make generate-client`; do not edit."""
@@ -0,0 +1 @@
1
+ """Generated from dakr/proto/sandbox/v1 by `make generate-client`; do not edit."""