langchain-heaven 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.
@@ -0,0 +1,42 @@
1
+ # Publishes the package when main holds a version PyPI lacks, then tags it
2
+ # vVERSION. PyPI trusts this workflow (trusted publishing): no token is kept.
3
+ name: publish
4
+ on:
5
+ push:
6
+ branches: [main]
7
+ workflow_dispatch:
8
+ permissions:
9
+ contents: write # the tag
10
+ id-token: write # PyPI's trusted publishing
11
+ concurrency:
12
+ group: publish
13
+ cancel-in-progress: false
14
+ jobs:
15
+ publish:
16
+ runs-on: ubuntu-24.04
17
+ steps:
18
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
19
+ - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
20
+ with:
21
+ python-version: "3.13"
22
+ - id: version
23
+ run: |
24
+ version=$(python3 -c 'import tomllib; print(tomllib.load(open("pyproject.toml", "rb"))["project"]["version"])')
25
+ echo "version=$version" >> "$GITHUB_OUTPUT"
26
+ if curl -sfo /dev/null "https://pypi.org/pypi/langchain-heaven/$version/json"; then
27
+ echo "published=true" >> "$GITHUB_OUTPUT"
28
+ fi
29
+ - if: steps.version.outputs.published != 'true'
30
+ run: |
31
+ python3 -m pip install build==1.6.1
32
+ python3 -m build
33
+ - if: steps.version.outputs.published != 'true'
34
+ uses: pypa/gh-action-pypi-publish@7245906fb61fa33a13554f9d5fb856fe61758086 # v1.14.3
35
+ - name: Tag
36
+ env:
37
+ VERSION: ${{ steps.version.outputs.version }}
38
+ run: |
39
+ if [ -z "$(git ls-remote --tags origin "refs/tags/v$VERSION")" ]; then
40
+ git tag "v$VERSION"
41
+ git push origin "v$VERSION"
42
+ fi
@@ -0,0 +1,5 @@
1
+ .venv/
2
+ .pytest_cache/
3
+ .ruff_cache/
4
+ __pycache__/
5
+ dist/
@@ -0,0 +1,5 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0
4
+
5
+ Initial Heaven (heaven.dev) sandbox backend.
@@ -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 [yyyy] [name of copyright owner]
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,64 @@
1
+ .PHONY: format lint type typecheck test tests integration_test integration_tests test_watch benchmark help lint_package
2
+
3
+ .DEFAULT_GOAL := help
4
+
5
+ .EXPORT_ALL_VARIABLES:
6
+ UV_FROZEN = true
7
+
8
+ ######################
9
+ # TESTING
10
+ ######################
11
+
12
+ TEST_FILE ?= tests/unit_tests/
13
+ PYTEST_EXTRA ?=
14
+
15
+ integration_test integration_tests: TEST_FILE=tests/integration_tests/
16
+
17
+ test: ## Run unit tests
18
+ test tests:
19
+ uv run --group test pytest -vvv $(PYTEST_EXTRA) --disable-socket --allow-unix-socket $(TEST_FILE)
20
+
21
+ integration_test: ## Run integration tests
22
+ integration_test integration_tests:
23
+ uv run --group test pytest -vvv --timeout 30 $(TEST_FILE)
24
+
25
+ test_watch: ## Run tests in watch mode
26
+ uv run --group test ptw --now . -- -vv $(TEST_FILE)
27
+
28
+ benchmark: ## Run benchmark tests
29
+ uv run --group test pytest ./tests -m benchmark
30
+
31
+ ######################
32
+ # LINTING AND FORMATTING
33
+ ######################
34
+
35
+ PYTHON_FILES=.
36
+ lint format: PYTHON_FILES=.
37
+ lint_diff format_diff: PYTHON_FILES=$(shell git diff --relative=. --name-only --diff-filter=d main | grep -E '\.py$$|\.ipynb$$')
38
+ lint_package: ## Lint only the package
39
+ lint_package: PYTHON_FILES=langchain_heaven
40
+
41
+ lint: ## Run linters and type checker
42
+ lint lint_diff lint_package:
43
+ [ "$(PYTHON_FILES)" = "" ] || uv run --all-groups ruff check $(PYTHON_FILES)
44
+ [ "$(PYTHON_FILES)" = "" ] || uv run --all-groups ruff format $(PYTHON_FILES) --diff
45
+ $(MAKE) type
46
+
47
+ type: ## Run type checker
48
+ type typecheck:
49
+ uv run --all-groups ty check langchain_heaven
50
+
51
+ format: ## Run code formatters
52
+ format format_diff:
53
+ [ "$(PYTHON_FILES)" = "" ] || uv run --all-groups ruff format $(PYTHON_FILES)
54
+ [ "$(PYTHON_FILES)" = "" ] || uv run --all-groups ruff check --fix $(PYTHON_FILES)
55
+
56
+ ######################
57
+ # HELP
58
+ ######################
59
+
60
+ help: ## Show this help message
61
+ @echo "Usage: make [target] [TEST_FILE=path/to/tests/]"
62
+ @echo ""
63
+ @echo "Targets:"
64
+ @awk 'BEGIN {FS = ":.*##"} /^[a-zA-Z_-]+:.*##/ {printf " %-20s %s\n", $$1, $$2}' $(MAKEFILE_LIST)
@@ -0,0 +1,40 @@
1
+ Metadata-Version: 2.5
2
+ Name: langchain-heaven
3
+ Version: 0.1.0
4
+ Summary: Heaven (heaven.dev) sandbox backend for Deep Agents
5
+ Project-URL: Homepage, https://heaven.dev
6
+ Project-URL: Documentation, https://github.com/heavendotdev/langchain-heaven#readme
7
+ Project-URL: Source, https://github.com/heavendotdev/langchain-heaven
8
+ License-Expression: Apache-2.0
9
+ License-File: LICENSE
10
+ Keywords: ai-agents,deepagents,heaven,langchain,sandbox
11
+ Requires-Python: <4,>=3.11
12
+ Requires-Dist: deepagents<0.8,>=0.7.43
13
+ Requires-Dist: heaven-sdk<0.2,>=0.1.2
14
+ Description-Content-Type: text/markdown
15
+
16
+ # Heaven (heaven.dev) for Deep Agents
17
+
18
+ Use a persistent Linux Computer in a Heaven pool for Deep Agents commands and filesystem tools. Install `langchain-heaven` alongside Deep Agents 0.7.x (0.7.43 or newer). Set `HEAVEN_API_KEY` in the host application.
19
+
20
+ ```sh
21
+ pip install langchain-heaven
22
+ ```
23
+
24
+ ```python
25
+ from deepagents import create_deep_agent
26
+ from heaven import Heaven
27
+ from langchain_heaven import HeavenSandbox
28
+
29
+ with HeavenSandbox.create(client=Heaven(), pool="my-pool") as backend:
30
+ agent = create_deep_agent(backend=backend)
31
+ print(backend.execute("uname -s").output)
32
+ ```
33
+
34
+ Pass `organization` when needed. The context manager deletes the Computer it creates. To keep an existing Computer, use `HeavenSandbox(client=Heaven(), computer=computer_id)` with its immutable ID. The application then owns that Computer's lifecycle.
35
+
36
+ Transfers support absolute paths and binary files. The default Heaven image supplies the shell, GNU coreutils and Python 3 used by filesystem tools. The default command timeout is 30 minutes. An explicit zero uses Heaven's one-hour execution limit. The adapter retains the first 4 MiB of output and reports truncation. Async methods use the Deep Agents sync-to-thread implementations.
37
+
38
+ Deep Agents Code discovers the installed backend under `heaven`. Set `HEAVEN_POOL` (and `HEAVEN_ORGANIZATION` if needed), then use `dcode --sandbox heaven` from the same Python environment. Supplying an existing running Computer with `--sandbox-id` leaves its lifecycle with the application.
39
+
40
+ See the [Heaven SDK guide](https://heaven.dev/docs/sdks).
@@ -0,0 +1,25 @@
1
+ # Heaven (heaven.dev) for Deep Agents
2
+
3
+ Use a persistent Linux Computer in a Heaven pool for Deep Agents commands and filesystem tools. Install `langchain-heaven` alongside Deep Agents 0.7.x (0.7.43 or newer). Set `HEAVEN_API_KEY` in the host application.
4
+
5
+ ```sh
6
+ pip install langchain-heaven
7
+ ```
8
+
9
+ ```python
10
+ from deepagents import create_deep_agent
11
+ from heaven import Heaven
12
+ from langchain_heaven import HeavenSandbox
13
+
14
+ with HeavenSandbox.create(client=Heaven(), pool="my-pool") as backend:
15
+ agent = create_deep_agent(backend=backend)
16
+ print(backend.execute("uname -s").output)
17
+ ```
18
+
19
+ Pass `organization` when needed. The context manager deletes the Computer it creates. To keep an existing Computer, use `HeavenSandbox(client=Heaven(), computer=computer_id)` with its immutable ID. The application then owns that Computer's lifecycle.
20
+
21
+ Transfers support absolute paths and binary files. The default Heaven image supplies the shell, GNU coreutils and Python 3 used by filesystem tools. The default command timeout is 30 minutes. An explicit zero uses Heaven's one-hour execution limit. The adapter retains the first 4 MiB of output and reports truncation. Async methods use the Deep Agents sync-to-thread implementations.
22
+
23
+ Deep Agents Code discovers the installed backend under `heaven`. Set `HEAVEN_POOL` (and `HEAVEN_ORGANIZATION` if needed), then use `dcode --sandbox heaven` from the same Python environment. Supplying an existing running Computer with `--sandbox-id` leaves its lifecycle with the application.
24
+
25
+ See the [Heaven SDK guide](https://heaven.dev/docs/sdks).
@@ -0,0 +1,24 @@
1
+ """Create a Computer, run a command and verify a binary transfer."""
2
+
3
+ import os
4
+ from uuid import uuid4
5
+
6
+ from heaven import Heaven
7
+
8
+ from langchain_heaven import HeavenSandbox
9
+
10
+ with HeavenSandbox.create(
11
+ client=Heaven(),
12
+ pool=os.environ["HEAVEN_POOL"],
13
+ organization=os.getenv("HEAVEN_ORGANIZATION"),
14
+ name=f"sbx-test-d-{uuid4().hex[:10]}",
15
+ ) as sandbox:
16
+ result = sandbox.execute("uname -s")
17
+ if result.exit_code != 0 or result.output.strip() != "Linux":
18
+ raise RuntimeError("Expected Linux from the guest")
19
+ path = "/tmp/heaven-example.bin"
20
+ data = bytes(range(256))
21
+ if sandbox.upload_files([(path, data)])[0].error:
22
+ raise RuntimeError("Upload failed")
23
+ if sandbox.download_files([path])[0].content != data:
24
+ raise RuntimeError("Download mismatch")
@@ -0,0 +1,5 @@
1
+ """Heaven (heaven.dev) sandbox backend for Deep Agents."""
2
+
3
+ from langchain_heaven.sandbox import HeavenSandbox
4
+
5
+ __all__ = ["HeavenSandbox"]
@@ -0,0 +1,55 @@
1
+ """Optional entry point loaded by Deep Agents Code when it is installed."""
2
+
3
+ import os
4
+
5
+ from deepagents_code.integrations.sandbox_provider import ( # ty: ignore[import-not-found]
6
+ SandboxNotFoundError,
7
+ SandboxProvider,
8
+ SandboxProviderMetadata,
9
+ )
10
+ from heaven import Heaven, NotFoundError
11
+
12
+ from langchain_heaven.sandbox import HeavenSandbox, _create_computer, _delete_computer
13
+
14
+
15
+ class HeavenProvider(SandboxProvider):
16
+ """Create session-owned Computers and reconnect to explicitly supplied IDs."""
17
+
18
+ @property
19
+ def metadata(self) -> SandboxProviderMetadata:
20
+ return SandboxProviderMetadata(name="heaven", working_dir="/home/heaven")
21
+
22
+ def get_or_create(
23
+ self, *, sandbox_id: str | None = None, **kwargs: object
24
+ ) -> HeavenSandbox:
25
+ if kwargs:
26
+ raise ValueError(
27
+ f"Unsupported Heaven provider options: {', '.join(sorted(kwargs))}"
28
+ )
29
+ client = Heaven()
30
+ if sandbox_id is not None:
31
+ try:
32
+ details = client.computers.get(sandbox_id)
33
+ except NotFoundError as exc:
34
+ raise SandboxNotFoundError(sandbox_id) from exc
35
+ if details.state != "running":
36
+ raise RuntimeError(
37
+ f"Computer is {details.state}. Start it before connecting."
38
+ )
39
+ return HeavenSandbox(client=client, computer=details.id)
40
+ pool = os.environ.get("HEAVEN_POOL")
41
+ if not pool:
42
+ raise ValueError("Set HEAVEN_POOL before creating a Computer.")
43
+ return HeavenSandbox(
44
+ client=client,
45
+ computer=_create_computer(
46
+ client, pool, None, os.getenv("HEAVEN_ORGANIZATION")
47
+ ),
48
+ )
49
+
50
+ def delete(self, *, sandbox_id: str, **kwargs: object) -> None:
51
+ if kwargs:
52
+ raise ValueError(
53
+ f"Unsupported Heaven provider options: {', '.join(sorted(kwargs))}"
54
+ )
55
+ _delete_computer(Heaven(), sandbox_id)
File without changes
@@ -0,0 +1,159 @@
1
+ """Run Deep Agents shell and filesystem tools on a Heaven Computer."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import io
6
+ import posixpath
7
+ import shlex
8
+ from collections.abc import Generator
9
+ from contextlib import contextmanager
10
+ from uuid import uuid4
11
+
12
+ from deepagents.backends.protocol import (
13
+ ExecuteResponse,
14
+ FileDownloadResponse,
15
+ FileUploadResponse,
16
+ )
17
+ from deepagents.backends.sandbox import BaseSandbox
18
+ from heaven import DeniedError, Heaven, HeavenError, InvalidError, NotFoundError
19
+
20
+ _OUTPUT_LIMIT = 4 * 1024 * 1024
21
+
22
+
23
+ def _file_error(exc: HeavenError) -> str:
24
+ if isinstance(exc, NotFoundError):
25
+ return "file_not_found"
26
+ if isinstance(exc, DeniedError):
27
+ return "permission_denied"
28
+ if isinstance(exc, InvalidError):
29
+ return "invalid_path"
30
+ return str(exc)
31
+
32
+
33
+ def _delete_computer(client: Heaven, computer: str) -> None:
34
+ removed = client.computers.delete(computer).results[0]
35
+ if removed.error and not isinstance(removed.error, NotFoundError):
36
+ raise removed.error
37
+ if removed.operation:
38
+ op = client.operations.wait(removed.operation)
39
+ if not op.ok:
40
+ raise RuntimeError(op.message or f"Delete ended in state {op.state}")
41
+ elif not isinstance(removed.error, NotFoundError):
42
+ raise RuntimeError("Deletion returned no operation.")
43
+
44
+
45
+ def _create_computer(
46
+ client: Heaven, pool: str, name: str | None, organization: str | None
47
+ ) -> str:
48
+ result = client.computers.create(
49
+ name or f"deepagents-{uuid4().hex[:12]}",
50
+ pool=pool,
51
+ organization=organization,
52
+ )
53
+ computer = result.operation.computer_id
54
+ if not computer:
55
+ raise RuntimeError("Creation returned no Computer ID.")
56
+ try:
57
+ op = client.operations.wait(result.operation)
58
+ if not op.ok:
59
+ raise RuntimeError(op.message or f"Create ended in state {op.state}")
60
+ return computer
61
+ except BaseException:
62
+ _delete_computer(client, computer)
63
+ raise
64
+
65
+
66
+ class HeavenSandbox(BaseSandbox):
67
+ """Bind to a running Computer by ID, or provision one with `create`."""
68
+
69
+ enable_capture_offload = True
70
+
71
+ def __init__(self, *, client: Heaven, computer: str, timeout: int = 1800) -> None:
72
+ self._client = client
73
+ self._computer = computer
74
+ self._timeout = timeout
75
+
76
+ @property
77
+ def id(self) -> str:
78
+ """The reference used for shell and file operations."""
79
+ return self._computer
80
+
81
+ @classmethod
82
+ @contextmanager
83
+ def create(
84
+ cls,
85
+ *,
86
+ client: Heaven,
87
+ pool: str,
88
+ name: str | None = None,
89
+ organization: str | None = None,
90
+ ) -> Generator[HeavenSandbox, None, None]:
91
+ """Create a Computer and delete that exact Computer on context exit."""
92
+ computer = _create_computer(client, pool, name, organization)
93
+ try:
94
+ yield cls(client=client, computer=computer)
95
+ finally:
96
+ _delete_computer(client, computer)
97
+
98
+ def execute(self, command: str, *, timeout: int | None = None) -> ExecuteResponse:
99
+ """Collect interleaved output and the guest exit status."""
100
+ seconds = self._timeout if timeout is None else timeout
101
+ if seconds < 0:
102
+ raise ValueError("timeout must be nonnegative")
103
+ # Enforce shorter deadlines in the guest and leave time for the exit frame.
104
+ if seconds:
105
+ command = f"timeout -k 1s {seconds}s sh -c {shlex.quote(command)}"
106
+ output = bytearray()
107
+ truncated = False
108
+ with self._client.exec_stream(
109
+ self.id, command, timeout=min(seconds + 5, 3660) if seconds else 3660
110
+ ) as run:
111
+ for chunk in run:
112
+ remaining = _OUTPUT_LIMIT - len(output)
113
+ output.extend(chunk.data[:remaining])
114
+ truncated |= len(chunk.data) > remaining
115
+ return ExecuteResponse(
116
+ output=output.decode(errors="replace"),
117
+ exit_code=run.exit_code,
118
+ truncated=truncated,
119
+ )
120
+
121
+ def upload_files(self, files: list[tuple[str, bytes]]) -> list[FileUploadResponse]:
122
+ """Create parent directories and return one result per input file."""
123
+ results = []
124
+ for path, data in files:
125
+ error = None
126
+ if not path.startswith("/") or "\x00" in path:
127
+ error = "invalid_path"
128
+ else:
129
+ try:
130
+ parent = posixpath.dirname(path)
131
+ prepared = self.execute(f"mkdir -p -- {shlex.quote(parent)}")
132
+ if prepared.exit_code:
133
+ error = prepared.output.strip() or "invalid_path"
134
+ else:
135
+ self._client.files.upload(self.id, path, data)
136
+ except HeavenError as exc:
137
+ error = _file_error(exc)
138
+ results.append(FileUploadResponse(path=path, error=error))
139
+ return results
140
+
141
+ def download_files(self, paths: list[str]) -> list[FileDownloadResponse]:
142
+ """Read bytes in input order, preserving individual transfer errors."""
143
+ results = []
144
+ for path in paths:
145
+ error = None
146
+ content = None
147
+ if not path.startswith("/") or "\x00" in path:
148
+ error = "invalid_path"
149
+ else:
150
+ try:
151
+ target = io.BytesIO()
152
+ self._client.files.download(self.id, path, target)
153
+ content = target.getvalue()
154
+ except HeavenError as exc:
155
+ error = _file_error(exc)
156
+ results.append(
157
+ FileDownloadResponse(path=path, content=content, error=error)
158
+ )
159
+ return results
@@ -0,0 +1,33 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "langchain-heaven"
7
+ version = "0.1.0"
8
+ license = "Apache-2.0"
9
+ license-files = ["LICENSE"]
10
+ description = "Heaven (heaven.dev) sandbox backend for Deep Agents"
11
+ readme = "README.md"
12
+ requires-python = ">=3.11,<4"
13
+ keywords = ["langchain", "deepagents", "sandbox", "heaven", "ai-agents"]
14
+ dependencies = ["deepagents>=0.7.43,<0.8", "heaven-sdk>=0.1.2,<0.2"]
15
+
16
+ [project.urls]
17
+ Homepage = "https://heaven.dev"
18
+ Documentation = "https://github.com/heavendotdev/langchain-heaven#readme"
19
+ Source = "https://github.com/heavendotdev/langchain-heaven"
20
+
21
+ [project.entry-points."deepagents_code.sandbox_providers"]
22
+ heaven = "langchain_heaven.provider:HeavenProvider"
23
+
24
+ [dependency-groups]
25
+ test = ["pytest>=9.1.1,<10", "pytest-asyncio", "pytest-timeout", "pytest-socket", "langchain-tests>=1.2.0", "ruff", "ty"]
26
+
27
+ [tool.ruff.lint]
28
+ select = ["E4", "E7", "E9", "F", "B", "I", "UP"]
29
+
30
+ [tool.pytest.ini_options]
31
+ asyncio_mode = "auto"
32
+ asyncio_default_fixture_loop_scope = "function"
33
+ filterwarnings = ["error", "ignore:Core Pydantic V1 functionality isn't compatible:UserWarning"]