e2b-acp 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.
- e2b_acp-0.1.0/LICENSE +201 -0
- e2b_acp-0.1.0/PKG-INFO +95 -0
- e2b_acp-0.1.0/README.md +79 -0
- e2b_acp-0.1.0/e2b_acp/__init__.py +201 -0
- e2b_acp-0.1.0/e2b_acp/consts.py +22 -0
- e2b_acp-0.1.0/e2b_acp/exceptions.py +5 -0
- e2b_acp-0.1.0/e2b_acp/transport.py +264 -0
- e2b_acp-0.1.0/e2b_acp/types.py +25 -0
- e2b_acp-0.1.0/e2b_acp/utils.py +156 -0
- e2b_acp-0.1.0/pyproject.toml +45 -0
- e2b_acp-0.1.0/pyproject.toml.orig +42 -0
e2b_acp-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2023 FoundryLabs, Inc.
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
e2b_acp-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: e2b-acp
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Run Agent Client Protocol (ACP) agents in E2B sandboxes
|
|
5
|
+
Author: e2b
|
|
6
|
+
Author-email: e2b <hello@e2b.dev>
|
|
7
|
+
License-Expression: Apache-2.0
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Requires-Dist: e2b>=2.62.0,<3.0.0
|
|
10
|
+
Requires-Dist: agent-client-protocol>=0.12.1,<0.13
|
|
11
|
+
Requires-Python: >=3.11
|
|
12
|
+
Project-URL: Homepage, https://e2b.dev/docs/agents/acp?utm_source=pypi&utm_medium=referral&utm_campaign=package_homepage&utm_content=e2b-acp
|
|
13
|
+
Project-URL: Repository, https://github.com/e2b-dev/e2b/tree/main/packages/acp-python
|
|
14
|
+
Project-URL: Bug Tracker, https://github.com/e2b-dev/e2b/issues
|
|
15
|
+
Description-Content-Type: text/markdown
|
|
16
|
+
|
|
17
|
+
# E2B ACP
|
|
18
|
+
|
|
19
|
+
Run [Agent Client Protocol](https://agentclientprotocol.com) (ACP) agents such as goose, OpenCode or Claude Code inside an [E2B](https://e2b.dev) sandbox, and drive them from your code with the official ACP client.
|
|
20
|
+
|
|
21
|
+
Source: [packages/acp-python](https://github.com/e2b-dev/E2B/tree/main/packages/acp-python)
|
|
22
|
+
|
|
23
|
+
## Install
|
|
24
|
+
|
|
25
|
+
```
|
|
26
|
+
pip install e2b e2b-acp agent-client-protocol
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
Set `E2B_API_KEY` to your [E2B API key](https://e2b.dev/dashboard?tab=keys), and the provider key the agent needs.
|
|
30
|
+
|
|
31
|
+
## Usage
|
|
32
|
+
|
|
33
|
+
Create a sandbox from a template with the agent installed, then start the agent and connect your ACP client to it. The ACP Python SDK is asynchronous, so use `AsyncSandbox`.
|
|
34
|
+
|
|
35
|
+
```python
|
|
36
|
+
import asyncio
|
|
37
|
+
import os
|
|
38
|
+
|
|
39
|
+
import acp
|
|
40
|
+
from acp import schema
|
|
41
|
+
from e2b import AsyncSandbox
|
|
42
|
+
from e2b_acp import AsyncACPAgent
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class Client:
|
|
46
|
+
async def request_permission(self, session_id, tool_call, options, **kwargs):
|
|
47
|
+
allow = next((o for o in options if o.kind == "allow_once"), options[0])
|
|
48
|
+
return schema.RequestPermissionResponse(
|
|
49
|
+
outcome=schema.AllowedOutcome(outcome="selected", option_id=allow.option_id)
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
async def session_update(self, session_id, update, **kwargs):
|
|
53
|
+
if isinstance(update, schema.AgentMessageChunk) and update.content.type == "text":
|
|
54
|
+
print(update.content.text, end="")
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
async def main():
|
|
58
|
+
sandbox = await AsyncSandbox.create("goose", timeout=600)
|
|
59
|
+
try:
|
|
60
|
+
agent = AsyncACPAgent(
|
|
61
|
+
sandbox,
|
|
62
|
+
"goose acp --with-builtin developer",
|
|
63
|
+
Client(),
|
|
64
|
+
envs={
|
|
65
|
+
"GOOSE_PROVIDER": "openai",
|
|
66
|
+
"GOOSE_MODEL": "gpt-5.6-luna",
|
|
67
|
+
"OPENAI_API_KEY": os.environ["OPENAI_API_KEY"],
|
|
68
|
+
},
|
|
69
|
+
)
|
|
70
|
+
await agent.start()
|
|
71
|
+
await agent.connection.initialize(protocol_version=acp.PROTOCOL_VERSION)
|
|
72
|
+
session = await agent.connection.new_session(cwd="/home/user", mcp_servers=[])
|
|
73
|
+
await agent.connection.prompt(
|
|
74
|
+
session_id=session.session_id,
|
|
75
|
+
prompt=[acp.text_block("Create fizzbuzz.py for 1 to 15 and run it.")],
|
|
76
|
+
)
|
|
77
|
+
await agent.stop()
|
|
78
|
+
finally:
|
|
79
|
+
await sandbox.kill()
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
asyncio.run(main())
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
## Where the agent's tools run
|
|
86
|
+
|
|
87
|
+
The agent talks ACP over its stdin and stdout. `AsyncACPAgent` turns off the client filesystem and terminal capabilities in `initialize` and answers agent requests for `fs/*` or `terminal/*` with an error, so the agent edits files and runs commands with its own tools inside the sandbox. It does not restrict the agent's network access or the MCP servers you pass to it.
|
|
88
|
+
|
|
89
|
+
## Lifecycle
|
|
90
|
+
|
|
91
|
+
- `AsyncACPAgent(...)` only stores the arguments; `await agent.start()` starts the agent and connects the client. `start()` can be called once.
|
|
92
|
+
- `agent.stop()` sends EOF to the agent and kills it if it has not exited within `timeout` (5 seconds by default) of the call. Messages the agent sends after that are not delivered. Before `start()` it does nothing, so it is safe in a `finally` block. While `start()` is still running, `stop()` and `kill()` wait for it and then stop the agent; the stop timeout counts from when the start finishes.
|
|
93
|
+
- `agent.wait()` returns the exit code once the agent exits. It raises `ACPException` if the agent sent a message over `max_message_bytes`.
|
|
94
|
+
- If the agent exits, pending requests on the connection fail with a connection error. Use `agent.wait()` for the exit code and pass `on_stderr` to receive the agent's logs.
|
|
95
|
+
- The agent runs as long as the sandbox does, so set the sandbox timeout for the longest task you expect.
|
e2b_acp-0.1.0/README.md
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
# E2B ACP
|
|
2
|
+
|
|
3
|
+
Run [Agent Client Protocol](https://agentclientprotocol.com) (ACP) agents such as goose, OpenCode or Claude Code inside an [E2B](https://e2b.dev) sandbox, and drive them from your code with the official ACP client.
|
|
4
|
+
|
|
5
|
+
Source: [packages/acp-python](https://github.com/e2b-dev/E2B/tree/main/packages/acp-python)
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
```
|
|
10
|
+
pip install e2b e2b-acp agent-client-protocol
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
Set `E2B_API_KEY` to your [E2B API key](https://e2b.dev/dashboard?tab=keys), and the provider key the agent needs.
|
|
14
|
+
|
|
15
|
+
## Usage
|
|
16
|
+
|
|
17
|
+
Create a sandbox from a template with the agent installed, then start the agent and connect your ACP client to it. The ACP Python SDK is asynchronous, so use `AsyncSandbox`.
|
|
18
|
+
|
|
19
|
+
```python
|
|
20
|
+
import asyncio
|
|
21
|
+
import os
|
|
22
|
+
|
|
23
|
+
import acp
|
|
24
|
+
from acp import schema
|
|
25
|
+
from e2b import AsyncSandbox
|
|
26
|
+
from e2b_acp import AsyncACPAgent
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class Client:
|
|
30
|
+
async def request_permission(self, session_id, tool_call, options, **kwargs):
|
|
31
|
+
allow = next((o for o in options if o.kind == "allow_once"), options[0])
|
|
32
|
+
return schema.RequestPermissionResponse(
|
|
33
|
+
outcome=schema.AllowedOutcome(outcome="selected", option_id=allow.option_id)
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
async def session_update(self, session_id, update, **kwargs):
|
|
37
|
+
if isinstance(update, schema.AgentMessageChunk) and update.content.type == "text":
|
|
38
|
+
print(update.content.text, end="")
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
async def main():
|
|
42
|
+
sandbox = await AsyncSandbox.create("goose", timeout=600)
|
|
43
|
+
try:
|
|
44
|
+
agent = AsyncACPAgent(
|
|
45
|
+
sandbox,
|
|
46
|
+
"goose acp --with-builtin developer",
|
|
47
|
+
Client(),
|
|
48
|
+
envs={
|
|
49
|
+
"GOOSE_PROVIDER": "openai",
|
|
50
|
+
"GOOSE_MODEL": "gpt-5.6-luna",
|
|
51
|
+
"OPENAI_API_KEY": os.environ["OPENAI_API_KEY"],
|
|
52
|
+
},
|
|
53
|
+
)
|
|
54
|
+
await agent.start()
|
|
55
|
+
await agent.connection.initialize(protocol_version=acp.PROTOCOL_VERSION)
|
|
56
|
+
session = await agent.connection.new_session(cwd="/home/user", mcp_servers=[])
|
|
57
|
+
await agent.connection.prompt(
|
|
58
|
+
session_id=session.session_id,
|
|
59
|
+
prompt=[acp.text_block("Create fizzbuzz.py for 1 to 15 and run it.")],
|
|
60
|
+
)
|
|
61
|
+
await agent.stop()
|
|
62
|
+
finally:
|
|
63
|
+
await sandbox.kill()
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
asyncio.run(main())
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
## Where the agent's tools run
|
|
70
|
+
|
|
71
|
+
The agent talks ACP over its stdin and stdout. `AsyncACPAgent` turns off the client filesystem and terminal capabilities in `initialize` and answers agent requests for `fs/*` or `terminal/*` with an error, so the agent edits files and runs commands with its own tools inside the sandbox. It does not restrict the agent's network access or the MCP servers you pass to it.
|
|
72
|
+
|
|
73
|
+
## Lifecycle
|
|
74
|
+
|
|
75
|
+
- `AsyncACPAgent(...)` only stores the arguments; `await agent.start()` starts the agent and connects the client. `start()` can be called once.
|
|
76
|
+
- `agent.stop()` sends EOF to the agent and kills it if it has not exited within `timeout` (5 seconds by default) of the call. Messages the agent sends after that are not delivered. Before `start()` it does nothing, so it is safe in a `finally` block. While `start()` is still running, `stop()` and `kill()` wait for it and then stop the agent; the stop timeout counts from when the start finishes.
|
|
77
|
+
- `agent.wait()` returns the exit code once the agent exits. It raises `ACPException` if the agent sent a message over `max_message_bytes`.
|
|
78
|
+
- If the agent exits, pending requests on the connection fail with a connection error. Use `agent.wait()` for the exit code and pass `on_stderr` to receive the agent's logs.
|
|
79
|
+
- The agent runs as long as the sandbox does, so set the sandbox timeout for the longest task you expect.
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Run [Agent Client Protocol](https://agentclientprotocol.com) agents in E2B sandboxes.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import contextlib
|
|
7
|
+
from typing import Callable, Dict, Optional, Tuple, Union, cast
|
|
8
|
+
|
|
9
|
+
import acp
|
|
10
|
+
from acp.core import ClientSideConnection
|
|
11
|
+
from e2b import AsyncSandbox
|
|
12
|
+
from e2b.connection_config import Username
|
|
13
|
+
|
|
14
|
+
from .consts import DEFAULT_MAX_MESSAGE_BYTES, DEFAULT_STOP_TIMEOUT
|
|
15
|
+
from .exceptions import ACPException
|
|
16
|
+
from .transport import ACPTransport
|
|
17
|
+
from .types import ACPAgentResult, StderrHandler
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class AsyncACPAgent:
|
|
21
|
+
"""
|
|
22
|
+
ACP agent running in a sandbox, connected to your client.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
def __init__(
|
|
26
|
+
self,
|
|
27
|
+
sandbox: AsyncSandbox,
|
|
28
|
+
command: str,
|
|
29
|
+
client: Union[acp.Client, Callable[[acp.Agent], acp.Client]],
|
|
30
|
+
*,
|
|
31
|
+
cwd: Optional[str] = None,
|
|
32
|
+
envs: Optional[Dict[str, str]] = None,
|
|
33
|
+
user: Optional[Username] = None,
|
|
34
|
+
on_stderr: Optional[StderrHandler] = None,
|
|
35
|
+
max_message_bytes: int = DEFAULT_MAX_MESSAGE_BYTES,
|
|
36
|
+
request_timeout: Optional[float] = None,
|
|
37
|
+
):
|
|
38
|
+
"""
|
|
39
|
+
Create an ACP agent for the sandbox. Call `start()` to run it and
|
|
40
|
+
connect your ACP client to it over the agent's stdin/stdout.
|
|
41
|
+
|
|
42
|
+
The client filesystem and terminal capabilities are turned off in
|
|
43
|
+
`initialize`, and agent requests for `fs/*` or `terminal/*` are answered
|
|
44
|
+
with an error without reaching your client, so the agent edits files and
|
|
45
|
+
runs commands with its own tools in the sandbox. Network access and MCP
|
|
46
|
+
servers you pass to the agent are not restricted.
|
|
47
|
+
|
|
48
|
+
```python
|
|
49
|
+
import acp
|
|
50
|
+
from e2b import AsyncSandbox
|
|
51
|
+
from e2b_acp import AsyncACPAgent
|
|
52
|
+
|
|
53
|
+
sandbox = await AsyncSandbox.create("goose")
|
|
54
|
+
agent = AsyncACPAgent(sandbox, "goose acp", client)
|
|
55
|
+
await agent.start()
|
|
56
|
+
await agent.connection.initialize(protocol_version=acp.PROTOCOL_VERSION)
|
|
57
|
+
# ...
|
|
58
|
+
await agent.stop()
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
:param sandbox: Sandbox with the agent installed
|
|
62
|
+
:param command: Command that starts the agent in ACP mode, for example `goose acp`
|
|
63
|
+
:param client: Your ACP client instance, or a function that takes the agent connection and returns one. It answers permission requests and receives the agent's session updates
|
|
64
|
+
:param cwd: Working directory of the agent
|
|
65
|
+
:param envs: Environment variables for the agent
|
|
66
|
+
:param user: User to run the agent as
|
|
67
|
+
:param on_stderr: Callback for the agent's stderr output (logs). The agent's stdout is reserved for the protocol
|
|
68
|
+
:param max_message_bytes: Maximum size of a single message from the agent in **bytes**; defaults to ``DEFAULT_MAX_MESSAGE_BYTES`` (32 MiB)
|
|
69
|
+
:param request_timeout: Timeout for starting the agent in **seconds**
|
|
70
|
+
"""
|
|
71
|
+
self._sandbox = sandbox
|
|
72
|
+
self._command = command
|
|
73
|
+
self._client = client
|
|
74
|
+
self._cwd = cwd
|
|
75
|
+
self._envs = envs
|
|
76
|
+
self._user = user
|
|
77
|
+
self._on_stderr = on_stderr
|
|
78
|
+
self._max_message_bytes = max_message_bytes
|
|
79
|
+
self._request_timeout = request_timeout
|
|
80
|
+
self._start_done: Optional[asyncio.Event] = None
|
|
81
|
+
self._transport: Optional[ACPTransport] = None
|
|
82
|
+
self._connection: Optional[ClientSideConnection] = None
|
|
83
|
+
|
|
84
|
+
async def start(self) -> None:
|
|
85
|
+
"""
|
|
86
|
+
Start the agent in the sandbox and connect your ACP client to it.
|
|
87
|
+
|
|
88
|
+
:raises InvalidArgumentException: If `max_message_bytes` is not a positive integer
|
|
89
|
+
:raises SandboxException: If the agent could not be started. Later, the
|
|
90
|
+
connection fails with an `ACPException` if the agent exits with a
|
|
91
|
+
non-zero code or sends a message over `max_message_bytes`
|
|
92
|
+
:raises RuntimeError: If `start()` was already called
|
|
93
|
+
"""
|
|
94
|
+
if self._start_done is not None:
|
|
95
|
+
raise RuntimeError("ACP agent was already started")
|
|
96
|
+
self._start_done = asyncio.Event()
|
|
97
|
+
try:
|
|
98
|
+
await self._start_transport()
|
|
99
|
+
finally:
|
|
100
|
+
self._start_done.set()
|
|
101
|
+
|
|
102
|
+
async def _start_transport(self) -> None:
|
|
103
|
+
transport = ACPTransport(
|
|
104
|
+
self._sandbox, self._max_message_bytes, self._on_stderr
|
|
105
|
+
)
|
|
106
|
+
await transport.start(
|
|
107
|
+
self._command, self._envs, self._user, self._cwd, self._request_timeout
|
|
108
|
+
)
|
|
109
|
+
try:
|
|
110
|
+
# connect_to_agent passes a factory on to ClientSideConnection, which
|
|
111
|
+
# accepts it, but annotates `client` as a client only.
|
|
112
|
+
self._connection = acp.connect_to_agent(
|
|
113
|
+
cast(acp.Client, self._client), transport
|
|
114
|
+
)
|
|
115
|
+
except BaseException:
|
|
116
|
+
with contextlib.suppress(Exception):
|
|
117
|
+
await transport.kill()
|
|
118
|
+
raise
|
|
119
|
+
self._transport = transport
|
|
120
|
+
|
|
121
|
+
async def _start_settled(self) -> None:
|
|
122
|
+
# A start() in flight has no transport yet, so stop() and kill() wait
|
|
123
|
+
# for it. Its error belongs to the start() caller.
|
|
124
|
+
if self._start_done is not None:
|
|
125
|
+
await self._start_done.wait()
|
|
126
|
+
|
|
127
|
+
def _running(self) -> Tuple[ACPTransport, ClientSideConnection]:
|
|
128
|
+
if self._transport is None or self._connection is None:
|
|
129
|
+
raise RuntimeError("ACP agent is not started, call start() first")
|
|
130
|
+
return self._transport, self._connection
|
|
131
|
+
|
|
132
|
+
@property
|
|
133
|
+
def connection(self) -> ClientSideConnection:
|
|
134
|
+
"""
|
|
135
|
+
Connection to the agent. Use it to initialize, create sessions and send prompts.
|
|
136
|
+
"""
|
|
137
|
+
return self._running()[1]
|
|
138
|
+
|
|
139
|
+
@property
|
|
140
|
+
def pid(self) -> int:
|
|
141
|
+
"""
|
|
142
|
+
Process ID of the agent in the sandbox.
|
|
143
|
+
"""
|
|
144
|
+
return self._running()[0].pid
|
|
145
|
+
|
|
146
|
+
async def wait(self) -> ACPAgentResult:
|
|
147
|
+
"""
|
|
148
|
+
Wait for the agent process to exit.
|
|
149
|
+
|
|
150
|
+
A non-zero exit is returned, not raised. If the agent's output stream
|
|
151
|
+
failed before the exit status was known (for example, a message over
|
|
152
|
+
`max_message_bytes`, or an exception raised by `on_stderr`), that
|
|
153
|
+
original error is raised instead.
|
|
154
|
+
|
|
155
|
+
:return: `ACPAgentResult` with the agent's `exit_code` and, if the process failed, its `error` message
|
|
156
|
+
"""
|
|
157
|
+
return await self._running()[0].wait()
|
|
158
|
+
|
|
159
|
+
async def stop(
|
|
160
|
+
self,
|
|
161
|
+
*,
|
|
162
|
+
timeout: float = DEFAULT_STOP_TIMEOUT,
|
|
163
|
+
request_timeout: Optional[float] = None,
|
|
164
|
+
) -> None:
|
|
165
|
+
"""
|
|
166
|
+
Stop the agent: send EOF to its stdin and kill it if it has not
|
|
167
|
+
exited within `timeout` of this call. Messages the agent sends after
|
|
168
|
+
this call are not delivered. It does nothing if the agent is not running.
|
|
169
|
+
If `start()` is still running, it waits for it and then stops the agent;
|
|
170
|
+
`timeout` then counts from when the start finishes.
|
|
171
|
+
|
|
172
|
+
:param timeout: Time for the agent to exit in **seconds**; defaults to ``DEFAULT_STOP_TIMEOUT`` (5 seconds)
|
|
173
|
+
:param request_timeout: Timeout for the request that closes the agent's stdin in **seconds**
|
|
174
|
+
|
|
175
|
+
:raises SandboxException: If the agent could not be killed
|
|
176
|
+
"""
|
|
177
|
+
await self._start_settled()
|
|
178
|
+
if self._transport is not None:
|
|
179
|
+
await self._transport.close(timeout, request_timeout)
|
|
180
|
+
|
|
181
|
+
async def kill(self) -> bool:
|
|
182
|
+
"""
|
|
183
|
+
Kill the agent process with `SIGKILL`. If `start()` is still running,
|
|
184
|
+
it waits for it and then kills the agent.
|
|
185
|
+
|
|
186
|
+
:return: `True` if the agent was killed, `False` if it was not found or not started
|
|
187
|
+
"""
|
|
188
|
+
await self._start_settled()
|
|
189
|
+
if self._transport is None:
|
|
190
|
+
return False
|
|
191
|
+
return await self._transport.kill()
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
__all__ = [
|
|
195
|
+
"DEFAULT_MAX_MESSAGE_BYTES",
|
|
196
|
+
"DEFAULT_STOP_TIMEOUT",
|
|
197
|
+
"ACPException",
|
|
198
|
+
"AsyncACPAgent",
|
|
199
|
+
"ACPAgentResult",
|
|
200
|
+
"StderrHandler",
|
|
201
|
+
]
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
DEFAULT_MAX_MESSAGE_BYTES = 32 * 1024 * 1024
|
|
2
|
+
"""
|
|
3
|
+
Default maximum size of a single message from the agent, the same as the
|
|
4
|
+
TypeScript ACP SDK uses.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
DEFAULT_STOP_TIMEOUT = 5
|
|
8
|
+
"""
|
|
9
|
+
Default time for an ACP agent to exit after `stop()`, in **seconds**.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
STDERR_TAIL_CHARS = 4096
|
|
13
|
+
READ_QUEUE_MESSAGES = 64
|
|
14
|
+
|
|
15
|
+
METHOD_NOT_FOUND = -32601
|
|
16
|
+
PARSE_ERROR = -32700
|
|
17
|
+
|
|
18
|
+
PARSE_ERROR_RESPONSE = {
|
|
19
|
+
"jsonrpc": "2.0",
|
|
20
|
+
"id": None,
|
|
21
|
+
"error": {"code": PARSE_ERROR, "message": "Parse error"},
|
|
22
|
+
}
|
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import inspect
|
|
3
|
+
from collections import deque
|
|
4
|
+
from typing import Any, Deque, Dict, Optional
|
|
5
|
+
|
|
6
|
+
from e2b import AsyncCommandHandle, AsyncSandbox, CommandExitException
|
|
7
|
+
from e2b.connection_config import Username
|
|
8
|
+
from e2b.envd.versions import ENVD_ENVD_CLOSE
|
|
9
|
+
|
|
10
|
+
from .consts import DEFAULT_STOP_TIMEOUT, READ_QUEUE_MESSAGES, STDERR_TAIL_CHARS
|
|
11
|
+
from .exceptions import ACPException
|
|
12
|
+
from .types import ACPAgentResult, JsonRpcMessage, StderrHandler
|
|
13
|
+
from .utils import (
|
|
14
|
+
LineSplitter,
|
|
15
|
+
encode_message,
|
|
16
|
+
parse_agent_line,
|
|
17
|
+
restrict_client_capabilities,
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class ACPTransport:
|
|
22
|
+
"""
|
|
23
|
+
ACP over the stdin/stdout of an agent process in the sandbox.
|
|
24
|
+
|
|
25
|
+
It implements the transport interface of the `agent-client-protocol`
|
|
26
|
+
package (`send`, `receive`, `close`).
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
def __init__(
|
|
30
|
+
self,
|
|
31
|
+
sandbox: AsyncSandbox,
|
|
32
|
+
max_message_bytes: int,
|
|
33
|
+
on_stderr: Optional[StderrHandler],
|
|
34
|
+
):
|
|
35
|
+
self._commands = sandbox.commands
|
|
36
|
+
self._lines = LineSplitter(max_message_bytes)
|
|
37
|
+
self._on_stderr = on_stderr
|
|
38
|
+
self._stderr_tail = ""
|
|
39
|
+
|
|
40
|
+
# Messages for the client. receive() and the reader hand them over
|
|
41
|
+
# through the deque, so a cancelled receive() never loses one.
|
|
42
|
+
self._pending: Deque[Any] = deque()
|
|
43
|
+
self._readable = asyncio.Event()
|
|
44
|
+
self._space = asyncio.Event()
|
|
45
|
+
self._space.set()
|
|
46
|
+
|
|
47
|
+
self._write_lock = asyncio.Lock()
|
|
48
|
+
self._handle_ready: asyncio.Future[AsyncCommandHandle[None]] = (
|
|
49
|
+
asyncio.get_running_loop().create_future()
|
|
50
|
+
)
|
|
51
|
+
self._handle: Optional[AsyncCommandHandle[None]] = None
|
|
52
|
+
self._exit_task: Optional[asyncio.Task[Optional[ACPAgentResult]]] = None
|
|
53
|
+
|
|
54
|
+
self._ended = False
|
|
55
|
+
self._error: Optional[BaseException] = None
|
|
56
|
+
# Set only once the process exit status is known.
|
|
57
|
+
self._exit: Optional[ACPAgentResult] = None
|
|
58
|
+
# Set by close(): the exit that follows is expected, and output after
|
|
59
|
+
# it is not delivered.
|
|
60
|
+
self._closing = False
|
|
61
|
+
|
|
62
|
+
@property
|
|
63
|
+
def pid(self) -> int:
|
|
64
|
+
assert self._handle is not None
|
|
65
|
+
return self._handle.pid
|
|
66
|
+
|
|
67
|
+
async def send(self, message: JsonRpcMessage) -> None:
|
|
68
|
+
await self._write(restrict_client_capabilities(message))
|
|
69
|
+
|
|
70
|
+
async def receive(self) -> Optional[JsonRpcMessage]:
|
|
71
|
+
while True:
|
|
72
|
+
if self._pending:
|
|
73
|
+
message = self._pending.popleft()
|
|
74
|
+
if len(self._pending) < READ_QUEUE_MESSAGES:
|
|
75
|
+
self._space.set()
|
|
76
|
+
return message
|
|
77
|
+
if self._ended:
|
|
78
|
+
if self._error is not None:
|
|
79
|
+
raise self._error
|
|
80
|
+
return None
|
|
81
|
+
self._readable.clear()
|
|
82
|
+
await self._readable.wait()
|
|
83
|
+
|
|
84
|
+
async def close(
|
|
85
|
+
self,
|
|
86
|
+
timeout: float = DEFAULT_STOP_TIMEOUT,
|
|
87
|
+
request_timeout: Optional[float] = None,
|
|
88
|
+
) -> None:
|
|
89
|
+
# Only a known exit status means the process is gone. A failed output
|
|
90
|
+
# stream can leave it running.
|
|
91
|
+
if self._exit is not None or self._exit_task is None:
|
|
92
|
+
return
|
|
93
|
+
|
|
94
|
+
self._closing = True
|
|
95
|
+
# Unblock the reader if it waits for the client.
|
|
96
|
+
self._space.set()
|
|
97
|
+
|
|
98
|
+
try:
|
|
99
|
+
exit = await asyncio.wait_for(self._stop_and_wait(request_timeout), timeout)
|
|
100
|
+
except Exception:
|
|
101
|
+
exit = None
|
|
102
|
+
if exit is None and self._exit is None:
|
|
103
|
+
await self.kill()
|
|
104
|
+
|
|
105
|
+
async def kill(self) -> bool:
|
|
106
|
+
assert self._handle is not None
|
|
107
|
+
# Output waiting for the client would otherwise keep the handle from
|
|
108
|
+
# seeing the exit.
|
|
109
|
+
self._closing = True
|
|
110
|
+
self._space.set()
|
|
111
|
+
return await self._handle.kill()
|
|
112
|
+
|
|
113
|
+
async def wait(self) -> ACPAgentResult:
|
|
114
|
+
assert self._exit_task is not None
|
|
115
|
+
exit = await asyncio.shield(self._exit_task)
|
|
116
|
+
if exit is None:
|
|
117
|
+
assert self._error is not None
|
|
118
|
+
raise self._error
|
|
119
|
+
return exit
|
|
120
|
+
|
|
121
|
+
async def start(
|
|
122
|
+
self,
|
|
123
|
+
cmd: str,
|
|
124
|
+
envs: Optional[Dict[str, str]],
|
|
125
|
+
user: Optional[Username],
|
|
126
|
+
cwd: Optional[str],
|
|
127
|
+
request_timeout: Optional[float],
|
|
128
|
+
) -> None:
|
|
129
|
+
try:
|
|
130
|
+
handle = await self._commands.run(
|
|
131
|
+
cmd,
|
|
132
|
+
background=True,
|
|
133
|
+
envs=envs,
|
|
134
|
+
user=user,
|
|
135
|
+
cwd=cwd,
|
|
136
|
+
on_stdout=self._handle_stdout,
|
|
137
|
+
on_stderr=self._handle_stderr,
|
|
138
|
+
stdin=True,
|
|
139
|
+
timeout=0,
|
|
140
|
+
request_timeout=request_timeout,
|
|
141
|
+
retain_output=False,
|
|
142
|
+
)
|
|
143
|
+
except BaseException:
|
|
144
|
+
self._handle_ready.cancel()
|
|
145
|
+
raise
|
|
146
|
+
self._handle = handle
|
|
147
|
+
self._handle_ready.set_result(handle)
|
|
148
|
+
self._exit_task = asyncio.create_task(self._watch_exit(handle))
|
|
149
|
+
|
|
150
|
+
async def _close_quietly(self) -> None:
|
|
151
|
+
# The stream already failed with the real error.
|
|
152
|
+
try:
|
|
153
|
+
await self.close()
|
|
154
|
+
except Exception:
|
|
155
|
+
pass
|
|
156
|
+
|
|
157
|
+
async def _stop_and_wait(
|
|
158
|
+
self, request_timeout: Optional[float]
|
|
159
|
+
) -> Optional[ACPAgentResult]:
|
|
160
|
+
await self._end_input(request_timeout)
|
|
161
|
+
assert self._exit_task is not None
|
|
162
|
+
return await asyncio.shield(self._exit_task)
|
|
163
|
+
|
|
164
|
+
async def _write(self, message: Any) -> None:
|
|
165
|
+
line = encode_message(message)
|
|
166
|
+
handle = await asyncio.shield(self._handle_ready)
|
|
167
|
+
# Client messages, replies to the agent and EOF share one ordered
|
|
168
|
+
# write path, so concurrent writes never interleave.
|
|
169
|
+
async with self._write_lock:
|
|
170
|
+
await handle.send_stdin(line)
|
|
171
|
+
|
|
172
|
+
async def _end_input(self, request_timeout: Optional[float] = None) -> None:
|
|
173
|
+
handle = await asyncio.shield(self._handle_ready)
|
|
174
|
+
async with self._write_lock:
|
|
175
|
+
if self._commands._envd_version >= ENVD_ENVD_CLOSE:
|
|
176
|
+
await handle.close_stdin(request_timeout=request_timeout)
|
|
177
|
+
else:
|
|
178
|
+
await handle.kill()
|
|
179
|
+
|
|
180
|
+
def _end(self, error: Optional[BaseException] = None) -> None:
|
|
181
|
+
if not self._ended:
|
|
182
|
+
self._ended = True
|
|
183
|
+
self._error = error
|
|
184
|
+
self._readable.set()
|
|
185
|
+
self._space.set()
|
|
186
|
+
|
|
187
|
+
async def _deliver(self, line: str) -> None:
|
|
188
|
+
if self._closing:
|
|
189
|
+
return
|
|
190
|
+
message, replies = parse_agent_line(line)
|
|
191
|
+
for reply in replies:
|
|
192
|
+
try:
|
|
193
|
+
await self._write(reply)
|
|
194
|
+
except Exception:
|
|
195
|
+
pass
|
|
196
|
+
if message is None:
|
|
197
|
+
return
|
|
198
|
+
# Stop reading agent output until the client catches up.
|
|
199
|
+
while len(self._pending) >= READ_QUEUE_MESSAGES and not (
|
|
200
|
+
self._closing or self._ended
|
|
201
|
+
):
|
|
202
|
+
self._space.clear()
|
|
203
|
+
await self._space.wait()
|
|
204
|
+
if self._closing or self._ended:
|
|
205
|
+
return
|
|
206
|
+
self._pending.append(message)
|
|
207
|
+
self._readable.set()
|
|
208
|
+
|
|
209
|
+
async def _handle_stdout(self, data: str) -> None:
|
|
210
|
+
if self._closing or self._ended:
|
|
211
|
+
return
|
|
212
|
+
try:
|
|
213
|
+
lines = self._lines.push(data)
|
|
214
|
+
except ACPException as e:
|
|
215
|
+
self._end(e)
|
|
216
|
+
asyncio.ensure_future(self._close_quietly())
|
|
217
|
+
return
|
|
218
|
+
for line in lines:
|
|
219
|
+
await self._deliver(line)
|
|
220
|
+
|
|
221
|
+
async def _handle_stderr(self, data: str) -> None:
|
|
222
|
+
self._stderr_tail = (self._stderr_tail + data)[-STDERR_TAIL_CHARS:]
|
|
223
|
+
if self._on_stderr:
|
|
224
|
+
result = self._on_stderr(data)
|
|
225
|
+
if inspect.isawaitable(result):
|
|
226
|
+
await result
|
|
227
|
+
|
|
228
|
+
async def _watch_exit(
|
|
229
|
+
self, handle: AsyncCommandHandle[None]
|
|
230
|
+
) -> Optional[ACPAgentResult]:
|
|
231
|
+
try:
|
|
232
|
+
result = await handle.wait()
|
|
233
|
+
exit = ACPAgentResult(exit_code=result.exit_code, error=result.error)
|
|
234
|
+
except CommandExitException as e:
|
|
235
|
+
exit = ACPAgentResult(exit_code=e.exit_code, error=e.error)
|
|
236
|
+
except Exception as e:
|
|
237
|
+
# The output stream failed. The process may still be running, but
|
|
238
|
+
# nothing can talk to it any more.
|
|
239
|
+
self._end(e)
|
|
240
|
+
try:
|
|
241
|
+
await self.kill()
|
|
242
|
+
except Exception:
|
|
243
|
+
# The stream already failed with the real error.
|
|
244
|
+
pass
|
|
245
|
+
return None
|
|
246
|
+
|
|
247
|
+
# A message over the limit ends the stream before the agent exits;
|
|
248
|
+
# wait() raises it instead of returning the exit that follows.
|
|
249
|
+
output_error = self._error
|
|
250
|
+
self._exit = exit
|
|
251
|
+
try:
|
|
252
|
+
await self._deliver(self._lines.flush())
|
|
253
|
+
except ACPException as e:
|
|
254
|
+
self._end(e)
|
|
255
|
+
if exit.exit_code != 0 and not self._closing:
|
|
256
|
+
message = f"ACP agent exited with code {exit.exit_code}"
|
|
257
|
+
if exit.error:
|
|
258
|
+
message += f": {exit.error}"
|
|
259
|
+
if self._stderr_tail:
|
|
260
|
+
message += f"\n{self._stderr_tail}"
|
|
261
|
+
self._end(ACPException(message))
|
|
262
|
+
else:
|
|
263
|
+
self._end()
|
|
264
|
+
return None if output_error is not None else exit
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
from dataclasses import dataclass
|
|
2
|
+
from typing import Any, Awaitable, Callable, Dict, Optional, Union
|
|
3
|
+
|
|
4
|
+
JsonRpcMessage = Dict[str, Any]
|
|
5
|
+
"""
|
|
6
|
+
JSON-RPC 2.0 message exchanged with an ACP agent.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
StderrHandler = Union[Callable[[str], None], Callable[[str], Awaitable[None]]]
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@dataclass
|
|
13
|
+
class ACPAgentResult:
|
|
14
|
+
"""
|
|
15
|
+
Exit status of an ACP agent process.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
exit_code: int
|
|
19
|
+
"""
|
|
20
|
+
Exit code of the agent process.
|
|
21
|
+
"""
|
|
22
|
+
error: Optional[str] = None
|
|
23
|
+
"""
|
|
24
|
+
Error message if the process failed.
|
|
25
|
+
"""
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import math
|
|
3
|
+
from typing import Any, List, Tuple
|
|
4
|
+
|
|
5
|
+
from e2b import InvalidArgumentException
|
|
6
|
+
|
|
7
|
+
from .consts import METHOD_NOT_FOUND, PARSE_ERROR_RESPONSE
|
|
8
|
+
from .exceptions import ACPException
|
|
9
|
+
from .types import JsonRpcMessage
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class LineSplitter:
|
|
13
|
+
"""
|
|
14
|
+
Splits newline-delimited text chunks into complete lines.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
def __init__(self, max_line_bytes: int):
|
|
18
|
+
if (
|
|
19
|
+
isinstance(max_line_bytes, bool)
|
|
20
|
+
or not isinstance(max_line_bytes, (int, float))
|
|
21
|
+
or not math.isfinite(max_line_bytes)
|
|
22
|
+
or max_line_bytes != int(max_line_bytes)
|
|
23
|
+
or max_line_bytes <= 0
|
|
24
|
+
):
|
|
25
|
+
raise InvalidArgumentException(
|
|
26
|
+
f"max_message_bytes must be a positive integer, got {max_line_bytes}"
|
|
27
|
+
)
|
|
28
|
+
self._max_line_bytes = int(max_line_bytes)
|
|
29
|
+
# Text after the last newline. Chunks are joined once, when the line
|
|
30
|
+
# ends, so a long message is not rescanned on every chunk.
|
|
31
|
+
self._pending: List[str] = []
|
|
32
|
+
self._pending_bytes = 0
|
|
33
|
+
|
|
34
|
+
def push(self, chunk: str) -> List[str]:
|
|
35
|
+
lines = chunk.split("\n")
|
|
36
|
+
rest = lines.pop()
|
|
37
|
+
if lines:
|
|
38
|
+
self._append(lines[0])
|
|
39
|
+
lines[0] = self.flush()
|
|
40
|
+
for line in lines[1:]:
|
|
41
|
+
# Characters never outnumber UTF-8 bytes, so the cheap length
|
|
42
|
+
# check only lets through lines that might be too large.
|
|
43
|
+
if len(line) > self._max_line_bytes / 4:
|
|
44
|
+
self._check(len(line.encode()))
|
|
45
|
+
self._append(rest)
|
|
46
|
+
return lines
|
|
47
|
+
|
|
48
|
+
def flush(self) -> str:
|
|
49
|
+
rest = "".join(self._pending)
|
|
50
|
+
self._pending = []
|
|
51
|
+
self._pending_bytes = 0
|
|
52
|
+
return rest
|
|
53
|
+
|
|
54
|
+
def _append(self, text: str) -> None:
|
|
55
|
+
if text:
|
|
56
|
+
self._pending.append(text)
|
|
57
|
+
self._pending_bytes += len(text.encode())
|
|
58
|
+
self._check(self._pending_bytes)
|
|
59
|
+
|
|
60
|
+
def _check(self, size: int) -> None:
|
|
61
|
+
if size > self._max_line_bytes:
|
|
62
|
+
raise ACPException(
|
|
63
|
+
f"ACP message exceeds the limit of {self._max_line_bytes} bytes. "
|
|
64
|
+
"Pass a larger `max_message_bytes` to AsyncACPAgent if the "
|
|
65
|
+
"agent sends larger messages."
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def encode_message(message: Any) -> str:
|
|
70
|
+
return json.dumps(message, separators=(",", ":"), ensure_ascii=False) + "\n"
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def is_client_execution_method(method: Any) -> bool:
|
|
74
|
+
"""
|
|
75
|
+
Methods that would make the agent read files or run commands on the
|
|
76
|
+
client's machine instead of inside the sandbox.
|
|
77
|
+
"""
|
|
78
|
+
return isinstance(method, str) and (
|
|
79
|
+
method.startswith("fs/") or method.startswith("terminal/")
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def restrict_client_capabilities(message: Any) -> Any:
|
|
84
|
+
"""
|
|
85
|
+
Turn off the client filesystem and terminal capabilities in an
|
|
86
|
+
`initialize` request, also inside a batch, so the agent keeps using its
|
|
87
|
+
own tools in the sandbox. Other messages are returned unchanged.
|
|
88
|
+
"""
|
|
89
|
+
if isinstance(message, list):
|
|
90
|
+
return [restrict_client_capabilities(item) for item in message]
|
|
91
|
+
if not isinstance(message, dict) or message.get("method") != "initialize":
|
|
92
|
+
return message
|
|
93
|
+
params = message.get("params")
|
|
94
|
+
params = params if isinstance(params, dict) else {}
|
|
95
|
+
capabilities = params.get("clientCapabilities")
|
|
96
|
+
capabilities = capabilities if isinstance(capabilities, dict) else {}
|
|
97
|
+
return {
|
|
98
|
+
**message,
|
|
99
|
+
"params": {
|
|
100
|
+
**params,
|
|
101
|
+
"clientCapabilities": {
|
|
102
|
+
**capabilities,
|
|
103
|
+
"fs": {"readTextFile": False, "writeTextFile": False},
|
|
104
|
+
"terminal": False,
|
|
105
|
+
},
|
|
106
|
+
},
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def filter_agent_message(message: Any) -> Tuple[Any, List[JsonRpcMessage]]:
|
|
111
|
+
"""
|
|
112
|
+
Split agent output into what is forwarded to the client (`None` if
|
|
113
|
+
nothing) and the error responses sent straight back to the agent for
|
|
114
|
+
client-execution requests.
|
|
115
|
+
"""
|
|
116
|
+
items = message if isinstance(message, list) else [message]
|
|
117
|
+
forward: List[Any] = []
|
|
118
|
+
replies: List[JsonRpcMessage] = []
|
|
119
|
+
|
|
120
|
+
for item in items:
|
|
121
|
+
if not isinstance(item, dict) or not is_client_execution_method(
|
|
122
|
+
item.get("method")
|
|
123
|
+
):
|
|
124
|
+
forward.append(item)
|
|
125
|
+
continue
|
|
126
|
+
# Notifications get no reply; requests are rejected.
|
|
127
|
+
if "id" in item:
|
|
128
|
+
replies.append(
|
|
129
|
+
{
|
|
130
|
+
"jsonrpc": "2.0",
|
|
131
|
+
"id": item["id"],
|
|
132
|
+
"error": {
|
|
133
|
+
"code": METHOD_NOT_FOUND,
|
|
134
|
+
"message": f"Method not found: {item['method']} is not available, the agent runs inside an E2B sandbox",
|
|
135
|
+
},
|
|
136
|
+
}
|
|
137
|
+
)
|
|
138
|
+
|
|
139
|
+
if not isinstance(message, list):
|
|
140
|
+
return (forward[0] if forward else None), replies
|
|
141
|
+
return (forward or None), replies
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def parse_agent_line(line: str) -> Tuple[Any, List[JsonRpcMessage]]:
|
|
145
|
+
"""
|
|
146
|
+
Parse one line of agent output into the message to forward to the client
|
|
147
|
+
and the replies to send back to the agent.
|
|
148
|
+
"""
|
|
149
|
+
text = line.strip()
|
|
150
|
+
if not text:
|
|
151
|
+
return None, []
|
|
152
|
+
try:
|
|
153
|
+
message = json.loads(text)
|
|
154
|
+
except ValueError:
|
|
155
|
+
return None, [PARSE_ERROR_RESPONSE]
|
|
156
|
+
return filter_agent_message(message)
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "e2b-acp"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Run Agent Client Protocol (ACP) agents in E2B sandboxes"
|
|
5
|
+
license = "Apache-2.0"
|
|
6
|
+
license-files = ["LICENSE"]
|
|
7
|
+
readme = "README.md"
|
|
8
|
+
requires-python = ">=3.11"
|
|
9
|
+
dependencies = [
|
|
10
|
+
"e2b>=2.62.0,<3.0.0",
|
|
11
|
+
"agent-client-protocol>=0.12.1,<0.13",
|
|
12
|
+
]
|
|
13
|
+
|
|
14
|
+
[[project.authors]]
|
|
15
|
+
name = "e2b"
|
|
16
|
+
email = "hello@e2b.dev"
|
|
17
|
+
|
|
18
|
+
[project.urls]
|
|
19
|
+
Homepage = "https://e2b.dev/docs/agents/acp?utm_source=pypi&utm_medium=referral&utm_campaign=package_homepage&utm_content=e2b-acp"
|
|
20
|
+
Repository = "https://github.com/e2b-dev/e2b/tree/main/packages/acp-python"
|
|
21
|
+
"Bug Tracker" = "https://github.com/e2b-dev/e2b/issues"
|
|
22
|
+
|
|
23
|
+
[dependency-groups]
|
|
24
|
+
dev = [
|
|
25
|
+
"pytest>=9.0.3,<10",
|
|
26
|
+
"python-dotenv>=1.0.0,<2",
|
|
27
|
+
"pytest-dotenv>=0.5.2,<0.6",
|
|
28
|
+
"pytest-asyncio>=1.3.0,<2",
|
|
29
|
+
"ruff>=0.11.12,<0.12",
|
|
30
|
+
"ty>=0.0.15,<0.0.16",
|
|
31
|
+
]
|
|
32
|
+
|
|
33
|
+
[build-system]
|
|
34
|
+
requires = ["uv_build>=0.10.0,<0.11.0"]
|
|
35
|
+
build-backend = "uv_build"
|
|
36
|
+
|
|
37
|
+
[tool.uv.build-backend]
|
|
38
|
+
module-name = ["e2b_acp"]
|
|
39
|
+
module-root = ""
|
|
40
|
+
|
|
41
|
+
[tool.uv.sources.e2b]
|
|
42
|
+
workspace = true
|
|
43
|
+
|
|
44
|
+
[tool.uv.workspace]
|
|
45
|
+
members = ["../python-sdk"]
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "e2b-acp"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Run Agent Client Protocol (ACP) agents in E2B sandboxes"
|
|
5
|
+
authors = [{ name = "e2b", email = "hello@e2b.dev" }]
|
|
6
|
+
license = "Apache-2.0"
|
|
7
|
+
license-files = ["LICENSE"]
|
|
8
|
+
readme = "README.md"
|
|
9
|
+
requires-python = ">=3.11"
|
|
10
|
+
dependencies = [
|
|
11
|
+
"e2b>=2.62.0,<3.0.0",
|
|
12
|
+
"agent-client-protocol>=0.12.1,<0.13",
|
|
13
|
+
]
|
|
14
|
+
|
|
15
|
+
[project.urls]
|
|
16
|
+
Homepage = "https://e2b.dev/docs/agents/acp?utm_source=pypi&utm_medium=referral&utm_campaign=package_homepage&utm_content=e2b-acp"
|
|
17
|
+
Repository = "https://github.com/e2b-dev/e2b/tree/main/packages/acp-python"
|
|
18
|
+
"Bug Tracker" = "https://github.com/e2b-dev/e2b/issues"
|
|
19
|
+
|
|
20
|
+
[dependency-groups]
|
|
21
|
+
dev = [
|
|
22
|
+
"pytest>=9.0.3,<10",
|
|
23
|
+
"python-dotenv>=1.0.0,<2",
|
|
24
|
+
"pytest-dotenv>=0.5.2,<0.6",
|
|
25
|
+
"pytest-asyncio>=1.3.0,<2",
|
|
26
|
+
"ruff>=0.11.12,<0.12",
|
|
27
|
+
"ty>=0.0.15,<0.0.16",
|
|
28
|
+
]
|
|
29
|
+
|
|
30
|
+
[build-system]
|
|
31
|
+
requires = ["uv_build>=0.10.0,<0.11.0"]
|
|
32
|
+
build-backend = "uv_build"
|
|
33
|
+
|
|
34
|
+
[tool.uv.build-backend]
|
|
35
|
+
module-name = ["e2b_acp"]
|
|
36
|
+
module-root = ""
|
|
37
|
+
|
|
38
|
+
[tool.uv.sources]
|
|
39
|
+
e2b = { workspace = true }
|
|
40
|
+
|
|
41
|
+
[tool.uv.workspace]
|
|
42
|
+
members = ["../python-sdk"]
|