langchain-withruntime 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,33 @@
1
+ node_modules
2
+ .turbo
3
+ .next
4
+ out
5
+ dist
6
+ build
7
+ .env
8
+ .env*.local
9
+ .env*
10
+ .DS_Store
11
+ *.tsbuildinfo
12
+ .vercel
13
+
14
+ # What a failing Playwright run leaves behind.
15
+ test-results
16
+ playwright-report
17
+
18
+ # Local-only preview config (contains machine-specific paths).
19
+ .claude/launch.json
20
+
21
+ # Worktrees a session opened inside the repo. We do not use them; this is here
22
+ # so that one somebody opens anyway is not committed.
23
+ .claude/worktrees
24
+
25
+ # Python interpreter caches; keep experiment logs and results.
26
+ __pycache__/
27
+ *.pyc
28
+ *.egg-info/
29
+
30
+ # Shared local agent memory; includes machine-specific operational context.
31
+ /.agents/memory/
32
+
33
+ # Screenshots and notes an agent left for Marc to read. Local to this machine.
@@ -0,0 +1,55 @@
1
+ Apache License
2
+
3
+ Version 2.0, January 2004
4
+
5
+ http://www.apache.org/licenses/
6
+
7
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
8
+
9
+ 1. Definitions.
10
+
11
+ "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
14
+
15
+ "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.
16
+
17
+ "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
18
+
19
+ "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
20
+
21
+ "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.
22
+
23
+ "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).
24
+
25
+ "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.
26
+
27
+ "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."
28
+
29
+ "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.
30
+
31
+ 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.
32
+
33
+ 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.
34
+
35
+ 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:
36
+
37
+ You must give any other recipients of the Work or Derivative Works a copy of this License; and
38
+
39
+ You must cause any modified files to carry prominent notices stating that You changed the files; and
40
+
41
+ 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
42
+
43
+ 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.
44
+
45
+ 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.
46
+
47
+ 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.
48
+
49
+ 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.
50
+
51
+ 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.
52
+
53
+ 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.
54
+
55
+ END OF TERMS AND CONDITIONS
@@ -0,0 +1,140 @@
1
+ Metadata-Version: 2.5
2
+ Name: langchain-withruntime
3
+ Version: 0.1.0
4
+ Summary: Runtime sandbox integration for Deep Agents
5
+ Project-URL: Homepage, https://withruntime.com/docs/langchain
6
+ Project-URL: Documentation, https://withruntime.com/docs/langchain
7
+ Author: Runtime LLC
8
+ License: Apache-2.0
9
+ License-File: LICENSE
10
+ Keywords: deepagents,firecracker,langchain,microvm,runtime,sandbox
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: License :: OSI Approved :: Apache Software License
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Programming Language :: Python :: 3.14
18
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
19
+ Requires-Python: <4.0,>=3.11
20
+ Requires-Dist: deepagents<0.8.0,>=0.7.0
21
+ Requires-Dist: withruntime[deepagents]>=0.6.1
22
+ Description-Content-Type: text/markdown
23
+
24
+ # langchain-withruntime
25
+
26
+ [![PyPI - Version](https://img.shields.io/pypi/v/langchain-withruntime?label=%20)](https://pypi.org/project/langchain-withruntime/#history)
27
+ [![PyPI - License](https://img.shields.io/pypi/l/langchain-withruntime)](https://www.apache.org/licenses/LICENSE-2.0)
28
+ [![PyPI - Downloads](https://img.shields.io/pepy/dt/langchain-withruntime)](https://pypistats.org/packages/langchain-withruntime)
29
+
30
+ Runtime sandbox integration for [Deep Agents](https://docs.langchain.com/oss/python/deepagents/overview).
31
+
32
+ [Runtime](https://withruntime.com) runs each sandbox in a Firecracker microVM
33
+ with its own kernel. `RuntimeSandbox` is a Deep Agents sandbox backend: the
34
+ agent's `execute`, `ls`, `read_file`, `write_file`, `edit_file`, `glob` and
35
+ `grep` tools all run in one sandbox.
36
+
37
+ ## Quick install
38
+
39
+ ```bash
40
+ pip install langchain-withruntime
41
+ ```
42
+
43
+ This installs the Runtime SDK, [`withruntime`](https://pypi.org/project/withruntime/),
44
+ and Deep Agents. Set `RUNTIME_API_KEY` to a key from
45
+ https://withruntime.com/account/keys, or run `npx -y withruntime login` once on
46
+ this machine. A new account starts on a free trial with no card.
47
+
48
+ ## Use it
49
+
50
+ ```python
51
+ from deepagents import create_deep_agent
52
+ from withruntime import Sandbox
53
+
54
+ from langchain_withruntime import RuntimeSandbox
55
+
56
+ with Sandbox.create() as sbx:
57
+ agent = create_deep_agent(
58
+ model="anthropic:claude-sonnet-4-6",
59
+ backend=RuntimeSandbox(sbx),
60
+ )
61
+ result = agent.invoke(
62
+ {"messages": [{"role": "user", "content": "Write fib.py, run it, and show the first 10 numbers."}]}
63
+ )
64
+ print(result["messages"][-1].content)
65
+ ```
66
+
67
+ Leaving the `with` block stops the sandbox. The backend works on its own too:
68
+
69
+ ```python
70
+ from withruntime import Sandbox
71
+
72
+ from langchain_withruntime import RuntimeSandbox
73
+
74
+ with Sandbox.create() as sbx:
75
+ backend = RuntimeSandbox(sbx, timeout_seconds=300)
76
+ print(backend.execute("python3 --version").output)
77
+ backend.write("/workspace/notes.txt", "hello\n")
78
+ print(backend.read("/workspace/notes.txt").file_data["content"])
79
+ ```
80
+
81
+ - `timeout_seconds` (default 1800) is the limit for a command that names none;
82
+ a command that runs past it is stopped and its output says so.
83
+ - `max_output_chars` (default 100,000) keeps the end of a longer output and
84
+ marks it truncated.
85
+ - `Sandbox.create()` takes the sandbox's settings: `image`, `region`, `vcpu`,
86
+ `memory_mib`, `timeout_seconds` (its lease), `network` and more. See the
87
+ [Python SDK guide](https://withruntime.com/docs/python).
88
+
89
+ ## Deep Agents Code
90
+
91
+ The package registers a `runtime` sandbox provider for Deep Agents Code:
92
+
93
+ ```bash
94
+ dcode install langchain-withruntime --package
95
+ dcode --sandbox runtime
96
+ ```
97
+
98
+ Each session gets a new sandbox, stopped when the session ends.
99
+ `--sandbox-id <id>` attaches to a sandbox that is already running and leaves it
100
+ running. `RuntimeProvider` is the same
101
+ lifecycle in code:
102
+
103
+ ```python
104
+ from langchain_withruntime import RuntimeProvider
105
+
106
+ provider = RuntimeProvider()
107
+ backend = provider.get_or_create(timeout=900) # a new sandbox with a 15 minute lease
108
+ try:
109
+ print(backend.execute("uname -r").output)
110
+ finally:
111
+ provider.delete(sandbox_id=backend.id)
112
+ ```
113
+
114
+ ## Where it comes from
115
+
116
+ `RuntimeSandbox` is maintained in the Runtime SDK as `withruntime.deepagents`
117
+ (`pip install "withruntime[deepagents]"` gives the same class). This package
118
+ installs it under the `langchain-<provider>` name the other Deep Agents sandbox
119
+ packages use and adds the Deep Agents Code provider.
120
+
121
+ ## Tests
122
+
123
+ ```bash
124
+ pip install -e . pytest pytest-asyncio langchain-tests
125
+ pytest tests/unit_tests # offline
126
+ RUNTIME_API_KEY=... pytest tests/integration_tests # real sandboxes
127
+ RUNTIME_API_KEY=... python scripts/e2e.py # a Deep Agent with a scripted model
128
+ ```
129
+
130
+ The offline tests run LangChain's standard `SandboxIntegrationTests` against a
131
+ stand-in sandbox that executes on the local machine (Linux).
132
+
133
+ ## Documentation
134
+
135
+ - [LangChain, LangGraph and Deep Agents on Runtime](https://withruntime.com/docs/langchain)
136
+ - [Runtime documentation](https://withruntime.com/docs)
137
+
138
+ ## License
139
+
140
+ Apache-2.0
@@ -0,0 +1,117 @@
1
+ # langchain-withruntime
2
+
3
+ [![PyPI - Version](https://img.shields.io/pypi/v/langchain-withruntime?label=%20)](https://pypi.org/project/langchain-withruntime/#history)
4
+ [![PyPI - License](https://img.shields.io/pypi/l/langchain-withruntime)](https://www.apache.org/licenses/LICENSE-2.0)
5
+ [![PyPI - Downloads](https://img.shields.io/pepy/dt/langchain-withruntime)](https://pypistats.org/packages/langchain-withruntime)
6
+
7
+ Runtime sandbox integration for [Deep Agents](https://docs.langchain.com/oss/python/deepagents/overview).
8
+
9
+ [Runtime](https://withruntime.com) runs each sandbox in a Firecracker microVM
10
+ with its own kernel. `RuntimeSandbox` is a Deep Agents sandbox backend: the
11
+ agent's `execute`, `ls`, `read_file`, `write_file`, `edit_file`, `glob` and
12
+ `grep` tools all run in one sandbox.
13
+
14
+ ## Quick install
15
+
16
+ ```bash
17
+ pip install langchain-withruntime
18
+ ```
19
+
20
+ This installs the Runtime SDK, [`withruntime`](https://pypi.org/project/withruntime/),
21
+ and Deep Agents. Set `RUNTIME_API_KEY` to a key from
22
+ https://withruntime.com/account/keys, or run `npx -y withruntime login` once on
23
+ this machine. A new account starts on a free trial with no card.
24
+
25
+ ## Use it
26
+
27
+ ```python
28
+ from deepagents import create_deep_agent
29
+ from withruntime import Sandbox
30
+
31
+ from langchain_withruntime import RuntimeSandbox
32
+
33
+ with Sandbox.create() as sbx:
34
+ agent = create_deep_agent(
35
+ model="anthropic:claude-sonnet-4-6",
36
+ backend=RuntimeSandbox(sbx),
37
+ )
38
+ result = agent.invoke(
39
+ {"messages": [{"role": "user", "content": "Write fib.py, run it, and show the first 10 numbers."}]}
40
+ )
41
+ print(result["messages"][-1].content)
42
+ ```
43
+
44
+ Leaving the `with` block stops the sandbox. The backend works on its own too:
45
+
46
+ ```python
47
+ from withruntime import Sandbox
48
+
49
+ from langchain_withruntime import RuntimeSandbox
50
+
51
+ with Sandbox.create() as sbx:
52
+ backend = RuntimeSandbox(sbx, timeout_seconds=300)
53
+ print(backend.execute("python3 --version").output)
54
+ backend.write("/workspace/notes.txt", "hello\n")
55
+ print(backend.read("/workspace/notes.txt").file_data["content"])
56
+ ```
57
+
58
+ - `timeout_seconds` (default 1800) is the limit for a command that names none;
59
+ a command that runs past it is stopped and its output says so.
60
+ - `max_output_chars` (default 100,000) keeps the end of a longer output and
61
+ marks it truncated.
62
+ - `Sandbox.create()` takes the sandbox's settings: `image`, `region`, `vcpu`,
63
+ `memory_mib`, `timeout_seconds` (its lease), `network` and more. See the
64
+ [Python SDK guide](https://withruntime.com/docs/python).
65
+
66
+ ## Deep Agents Code
67
+
68
+ The package registers a `runtime` sandbox provider for Deep Agents Code:
69
+
70
+ ```bash
71
+ dcode install langchain-withruntime --package
72
+ dcode --sandbox runtime
73
+ ```
74
+
75
+ Each session gets a new sandbox, stopped when the session ends.
76
+ `--sandbox-id <id>` attaches to a sandbox that is already running and leaves it
77
+ running. `RuntimeProvider` is the same
78
+ lifecycle in code:
79
+
80
+ ```python
81
+ from langchain_withruntime import RuntimeProvider
82
+
83
+ provider = RuntimeProvider()
84
+ backend = provider.get_or_create(timeout=900) # a new sandbox with a 15 minute lease
85
+ try:
86
+ print(backend.execute("uname -r").output)
87
+ finally:
88
+ provider.delete(sandbox_id=backend.id)
89
+ ```
90
+
91
+ ## Where it comes from
92
+
93
+ `RuntimeSandbox` is maintained in the Runtime SDK as `withruntime.deepagents`
94
+ (`pip install "withruntime[deepagents]"` gives the same class). This package
95
+ installs it under the `langchain-<provider>` name the other Deep Agents sandbox
96
+ packages use and adds the Deep Agents Code provider.
97
+
98
+ ## Tests
99
+
100
+ ```bash
101
+ pip install -e . pytest pytest-asyncio langchain-tests
102
+ pytest tests/unit_tests # offline
103
+ RUNTIME_API_KEY=... pytest tests/integration_tests # real sandboxes
104
+ RUNTIME_API_KEY=... python scripts/e2e.py # a Deep Agent with a scripted model
105
+ ```
106
+
107
+ The offline tests run LangChain's standard `SandboxIntegrationTests` against a
108
+ stand-in sandbox that executes on the local machine (Linux).
109
+
110
+ ## Documentation
111
+
112
+ - [LangChain, LangGraph and Deep Agents on Runtime](https://withruntime.com/docs/langchain)
113
+ - [Runtime documentation](https://withruntime.com/docs)
114
+
115
+ ## License
116
+
117
+ Apache-2.0
@@ -0,0 +1,27 @@
1
+ """Runtime sandbox integration for LangChain Deep Agents.
2
+
3
+ Runtime (https://withruntime.com) runs each sandbox in a Firecracker microVM.
4
+ `RuntimeSandbox` is a Deep Agents `BaseSandbox`, so the agent's `execute`,
5
+ `ls`, `read_file`, `write_file`, `edit_file`, `glob` and `grep` tools run in
6
+ the sandbox::
7
+
8
+ from deepagents import create_deep_agent
9
+ from withruntime import Sandbox
10
+
11
+ from langchain_withruntime import RuntimeSandbox
12
+
13
+ with Sandbox.create() as sbx:
14
+ agent = create_deep_agent(backend=RuntimeSandbox(sbx))
15
+
16
+ The backend is maintained in the Runtime SDK as `withruntime.deepagents`; this
17
+ package installs it under the `langchain-<provider>` name the other Deep Agents
18
+ sandbox packages use, and adds `RuntimeProvider`, which creates and stops
19
+ sandboxes for Deep Agents Code (`dcode --sandbox runtime`).
20
+ """
21
+
22
+ from withruntime.deepagents import RuntimeSandbox
23
+
24
+ from langchain_withruntime._version import __version__
25
+ from langchain_withruntime.provider import RuntimeProvider
26
+
27
+ __all__ = ["RuntimeProvider", "RuntimeSandbox", "__version__"]
@@ -0,0 +1,3 @@
1
+ """Version information for `langchain-withruntime`."""
2
+
3
+ __version__ = "0.1.0"
@@ -0,0 +1,168 @@
1
+ """Runtime sandbox lifecycle (create, attach, stop) for Deep Agents Code.
2
+
3
+ Installing this package registers the `runtime` provider under the
4
+ `deepagents_code.sandbox_providers` entry point, so `dcode --sandbox runtime`
5
+ creates a Runtime sandbox for the session and stops it at the end.
6
+ `RuntimeProvider` also works without Deep Agents Code, as a small factory for
7
+ `RuntimeSandbox` backends.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import os
13
+ from collections.abc import Callable
14
+ from typing import Any
15
+
16
+ from withruntime import NotFoundError, Runtime
17
+ from withruntime.deepagents import RuntimeSandbox
18
+
19
+ WORKING_DIR = "/workspace"
20
+ """`HOME` and the default working directory in a Runtime sandbox."""
21
+
22
+ EnvResolver = Callable[[str], str | None]
23
+
24
+
25
+ def _default_resolve_env(name: str) -> str | None:
26
+ """Read `name`, letting `DEEPAGENTS_CODE_<name>` override it, as the other providers do."""
27
+ prefixed = f"DEEPAGENTS_CODE_{name}"
28
+ if prefixed in os.environ:
29
+ return os.environ[prefixed] or None
30
+ return os.environ.get(name) or None
31
+
32
+
33
+ def _not_found(sandbox_id: str, cause: BaseException) -> Exception:
34
+ """Deep Agents Code's `SandboxNotFoundError` when it is installed, else `KeyError`."""
35
+ try:
36
+ from deepagents_code.integrations.sandbox_provider import ( # noqa: PLC0415
37
+ SandboxNotFoundError,
38
+ )
39
+ except ImportError:
40
+ error: Exception = KeyError(sandbox_id)
41
+ else:
42
+ error = SandboxNotFoundError(sandbox_id)
43
+ error.__cause__ = cause
44
+ return error
45
+
46
+
47
+ class RuntimeProvider:
48
+ """Create or attach Runtime sandboxes and wrap each in a `RuntimeSandbox`.
49
+
50
+ The key comes from `RUNTIME_API_KEY` (or `DEEPAGENTS_CODE_RUNTIME_API_KEY`),
51
+ and otherwise from this machine's `npx withruntime login`. Pass `client` to
52
+ share a `withruntime.Runtime`.
53
+ """
54
+
55
+ def __init__(
56
+ self,
57
+ *,
58
+ client: Runtime | None = None,
59
+ api_key: str | None = None,
60
+ resolve_env_var: EnvResolver | None = None,
61
+ ) -> None:
62
+ """Initialize the provider.
63
+
64
+ Args:
65
+ client: A `withruntime.Runtime` to use. One is made when omitted.
66
+ api_key: A Runtime API key, when `client` is omitted.
67
+ resolve_env_var: Environment lookup for the key and base URL.
68
+ """
69
+ self._client = client
70
+ self._api_key = api_key
71
+ self._resolve_env = resolve_env_var or _default_resolve_env
72
+
73
+ @property
74
+ def client(self) -> Runtime:
75
+ """The Runtime client, made on first use so constructing needs no key."""
76
+ if self._client is None:
77
+ self._client = Runtime(
78
+ api_key=self._api_key or self._resolve_env("RUNTIME_API_KEY"),
79
+ base_url=self._resolve_env("RUNTIME_API_URL"),
80
+ )
81
+ return self._client
82
+
83
+ @property
84
+ def metadata(self) -> Any:
85
+ """Deep Agents Code's description of this provider, or `None` without it."""
86
+ try:
87
+ from deepagents_code.integrations.sandbox_provider import ( # noqa: PLC0415
88
+ SandboxInstallHint,
89
+ SandboxProviderMetadata,
90
+ )
91
+ except ImportError:
92
+ return None
93
+ return SandboxProviderMetadata(
94
+ name="runtime",
95
+ working_dir=WORKING_DIR,
96
+ install=SandboxInstallHint(kind="package", name="langchain-withruntime"),
97
+ supports_sandbox_id=True,
98
+ supports_snapshot_name=False,
99
+ backend_module="langchain_withruntime",
100
+ )
101
+
102
+ def get_or_create(
103
+ self,
104
+ *,
105
+ sandbox_id: str | None = None,
106
+ timeout: int | None = None,
107
+ command_timeout: int = 1800,
108
+ **fields: Any,
109
+ ) -> RuntimeSandbox:
110
+ """Return a backend on an existing sandbox, or on a new one.
111
+
112
+ Args:
113
+ sandbox_id: An existing sandbox to attach to, or `None` to create one.
114
+ timeout: The new sandbox's lease in seconds (`timeout_seconds`).
115
+ command_timeout: Default seconds for a command that names none.
116
+ **fields: Create fields for a new sandbox, as `Sandbox.create`
117
+ takes them: `funding`, `image`, `region`, `vcpu`, `memory_mib`,
118
+ `name`, `labels` and the rest.
119
+
120
+ Returns:
121
+ A `RuntimeSandbox` on the sandbox.
122
+
123
+ Raises:
124
+ SandboxNotFoundError: `sandbox_id` names no sandbox in this account
125
+ (`KeyError` when Deep Agents Code is not installed).
126
+ TypeError: Create fields were passed with `sandbox_id`.
127
+ """
128
+ if sandbox_id is not None:
129
+ if fields or timeout is not None:
130
+ msg = f"Create fields apply only to a new sandbox: {sorted(fields) or ['timeout']}"
131
+ raise TypeError(msg)
132
+ try:
133
+ sandbox = self.client.sandboxes.get(sandbox_id)
134
+ except NotFoundError as error:
135
+ raise _not_found(sandbox_id, error) from error
136
+ return RuntimeSandbox(sandbox, timeout_seconds=command_timeout)
137
+ if timeout is not None:
138
+ fields["timeout_seconds"] = timeout
139
+ sandbox = self.client.sandboxes.create(**fields)
140
+ return RuntimeSandbox(sandbox, timeout_seconds=command_timeout)
141
+
142
+ def delete(self, *, sandbox_id: str, **kwargs: Any) -> None:
143
+ """Stop a sandbox. Its files go with it unless it was created persistent.
144
+
145
+ Raises:
146
+ SandboxNotFoundError: `sandbox_id` names no sandbox in this account
147
+ (`KeyError` when Deep Agents Code is not installed).
148
+ TypeError: Unsupported arguments were passed.
149
+ """
150
+ if kwargs:
151
+ msg = f"Received unsupported arguments: {sorted(kwargs)}"
152
+ raise TypeError(msg)
153
+ try:
154
+ self.client.sandboxes.get(sandbox_id).stop()
155
+ except NotFoundError as error:
156
+ raise _not_found(sandbox_id, error) from error
157
+
158
+ async def aget_or_create(self, *, sandbox_id: str | None = None, **kwargs: Any) -> RuntimeSandbox:
159
+ """Async `get_or_create`, on a worker thread."""
160
+ import asyncio # noqa: PLC0415
161
+
162
+ return await asyncio.to_thread(self.get_or_create, sandbox_id=sandbox_id, **kwargs)
163
+
164
+ async def adelete(self, *, sandbox_id: str, **kwargs: Any) -> None:
165
+ """Async `delete`, on a worker thread."""
166
+ import asyncio # noqa: PLC0415
167
+
168
+ await asyncio.to_thread(self.delete, sandbox_id=sandbox_id, **kwargs)
@@ -0,0 +1,54 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "langchain-withruntime"
7
+ version = "0.1.0"
8
+ description = "Runtime sandbox integration for Deep Agents"
9
+ readme = "README.md"
10
+ license = { text = "Apache-2.0" }
11
+ authors = [{ name = "Runtime LLC" }]
12
+ keywords = ["langchain", "deepagents", "sandbox", "firecracker", "microvm", "runtime"]
13
+ classifiers = [
14
+ "Intended Audience :: Developers",
15
+ "License :: OSI Approved :: Apache Software License",
16
+ "Programming Language :: Python :: 3",
17
+ "Programming Language :: Python :: 3.11",
18
+ "Programming Language :: Python :: 3.12",
19
+ "Programming Language :: Python :: 3.13",
20
+ "Programming Language :: Python :: 3.14",
21
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
22
+ ]
23
+ requires-python = ">=3.11,<4.0"
24
+ dependencies = [
25
+ "deepagents>=0.7.0,<0.8.0",
26
+ # 0.6.0 and earlier cut long command output at 100,000 characters by
27
+ # default, which broke read_file on files past about 75 KB. 0.6.1 returns it whole.
28
+ "withruntime[deepagents]>=0.6.1",
29
+ ]
30
+
31
+ [project.urls]
32
+ Homepage = "https://withruntime.com/docs/langchain"
33
+ Documentation = "https://withruntime.com/docs/langchain"
34
+
35
+ [project.entry-points."deepagents_code.sandbox_providers"]
36
+ runtime = "langchain_withruntime.provider:RuntimeProvider"
37
+
38
+ [dependency-groups]
39
+ test = [
40
+ "pytest>=9.0.0,<10.0.0",
41
+ "pytest-asyncio>=1.0.0",
42
+ "langchain-tests>=1.1.9",
43
+ ]
44
+
45
+ [tool.hatch.build.targets.wheel]
46
+ packages = ["langchain_withruntime"]
47
+
48
+ [tool.hatch.build.targets.sdist]
49
+ include = ["langchain_withruntime", "tests", "scripts", "README.md", "LICENSE"]
50
+
51
+ [tool.pytest.ini_options]
52
+ addopts = "--strict-markers --strict-config"
53
+ testpaths = ["tests"]
54
+ asyncio_mode = "auto"
@@ -0,0 +1,157 @@
1
+ """End to end against the real API: a Deep Agent works in Runtime sandboxes.
2
+
3
+ RUNTIME_API_KEY=... python scripts/e2e.py
4
+
5
+ `create_deep_agent` runs with a scripted model, so no model is paid for. The
6
+ model calls each of the agent's sandbox tools in turn: `write_file`,
7
+ `edit_file`, `read_file`, `execute`, `ls`, `glob` and `grep`. The script checks
8
+ what every tool returned and then reads the file back through the backend
9
+ itself. It does this twice in each sandbox: under /workspace, which the Files
10
+ API serves, and under /tmp, where files move through a staged copy.
11
+
12
+ Two sandboxes, one after the other, on the account's default funding (the free
13
+ trial while it lasts), each with a ten minute lease so a crashed run cannot
14
+ leave one billing: the first made with `Sandbox.create` and wrapped in
15
+ `RuntimeSandbox`, the second made and stopped by `RuntimeProvider`, as
16
+ Deep Agents Code does. The script stops both and then checks that neither is
17
+ still running. RUNTIME_API_URL points it at another deployment.
18
+
19
+ `drive(backend, root)` is the whole agent run; the offline tests call it on a
20
+ stand-in sandbox. Needs `pip install langchain-withruntime`.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import json
26
+ import os
27
+ import sys
28
+ import uuid
29
+ from collections.abc import Sequence
30
+ from typing import Any
31
+
32
+ from langchain_core.language_models.chat_models import BaseChatModel
33
+ from langchain_core.messages import AIMessage, BaseMessage, ToolMessage
34
+ from langchain_core.outputs import ChatGeneration, ChatResult
35
+ from pydantic import PrivateAttr
36
+
37
+ LEASE_SECONDS = 600
38
+ SOURCE = "def greet(name):\n return 'Hello, ' + name + '!'\n"
39
+ EDITED = SOURCE.replace("Hello", "Hi")
40
+
41
+
42
+ class ScriptedModel(BaseChatModel):
43
+ """A chat model that returns the messages it was given, in order."""
44
+
45
+ script: list[AIMessage]
46
+ _turn: int = PrivateAttr(default=0)
47
+
48
+ @property
49
+ def _llm_type(self) -> str:
50
+ return "scripted"
51
+
52
+ def bind_tools(self, tools: Sequence[Any], **kwargs: Any) -> ScriptedModel: # noqa: ARG002
53
+ return self
54
+
55
+ def _generate(self, messages: list[BaseMessage], stop: Any = None, run_manager: Any = None,
56
+ **kwargs: Any) -> ChatResult:
57
+ message = self.script[min(self._turn, len(self.script) - 1)]
58
+ self._turn += 1
59
+ return ChatResult(generations=[ChatGeneration(message=message)])
60
+
61
+
62
+ def steps(root: str) -> list[tuple[str, dict[str, Any], str]]:
63
+ """Each tool call the model makes, and a string its result must contain."""
64
+ app = f"{root}/app"
65
+ return [
66
+ ("write_file", {"file_path": f"{app}/greet.py", "content": SOURCE}, f"{app}/greet.py"),
67
+ ("edit_file", {"file_path": f"{app}/greet.py", "old_string": "Hello", "new_string": "Hi"}, "greet.py"),
68
+ ("read_file", {"file_path": f"{app}/greet.py"}, "return 'Hi, ' + name"),
69
+ ("execute", {"command": f"cd {root} && python3 -c 'from app.greet import greet; print(greet(\"Runtime\"))'"},
70
+ "Hi, Runtime!"),
71
+ ("ls", {"path": app}, f"{app}/greet.py"),
72
+ ("glob", {"pattern": "**/*.py", "path": root}, f"{app}/greet.py"),
73
+ ("grep", {"pattern": "Hi, ", "path": root, "output_mode": "content"}, "return 'Hi, ' + name"),
74
+ ]
75
+
76
+
77
+ def drive(backend: Any, root: str) -> list[str]:
78
+ """Run a Deep Agent on `backend` under `root`. Returns the failures, none when it worked."""
79
+ from deepagents import create_deep_agent # noqa: PLC0415
80
+
81
+ plan = steps(root)
82
+ calls = [(f"call_{i}", tool, args) for i, (tool, args, _) in enumerate(plan)]
83
+ script = [AIMessage(content="", tool_calls=[{"id": cid, "name": tool, "args": args, "type": "tool_call"}])
84
+ for cid, tool, args in calls]
85
+ script.append(AIMessage(content="Done."))
86
+ agent = create_deep_agent(model=ScriptedModel(script=script), backend=backend,
87
+ system_prompt="Use the sandbox tools.")
88
+ result = agent.invoke({"messages": [{"role": "user", "content": "Write, fix and run greet.py."}]},
89
+ config={"recursion_limit": 60})
90
+ replies = {m.tool_call_id: m for m in result["messages"] if isinstance(m, ToolMessage)}
91
+ failures = []
92
+ for (cid, tool, _), (_, _, expected) in zip(calls, plan, strict=True):
93
+ reply = replies.get(cid)
94
+ text = "" if reply is None else str(reply.content)
95
+ if reply is None or reply.status == "error" or expected not in text:
96
+ failures.append(f"{tool} under {root}: expected {expected!r}, got {text[:300]!r}")
97
+ downloaded = backend.download_files([f"{root}/app/greet.py"])[0]
98
+ if downloaded.error or downloaded.content != EDITED.encode():
99
+ failures.append(f"download under {root}: {downloaded.error or downloaded.content!r}")
100
+ if result["messages"][-1].content != "Done.":
101
+ failures.append(f"the agent did not finish: {result['messages'][-1]!r}")
102
+ return failures
103
+
104
+
105
+ def _run(name: str, backend: Any) -> list[str]:
106
+ failures: list[str] = []
107
+ for root in (f"/workspace/e2e-{uuid.uuid4().hex[:8]}", f"/tmp/e2e-{uuid.uuid4().hex[:8]}"): # noqa: S108
108
+ found = drive(backend, root)
109
+ print(f"{name}: {len(steps(root))} tools under {root}: {'ok' if not found else 'FAILED'}")
110
+ failures += found
111
+ return failures
112
+
113
+
114
+ def main() -> int:
115
+ if not os.environ.get("RUNTIME_API_KEY"):
116
+ print("Set RUNTIME_API_KEY to a Runtime key (a test key) to run this against the real API.")
117
+ return 2
118
+ from withruntime import Runtime # noqa: PLC0415
119
+
120
+ from langchain_withruntime import RuntimeProvider, RuntimeSandbox # noqa: PLC0415
121
+
122
+ run = uuid.uuid4().hex[:8]
123
+ labels = {"purpose": "langchain-withruntime-e2e", "run": run}
124
+ client = Runtime()
125
+ print(f"Running against {client.base_url}, run {run}")
126
+ failures: list[str] = []
127
+ created: list[str] = []
128
+
129
+ sbx = client.sandboxes.create(timeout_seconds=LEASE_SECONDS, labels=labels)
130
+ created.append(sbx.id)
131
+ try:
132
+ failures += _run(f"RuntimeSandbox({sbx.id})", RuntimeSandbox(sbx))
133
+ finally:
134
+ sbx.stop()
135
+
136
+ provider = RuntimeProvider(client=client)
137
+ backend = provider.get_or_create(timeout=LEASE_SECONDS, labels=labels)
138
+ created.append(backend.id)
139
+ try:
140
+ failures += _run(f"RuntimeProvider({backend.id})", backend)
141
+ finally:
142
+ provider.delete(sandbox_id=backend.id)
143
+
144
+ running = [s.id for s in client.sandboxes.list(labels=labels)]
145
+ for sandbox_id in created:
146
+ state = client.sandboxes.get(sandbox_id).state
147
+ print(f"{sandbox_id}: {state}")
148
+ if state not in ("stopped", "stopping"):
149
+ failures.append(f"{sandbox_id} is {state} after the run")
150
+ if running:
151
+ failures.append(f"still listed as live after the run: {running}")
152
+ print(json.dumps({"run": run, "sandboxes": created, "failures": failures}, indent=2))
153
+ return 1 if failures else 0
154
+
155
+
156
+ if __name__ == "__main__":
157
+ sys.exit(main())
File without changes
@@ -0,0 +1,36 @@
1
+ """LangChain's standard sandbox suite against a real Runtime sandbox.
2
+
3
+ RUNTIME_API_KEY=... pytest tests/integration_tests
4
+
5
+ One sandbox on the account's default funding (the free trial while it lasts),
6
+ with a ten minute lease, stopped when the suite ends. Skipped without a key.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import os
12
+ from typing import TYPE_CHECKING
13
+
14
+ import pytest
15
+
16
+ from langchain_withruntime import RuntimeSandbox
17
+ from tests.standard import RuntimeSandboxSuite
18
+
19
+ if TYPE_CHECKING:
20
+ from collections.abc import Iterator
21
+
22
+ from deepagents.backends.protocol import SandboxBackendProtocol
23
+
24
+ pytestmark = pytest.mark.skipif(not os.environ.get("RUNTIME_API_KEY"), reason="RUNTIME_API_KEY is not set")
25
+
26
+
27
+ class TestRuntimeSandboxLive(RuntimeSandboxSuite):
28
+ @pytest.fixture(scope="class")
29
+ def sandbox(self) -> Iterator[SandboxBackendProtocol]:
30
+ from withruntime import Sandbox
31
+
32
+ sbx = Sandbox.create(timeout_seconds=600, labels={"purpose": "langchain-withruntime-tests"})
33
+ try:
34
+ yield RuntimeSandbox(sbx)
35
+ finally:
36
+ sbx.stop()
@@ -0,0 +1,116 @@
1
+ """A stand-in for a Runtime sandbox that runs on this machine, for offline tests.
2
+
3
+ It keeps the two surfaces ``RuntimeSandbox`` uses:
4
+
5
+ - ``exec``: a string runs under ``bash -c`` and a list runs without a shell, as
6
+ the API does. A command past its timeout comes back with ``timed_out`` set
7
+ and no exit code, as the API returns it.
8
+ - ``files``: read, write and remove under ``/workspace``, which the stand-in
9
+ keeps in a temporary directory. The Files API is the only way in to
10
+ ``/workspace`` here, so an argument of a list command that names a path
11
+ under it is mapped to the same directory.
12
+
13
+ Commands run on the host, not in a microVM, so the tests prove the backend's
14
+ protocol and the shell and Python it sends, not the sandbox image.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import os
20
+ import shutil
21
+ import subprocess
22
+ import tempfile
23
+ from pathlib import Path
24
+ from typing import Any
25
+
26
+ from withruntime import CommandResult
27
+ from withruntime._errors import NotFoundError
28
+ from withruntime._errors import RuntimeError as RuntimeCloudError
29
+
30
+ WORKSPACE = "/workspace"
31
+
32
+
33
+ class LocalFiles:
34
+ def __init__(self, root: Path) -> None:
35
+ self.root = root
36
+
37
+ def host(self, path: str) -> Path:
38
+ if not path.startswith(WORKSPACE + "/"):
39
+ msg = f"this stand-in serves {WORKSPACE} only: {path}"
40
+ raise AssertionError(msg)
41
+ return self.root / path[len(WORKSPACE) + 1 :]
42
+
43
+ def read(self, path: str) -> bytes:
44
+ target = self.host(path)
45
+ if target.is_dir():
46
+ msg = f"{path} is a directory"
47
+ raise RuntimeCloudError(msg, code="is_directory", status=400)
48
+ if not target.exists():
49
+ msg = f"{path} does not exist"
50
+ raise NotFoundError(msg, code="file_not_found", status=404)
51
+ return target.read_bytes()
52
+
53
+ def write(self, path: str, data: str | bytes, mode: int | None = None) -> dict[str, Any]:
54
+ target = self.host(path)
55
+ target.parent.mkdir(parents=True, exist_ok=True)
56
+ payload = data.encode() if isinstance(data, str) else bytes(data)
57
+ target.write_bytes(payload)
58
+ if mode is not None:
59
+ target.chmod(mode)
60
+ return {"path": path, "size": len(payload)}
61
+
62
+ def remove(self, path: str, recursive: bool = False) -> bool: # noqa: FBT001, FBT002
63
+ target = self.host(path)
64
+ if target.is_dir() and recursive:
65
+ shutil.rmtree(target)
66
+ return True
67
+ if not target.exists():
68
+ msg = f"{path} does not exist"
69
+ raise NotFoundError(msg, code="file_not_found", status=404)
70
+ target.unlink()
71
+ return True
72
+
73
+
74
+ class LocalSandbox:
75
+ """What ``RuntimeSandbox`` needs of a ``withruntime.Sandbox``, on this machine."""
76
+
77
+ def __init__(self, sandbox_id: str = "sbx-local") -> None:
78
+ self.id = sandbox_id
79
+ self._dir = tempfile.mkdtemp(prefix="runtime-local-sandbox-")
80
+ self.files = LocalFiles(Path(self._dir) / "workspace")
81
+ self.files.root.mkdir()
82
+ self.commands: list[Any] = []
83
+
84
+ def exec(self, command: str | list[str], *, timeout_ms: int | None = None, **_: Any) -> CommandResult:
85
+ self.commands.append(command)
86
+ if isinstance(command, str):
87
+ argv = ["bash", "-c", command]
88
+ else:
89
+ argv = [str(self.files.host(a)) if a.startswith(WORKSPACE + "/") else a for a in command]
90
+ try:
91
+ done = subprocess.run( # noqa: S603
92
+ argv,
93
+ capture_output=True,
94
+ timeout=None if timeout_ms is None else timeout_ms / 1000,
95
+ check=False,
96
+ )
97
+ except subprocess.TimeoutExpired as expired:
98
+ return CommandResult(
99
+ exit_code=None,
100
+ stdout=(expired.stdout or b"").decode(errors="replace"),
101
+ stderr=(expired.stderr or b"").decode(errors="replace"),
102
+ timed_out=True,
103
+ )
104
+ return CommandResult(
105
+ exit_code=done.returncode,
106
+ stdout=done.stdout.decode(errors="replace"),
107
+ stderr=done.stderr.decode(errors="replace"),
108
+ )
109
+
110
+ def close(self) -> None:
111
+ shutil.rmtree(self._dir, ignore_errors=True)
112
+
113
+
114
+ def scratch_root() -> str:
115
+ """A directory outside ``/workspace`` for tests, made fresh."""
116
+ return tempfile.mkdtemp(prefix="runtime-sandbox-ops-") + os.sep
@@ -0,0 +1,49 @@
1
+ """LangChain's standard sandbox suite, with the cases it has not caught up on.
2
+
3
+ langchain-tests 1.1.9, the newest on PyPI on 25 September 2026, predates two
4
+ Deep Agents 0.7 behaviours: `BaseSandbox.write` overwrites an existing file,
5
+ and `glob` returns absolute paths. Seven of its cases fail for any
6
+ `BaseSandbox` on Deep Agents 0.7.19, including one that runs straight on the
7
+ local machine with no Runtime code. They are expected failures here, strict,
8
+ so a suite that catches up shows at once; `test_sandbox.py` checks the Deep
9
+ Agents 0.7 behaviour in their place.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import pytest
15
+ from langchain_tests.integration_tests import SandboxIntegrationTests
16
+
17
+ _SKEW = "langchain-tests 1.1.9 expects {}; Deep Agents 0.7 {}"
18
+ _GLOB = pytest.mark.xfail(strict=True, reason=_SKEW.format("relative glob paths", "returns absolute ones"))
19
+ _WRITE = pytest.mark.xfail(strict=True, reason=_SKEW.format("write to refuse an existing file", "overwrites it"))
20
+
21
+
22
+ class RuntimeSandboxSuite(SandboxIntegrationTests):
23
+ @_WRITE
24
+ def test_write_existing_file_fails(self, sandbox_backend, sandbox_test_root) -> None: # noqa: ANN001
25
+ super().test_write_existing_file_fails(sandbox_backend, sandbox_test_root)
26
+
27
+ @_GLOB
28
+ def test_glob(self, sandbox_backend, sandbox_test_root) -> None: # noqa: ANN001
29
+ super().test_glob(sandbox_backend, sandbox_test_root)
30
+
31
+ @_GLOB
32
+ def test_glob_basic_pattern(self, sandbox_backend, sandbox_test_root) -> None: # noqa: ANN001
33
+ super().test_glob_basic_pattern(sandbox_backend, sandbox_test_root)
34
+
35
+ @_GLOB
36
+ def test_glob_with_directories(self, sandbox_backend, sandbox_test_root) -> None: # noqa: ANN001
37
+ super().test_glob_with_directories(sandbox_backend, sandbox_test_root)
38
+
39
+ @_GLOB
40
+ def test_glob_hidden_files_explicitly(self, sandbox_backend, sandbox_test_root) -> None: # noqa: ANN001
41
+ super().test_glob_hidden_files_explicitly(sandbox_backend, sandbox_test_root)
42
+
43
+ @_GLOB
44
+ def test_glob_with_character_class(self, sandbox_backend, sandbox_test_root) -> None: # noqa: ANN001
45
+ super().test_glob_with_character_class(sandbox_backend, sandbox_test_root)
46
+
47
+ @_GLOB
48
+ def test_glob_with_question_mark(self, sandbox_backend, sandbox_test_root) -> None: # noqa: ANN001
49
+ super().test_glob_with_question_mark(sandbox_backend, sandbox_test_root)
@@ -0,0 +1,25 @@
1
+ from __future__ import annotations
2
+
3
+ import importlib.metadata
4
+
5
+ import withruntime.deepagents
6
+
7
+ import langchain_withruntime
8
+ from langchain_withruntime import RuntimeProvider, RuntimeSandbox
9
+
10
+
11
+ def test_exports() -> None:
12
+ assert langchain_withruntime.__all__ == ["RuntimeProvider", "RuntimeSandbox", "__version__"]
13
+ assert RuntimeSandbox is withruntime.deepagents.RuntimeSandbox
14
+ assert RuntimeProvider.__module__ == "langchain_withruntime.provider"
15
+
16
+
17
+ def test_version_matches_the_distribution() -> None:
18
+ assert langchain_withruntime.__version__ == importlib.metadata.version("langchain-withruntime")
19
+
20
+
21
+ def test_entry_point_names_the_provider() -> None:
22
+ points = importlib.metadata.entry_points(group="deepagents_code.sandbox_providers")
23
+ runtime = [point for point in points if point.name == "runtime"]
24
+ assert len(runtime) == 1
25
+ assert runtime[0].load() is RuntimeProvider
@@ -0,0 +1,120 @@
1
+ """RuntimeProvider against a stand-in client: what it asks the API for."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import importlib.util
6
+ from typing import Any
7
+
8
+ import pytest
9
+ from withruntime import NotFoundError
10
+
11
+ from langchain_withruntime import RuntimeProvider, RuntimeSandbox
12
+
13
+
14
+ class Sandbox:
15
+ def __init__(self, sandbox_id: str) -> None:
16
+ self.id, self.stopped = sandbox_id, False
17
+
18
+ def stop(self) -> None:
19
+ self.stopped = True
20
+
21
+
22
+ class Sandboxes:
23
+ def __init__(self) -> None:
24
+ self.known: dict[str, Sandbox] = {"sbx-old": Sandbox("sbx-old")}
25
+ self.created: list[dict[str, Any]] = []
26
+
27
+ def create(self, **fields: Any) -> Sandbox:
28
+ self.created.append(fields)
29
+ sandbox = Sandbox(f"sbx-{len(self.created)}")
30
+ self.known[sandbox.id] = sandbox
31
+ return sandbox
32
+
33
+ def get(self, sandbox_id: str) -> Sandbox:
34
+ if sandbox_id not in self.known:
35
+ raise NotFoundError("no such sandbox", code="sandbox_not_found", status=404)
36
+ return self.known[sandbox_id]
37
+
38
+
39
+ class Client:
40
+ def __init__(self) -> None:
41
+ self.sandboxes = Sandboxes()
42
+
43
+
44
+ HAVE_DCODE = importlib.util.find_spec("deepagents_code") is not None
45
+
46
+
47
+ def test_creates_with_the_lease_and_fields_and_stops() -> None:
48
+ client = Client()
49
+ provider = RuntimeProvider(client=client) # type: ignore[arg-type]
50
+ backend = provider.get_or_create(timeout=900, command_timeout=60, image="python:3.12", labels={"a": "b"})
51
+ assert isinstance(backend, RuntimeSandbox)
52
+ assert backend.id == "sbx-1"
53
+ assert backend.timeout_seconds == 60
54
+ assert client.sandboxes.created == [{"image": "python:3.12", "labels": {"a": "b"}, "timeout_seconds": 900}]
55
+ provider.delete(sandbox_id="sbx-1")
56
+ assert client.sandboxes.known["sbx-1"].stopped
57
+
58
+
59
+ def test_creates_with_no_fields() -> None:
60
+ client = Client()
61
+ RuntimeProvider(client=client).get_or_create() # type: ignore[arg-type]
62
+ assert client.sandboxes.created == [{}]
63
+
64
+
65
+ def test_attaches_without_creating() -> None:
66
+ client = Client()
67
+ backend = RuntimeProvider(client=client).get_or_create(sandbox_id="sbx-old") # type: ignore[arg-type]
68
+ assert backend.id == "sbx-old"
69
+ assert client.sandboxes.created == []
70
+ with pytest.raises(TypeError):
71
+ RuntimeProvider(client=client).get_or_create(sandbox_id="sbx-old", image="x") # type: ignore[arg-type]
72
+
73
+
74
+ def test_missing_sandbox() -> None:
75
+ provider = RuntimeProvider(client=Client()) # type: ignore[arg-type]
76
+ expected: type[Exception] = KeyError
77
+ if HAVE_DCODE:
78
+ from deepagents_code.integrations.sandbox_provider import SandboxNotFoundError
79
+
80
+ expected = SandboxNotFoundError
81
+ with pytest.raises(expected):
82
+ provider.get_or_create(sandbox_id="sbx-none")
83
+ with pytest.raises(expected):
84
+ provider.delete(sandbox_id="sbx-none")
85
+ with pytest.raises(TypeError):
86
+ provider.delete(sandbox_id="sbx-old", force=True)
87
+
88
+
89
+ def test_constructing_needs_no_key(monkeypatch: pytest.MonkeyPatch) -> None:
90
+ monkeypatch.delenv("RUNTIME_API_KEY", raising=False)
91
+ RuntimeProvider()
92
+
93
+
94
+ def test_key_from_the_prefixed_variable(monkeypatch: pytest.MonkeyPatch) -> None:
95
+ monkeypatch.setenv("RUNTIME_API_KEY", "rt_plain")
96
+ monkeypatch.setenv("DEEPAGENTS_CODE_RUNTIME_API_KEY", "rt_prefixed")
97
+ assert RuntimeProvider().client._t._key == "rt_prefixed" # noqa: SLF001
98
+
99
+
100
+ async def test_async_wrappers() -> None:
101
+ client = Client()
102
+ provider = RuntimeProvider(client=client) # type: ignore[arg-type]
103
+ backend = await provider.aget_or_create(timeout=60)
104
+ await provider.adelete(sandbox_id=backend.id)
105
+ assert client.sandboxes.known[backend.id].stopped
106
+
107
+
108
+ @pytest.mark.skipif(not HAVE_DCODE, reason="Deep Agents Code is not installed")
109
+ def test_deep_agents_code_finds_the_provider() -> None:
110
+ from deepagents_code.integrations.sandbox_config import SandboxConfig
111
+ from deepagents_code.integrations.sandbox_registry import SandboxRegistry
112
+
113
+ registry = SandboxRegistry(config=SandboxConfig(), include_entry_points=True)
114
+ assert "runtime" in registry.available_providers()
115
+ metadata = registry.get_metadata("runtime")
116
+ assert metadata is not None
117
+ assert metadata.working_dir == "/workspace"
118
+ assert metadata.install is not None
119
+ assert metadata.install.command(in_app=False) == "dcode install langchain-withruntime --package"
120
+ assert isinstance(registry.create_provider("runtime"), RuntimeProvider)
@@ -0,0 +1,82 @@
1
+ """A Deep Agent's whole tool loop on RuntimeSandbox, offline.
2
+
3
+ `scripts/e2e.py` drives `create_deep_agent` with a scripted model through
4
+ `write_file`, `edit_file`, `read_file`, `execute`, `ls`, `glob` and `grep`.
5
+ Here the same run goes to the stand-in sandbox, so the script is proven before
6
+ it spends a real sandbox.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import importlib.util
12
+ import shutil
13
+ import sys
14
+ from pathlib import Path
15
+
16
+ import pytest
17
+
18
+ from langchain_withruntime import RuntimeSandbox
19
+ from tests.local_sandbox import LocalSandbox, scratch_root
20
+
21
+ pytestmark = pytest.mark.skipif(
22
+ not sys.platform.startswith("linux") or not shutil.which("bash") or not shutil.which("python3"),
23
+ reason="the stand-in runs BaseSandbox's GNU shell and python3 commands on this machine",
24
+ )
25
+
26
+ _spec = importlib.util.spec_from_file_location("e2e", Path(__file__).parents[2] / "scripts" / "e2e.py")
27
+ assert _spec is not None
28
+ assert _spec.loader is not None
29
+ e2e = importlib.util.module_from_spec(_spec)
30
+ sys.modules["e2e"] = e2e # pydantic resolves the scripted model's annotations through it
31
+ _spec.loader.exec_module(e2e)
32
+
33
+
34
+ @pytest.fixture
35
+ def local() -> LocalSandbox:
36
+ sandbox = LocalSandbox()
37
+ yield sandbox
38
+ sandbox.close()
39
+
40
+
41
+ def test_a_deep_agent_uses_every_sandbox_tool(local: LocalSandbox) -> None:
42
+ root = scratch_root().rstrip("/")
43
+ try:
44
+ assert e2e.drive(RuntimeSandbox(local), root) == []
45
+ finally:
46
+ shutil.rmtree(root, ignore_errors=True)
47
+ # Outside /workspace, each write went through a staged copy that was removed.
48
+ staging = local.files.root / ".deepagents-staging"
49
+ assert not staging.exists() or not any(staging.iterdir())
50
+
51
+
52
+ def test_write_overwrites_and_glob_returns_absolute_paths(local: LocalSandbox) -> None:
53
+ """The Deep Agents 0.7 behaviour that langchain-tests 1.1.9 still expects otherwise."""
54
+ root = scratch_root().rstrip("/")
55
+ backend = RuntimeSandbox(local)
56
+ try:
57
+ assert backend.write(f"{root}/a.txt", "one").error is None
58
+ assert backend.write(f"{root}/a.txt", "two").error is None
59
+ assert backend.download_files([f"{root}/a.txt"])[0].content == b"two"
60
+ found = backend.glob("*.txt", path=root)
61
+ assert found.error is None
62
+ assert [m["path"] for m in found.matches or []] == [f"{root}/a.txt"]
63
+ finally:
64
+ shutil.rmtree(root, ignore_errors=True)
65
+
66
+
67
+ def test_long_output_is_returned_whole(local: LocalSandbox) -> None:
68
+ """Deep Agents' read_file parses one JSON line; a cut output broke files past about 75 KB."""
69
+ root = scratch_root().rstrip("/")
70
+ backend = RuntimeSandbox(local)
71
+ try:
72
+ text = "".join(f"line {i:06d} " + "x" * 90 + "\n" for i in range(1500)) # about 150 KB
73
+ assert backend.write(f"{root}/big.txt", text).error is None
74
+ read = backend.read(f"{root}/big.txt", limit=2000)
75
+ assert read.error is None
76
+ assert read.file_data is not None
77
+ assert "line 001499" in read.file_data["content"]
78
+ response = backend.execute(f"cat {root}/big.txt")
79
+ assert response.truncated is False
80
+ assert len(response.output) == len(text)
81
+ finally:
82
+ shutil.rmtree(root, ignore_errors=True)
@@ -0,0 +1,48 @@
1
+ """LangChain's standard sandbox tests, offline, against a stand-in sandbox.
2
+
3
+ `SandboxIntegrationTests` is the suite a Deep Agents sandbox backend is held
4
+ to (see `tests/standard.py` for the seven cases it has not caught up on). Here it drives `RuntimeSandbox` over `LocalSandbox`, which runs commands on
5
+ this machine and serves `/workspace` from a temporary directory, so the suite
6
+ checks every protocol method and the commands `BaseSandbox` sends, with no
7
+ account and no network. `tests/integration_tests` runs the same suite against
8
+ the real API.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import shutil
14
+ import sys
15
+ from typing import TYPE_CHECKING
16
+
17
+ import pytest
18
+
19
+ from langchain_withruntime import RuntimeSandbox
20
+ from tests.local_sandbox import LocalSandbox, scratch_root
21
+ from tests.standard import RuntimeSandboxSuite
22
+
23
+ if TYPE_CHECKING:
24
+ from collections.abc import Iterator
25
+
26
+ from deepagents.backends.protocol import SandboxBackendProtocol
27
+
28
+ pytestmark = pytest.mark.skipif(
29
+ not sys.platform.startswith("linux") or not shutil.which("bash") or not shutil.which("python3"),
30
+ reason="the stand-in runs BaseSandbox's GNU shell and python3 commands on this machine",
31
+ )
32
+
33
+
34
+ class TestRuntimeSandboxStandard(RuntimeSandboxSuite):
35
+ _root = scratch_root()
36
+
37
+ @property
38
+ def sandbox_root_dir(self) -> str:
39
+ return self._root
40
+
41
+ @pytest.fixture(scope="class")
42
+ def sandbox(self) -> Iterator[SandboxBackendProtocol]:
43
+ local = LocalSandbox()
44
+ try:
45
+ yield RuntimeSandbox(local)
46
+ finally:
47
+ local.close()
48
+ shutil.rmtree(self._root, ignore_errors=True)