@cuylabs/agent-sandbox-docker 0.10.0

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.
package/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 [yyyy] [name of copyright owner]
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.
package/README.md ADDED
@@ -0,0 +1,119 @@
1
+ # @cuylabs/agent-sandbox-docker
2
+
3
+ Docker-backed sandbox sessions and execution hosts for `@cuylabs/agent-core`.
4
+
5
+ Use this package when you want host-aware tools to run inside Docker instead of
6
+ on the local machine. The package supports:
7
+
8
+ - low-level `ToolHost` adaptation for an existing container via `dockerHost()`
9
+ - higher-level `DockerSandboxSession` lifecycle for a managed Docker environment
10
+ with `snapshot()`, `extendTimeout()`, and `getPreviewUrl()` support
11
+ - `registerDockerHostProvider()` for registry-based host discovery
12
+
13
+ The agent loop, model calls, middleware, and sessions still live in your
14
+ Node.js process. Only host-backed tool operations are redirected into the
15
+ container through the `ToolHost` interface from `@cuylabs/agent-core/tool/host`.
16
+
17
+ ## Package Boundary
18
+
19
+ `@cuylabs/agent-core` owns:
20
+
21
+ - the `ToolHost` interface
22
+ - the `SandboxSession` interface
23
+ - the default `localHost()`
24
+ - the `ToolHostRegistry` and `defaultToolHostRegistry`
25
+ - the executor path that passes `ctx.host` into tools
26
+
27
+ `@cuylabs/agent-sandbox-docker` owns:
28
+
29
+ - connecting `ToolHost` to a running Docker container
30
+ - path resolution inside the container
31
+ - file and shell operations implemented through Docker exec sessions (with stdin piping for large files)
32
+ - `DockerSandboxSession` class implementing the full `SandboxSession` contract
33
+ - container snapshot via `commit()`, lease/timeout tracking, and preview URL construction
34
+ - optional self-registration into `ToolHostRegistry` via `registerDockerHostProvider()`
35
+
36
+ That same pattern is intended for other host packages too. Docker is one concrete backend implementing the public `ToolHost` contract from `agent-core`.
37
+
38
+ ## Quick Start
39
+
40
+ ### Managed Session (recommended)
41
+
42
+ ```ts
43
+ import { createAgent } from "@cuylabs/agent-core";
44
+ import { createDockerSandboxSession } from "@cuylabs/agent-sandbox-docker";
45
+
46
+ const sandbox = await createDockerSandboxSession({
47
+ create: {
48
+ image: "node:20",
49
+ workdir: "/workspace",
50
+ },
51
+ timeoutMs: 300_000, // 5 minute lease
52
+ hostAddress: "localhost", // for preview URLs
53
+ });
54
+
55
+ const agent = createAgent({
56
+ model,
57
+ sandbox,
58
+ });
59
+
60
+ // Snapshot the environment
61
+ const snap = await sandbox.snapshot();
62
+
63
+ // Extend the lease
64
+ await sandbox.extendTimeout(60_000);
65
+
66
+ // Get preview URL for an exposed port
67
+ const url = sandbox.getPreviewUrl(3000); // "http://localhost:3000"
68
+
69
+ // Clean up
70
+ await sandbox.stop();
71
+ ```
72
+
73
+ ### Attach to Existing Container
74
+
75
+ ```ts
76
+ import { createDockerSandboxSession } from "@cuylabs/agent-sandbox-docker";
77
+
78
+ const sandbox = await createDockerSandboxSession({
79
+ container: "my-workspace",
80
+ workdir: "/workspace",
81
+ });
82
+ ```
83
+
84
+ ### Low-Level Host Only
85
+
86
+ If you already manage the container lifecycle yourself:
87
+
88
+ ```ts
89
+ import { dockerHost } from "@cuylabs/agent-sandbox-docker";
90
+
91
+ const host = await dockerHost({
92
+ container: "my-sandbox",
93
+ workdir: "/workspace",
94
+ });
95
+ ```
96
+
97
+ ### Registry Integration
98
+
99
+ ```ts
100
+ import { registerDockerHostProvider } from "@cuylabs/agent-sandbox-docker";
101
+ import { defaultToolHostRegistry } from "@cuylabs/agent-core/tool/host";
102
+
103
+ // Call once at startup
104
+ registerDockerHostProvider();
105
+
106
+ // Then create hosts by name
107
+ const host = await defaultToolHostRegistry.create("docker", {
108
+ container: "my-workspace",
109
+ });
110
+ ```
111
+
112
+ ## Start Here
113
+
114
+ - [docs/README.md](./docs/README.md) for the package documentation map
115
+ - [docs/how-it-works.md](./docs/how-it-works.md) for the implementation details
116
+ - [examples/README.md](./examples/README.md) for a runnable end-to-end example
117
+
118
+ `agent-core` keeps the host contract and the default local host. Concrete
119
+ non-local hosts live in separate packages so they can evolve independently.
@@ -0,0 +1,180 @@
1
+ import * as _cuylabs_agent_core_tool_host from '@cuylabs/agent-core/tool/host';
2
+ import { ToolHost } from '@cuylabs/agent-core/tool/host';
3
+ import { SandboxSession, SandboxSessionMetadata, SandboxSnapshotResult } from '@cuylabs/agent-core';
4
+
5
+ /**
6
+ * A Docker container reference understood by this package.
7
+ */
8
+ interface DockerContainerRefLike {
9
+ id: string;
10
+ modem?: unknown;
11
+ start?: () => Promise<void>;
12
+ stop?: (options?: {
13
+ t?: number;
14
+ }) => Promise<void>;
15
+ remove?: (options?: {
16
+ force?: boolean;
17
+ }) => Promise<void>;
18
+ inspect?: () => Promise<{
19
+ Id?: string;
20
+ Name?: string;
21
+ State?: {
22
+ Running?: boolean;
23
+ };
24
+ NetworkSettings?: {
25
+ Ports?: Record<string, Array<{
26
+ HostIp?: string;
27
+ HostPort?: string;
28
+ }> | null>;
29
+ };
30
+ }>;
31
+ commit?: (options?: Record<string, unknown>) => Promise<{
32
+ Id?: string;
33
+ }>;
34
+ pause?: () => Promise<void>;
35
+ unpause?: () => Promise<void>;
36
+ }
37
+ /**
38
+ * Configuration for creating a Docker-backed execution host.
39
+ */
40
+ interface DockerHostOptions {
41
+ /**
42
+ * The container to connect to. Either:
43
+ * - a container name or ID
44
+ * - a Dockerode `Container`-like object
45
+ */
46
+ container: string | DockerContainerRefLike;
47
+ /** User to run commands as inside the container. */
48
+ user?: string;
49
+ /** Default working directory inside the container. */
50
+ workdir?: string;
51
+ /**
52
+ * Dockerode constructor options.
53
+ * Only used when `container` is a string.
54
+ */
55
+ dockerOptions?: Record<string, unknown>;
56
+ }
57
+ /**
58
+ * Provisioning options for a managed Docker sandbox session.
59
+ */
60
+ interface DockerSandboxProvisionOptions {
61
+ /** Container image to create. */
62
+ image: string;
63
+ /** Optional container name. */
64
+ name?: string;
65
+ /** Optional container command. */
66
+ command?: string[];
67
+ /** Environment variables for the container. */
68
+ env?: Record<string, string | undefined>;
69
+ /** Working directory inside the container. */
70
+ workdir?: string;
71
+ /** Default user inside the container. */
72
+ user?: string;
73
+ /** Dockerode constructor options. */
74
+ dockerOptions?: Record<string, unknown>;
75
+ /** Additional raw options merged into `docker.createContainer(...)`. */
76
+ containerOptions?: Record<string, unknown>;
77
+ /** Pull the image before create. Default: `true`. */
78
+ pull?: boolean;
79
+ /**
80
+ * Remove an existing container with the same name before create.
81
+ * Default: `false`.
82
+ */
83
+ removeExisting?: boolean;
84
+ }
85
+ /**
86
+ * Configuration for a managed Docker sandbox session.
87
+ *
88
+ * Choose exactly one source:
89
+ * - `container` to attach to an existing container
90
+ * - `create` to provision a new one
91
+ */
92
+ interface DockerSandboxSessionOptions {
93
+ /** Existing container to attach to. */
94
+ container?: DockerHostOptions["container"];
95
+ /** Provision a new container and manage its lifecycle. */
96
+ create?: DockerSandboxProvisionOptions;
97
+ /** User exposed through the embedded ToolHost. */
98
+ user?: string;
99
+ /** Working directory exposed through the embedded ToolHost. */
100
+ workdir?: string;
101
+ /** Dockerode constructor options when attaching by container name. */
102
+ dockerOptions?: Record<string, unknown>;
103
+ /**
104
+ * Stop the container when the sandbox session stops.
105
+ * Default: `true` for provisioned containers, `false` for attached ones.
106
+ */
107
+ stopOnClose?: boolean;
108
+ /**
109
+ * Remove the container when the sandbox session stops.
110
+ * Default: `true` for provisioned containers, `false` for attached ones.
111
+ */
112
+ removeOnStop?: boolean;
113
+ /**
114
+ * Session timeout/lease in milliseconds.
115
+ * When set, the session tracks an expiration timestamp and supports
116
+ * `extendTimeout()`. Default: no timeout.
117
+ */
118
+ timeoutMs?: number;
119
+ /**
120
+ * Host address for building preview URLs.
121
+ * Used by `getPreviewUrl()` to construct `http://{hostAddress}:{hostPort}` URLs.
122
+ * Default: `"localhost"`.
123
+ */
124
+ hostAddress?: string;
125
+ }
126
+
127
+ interface DockerRuntime {
128
+ docker: any;
129
+ container: any;
130
+ label: string;
131
+ }
132
+
133
+ declare function dockerHost(options: DockerHostOptions): Promise<ToolHost>;
134
+
135
+ declare class DockerSandboxSession implements SandboxSession {
136
+ readonly id: string;
137
+ readonly host: ToolHost;
138
+ readonly metadata: SandboxSessionMetadata;
139
+ private closed;
140
+ private readonly runtime;
141
+ private readonly stopOnClose;
142
+ private readonly removeOnStop;
143
+ private readonly hostAddress;
144
+ private expiresAt;
145
+ private timeoutMs;
146
+ private snapshotCounter;
147
+ constructor(options: {
148
+ runtime: DockerRuntime;
149
+ host: ToolHost;
150
+ managed: boolean;
151
+ workdir: string;
152
+ stopOnClose: boolean;
153
+ removeOnStop: boolean;
154
+ hostAddress: string;
155
+ timeoutMs?: number;
156
+ });
157
+ stop(): Promise<void>;
158
+ snapshot(): Promise<SandboxSnapshotResult>;
159
+ extendTimeout(additionalMs: number): Promise<{
160
+ expiresAt: number;
161
+ } | void>;
162
+ getPreviewUrl(port: number): string | undefined;
163
+ }
164
+ declare function createDockerSandboxSession(options: DockerSandboxSessionOptions): Promise<DockerSandboxSession>;
165
+
166
+ /**
167
+ * Register the "docker" host provider on a ToolHostRegistry.
168
+ *
169
+ * Call this once at startup to enable `registry.create("docker", options)`.
170
+ * When called without arguments, registers on the default global registry.
171
+ */
172
+ declare function registerDockerHostProvider(registry?: {
173
+ register(provider: {
174
+ name: string;
175
+ description?: string;
176
+ create(options?: DockerHostOptions): Promise<_cuylabs_agent_core_tool_host.ToolHost>;
177
+ }): unknown;
178
+ }): void;
179
+
180
+ export { type DockerContainerRefLike, type DockerHostOptions, type DockerSandboxProvisionOptions, DockerSandboxSession, type DockerSandboxSessionOptions, createDockerSandboxSession, dockerHost, registerDockerHostProvider };
package/dist/index.js ADDED
@@ -0,0 +1,506 @@
1
+ // src/exec.ts
2
+ async function loadDockerode() {
3
+ try {
4
+ const module = await import("dockerode");
5
+ return module.default ?? module;
6
+ } catch {
7
+ throw new Error(
8
+ "dockerHost requires the 'dockerode' package. Install it with: npm install dockerode"
9
+ );
10
+ }
11
+ }
12
+ async function resolveDockerRuntime(options) {
13
+ const Dockerode = await loadDockerode();
14
+ if (typeof options.container === "string") {
15
+ const docker = new Dockerode(options.dockerOptions);
16
+ const container2 = docker.getContainer(options.container);
17
+ return {
18
+ docker,
19
+ container: container2,
20
+ label: options.container
21
+ };
22
+ }
23
+ const container = options.container;
24
+ return {
25
+ docker: { modem: container.modem },
26
+ container,
27
+ label: container.id?.slice(0, 12) ?? "unknown"
28
+ };
29
+ }
30
+ async function containerExec(runtime, command, options = {}) {
31
+ const envEntries = options.env ? Object.entries(options.env).filter((entry) => entry[1] !== void 0).map(([key, value]) => `${key}=${value}`) : void 0;
32
+ const attachStdin = options.stdin !== void 0;
33
+ const exec = await runtime.container.exec({
34
+ Cmd: ["sh", "-c", command],
35
+ ...options.user ? { User: options.user } : {},
36
+ ...options.workdir ? { WorkingDir: options.workdir } : {},
37
+ ...envEntries && envEntries.length > 0 ? { Env: envEntries } : {},
38
+ AttachStdout: true,
39
+ AttachStderr: true,
40
+ ...attachStdin ? { AttachStdin: true } : {}
41
+ });
42
+ const stream = await exec.start({
43
+ ...attachStdin ? { hijack: true, stdin: true } : {}
44
+ });
45
+ if (attachStdin && options.stdin) {
46
+ stream.write(options.stdin);
47
+ stream.end();
48
+ }
49
+ let timedOut = false;
50
+ let aborted = false;
51
+ return await new Promise((resolve, reject) => {
52
+ const stdoutChunks = [];
53
+ const stderrChunks = [];
54
+ runtime.docker.modem.demuxStream(
55
+ stream,
56
+ {
57
+ write: (chunk) => {
58
+ stdoutChunks.push(chunk);
59
+ options.onStdout?.(chunk);
60
+ return true;
61
+ },
62
+ end: function() {
63
+ return this;
64
+ }
65
+ },
66
+ {
67
+ write: (chunk) => {
68
+ stderrChunks.push(chunk);
69
+ options.onStderr?.(chunk);
70
+ return true;
71
+ },
72
+ end: function() {
73
+ return this;
74
+ }
75
+ }
76
+ );
77
+ let timer;
78
+ if (options.timeout && options.timeout > 0) {
79
+ timer = setTimeout(() => {
80
+ timedOut = true;
81
+ stream.destroy?.();
82
+ }, options.timeout);
83
+ }
84
+ const onAbort = () => {
85
+ aborted = true;
86
+ stream.destroy?.();
87
+ };
88
+ options.signal?.addEventListener("abort", onAbort, { once: true });
89
+ stream.on("end", async () => {
90
+ if (timer) {
91
+ clearTimeout(timer);
92
+ }
93
+ options.signal?.removeEventListener("abort", onAbort);
94
+ try {
95
+ const info = await exec.inspect();
96
+ resolve({
97
+ stdout: Buffer.concat(stdoutChunks).toString("utf-8"),
98
+ stderr: Buffer.concat(stderrChunks).toString("utf-8"),
99
+ exitCode: timedOut || aborted ? null : info.ExitCode ?? 0,
100
+ timedOut
101
+ });
102
+ } catch (error) {
103
+ reject(error);
104
+ }
105
+ });
106
+ stream.on("error", (error) => {
107
+ if (timer) {
108
+ clearTimeout(timer);
109
+ }
110
+ options.signal?.removeEventListener("abort", onAbort);
111
+ if (timedOut || aborted) {
112
+ resolve({
113
+ stdout: Buffer.concat(stdoutChunks).toString("utf-8"),
114
+ stderr: Buffer.concat(stderrChunks).toString("utf-8"),
115
+ exitCode: null,
116
+ timedOut
117
+ });
118
+ return;
119
+ }
120
+ reject(error);
121
+ });
122
+ });
123
+ }
124
+ async function runDockerCommand(options) {
125
+ const { runtime, command, defaultUser, defaultWorkdir, execOptions, stdin } = options;
126
+ return await containerExec(runtime, command, {
127
+ user: defaultUser,
128
+ workdir: execOptions?.workdir ?? execOptions?.cwd ?? defaultWorkdir,
129
+ env: execOptions?.env,
130
+ timeout: execOptions?.timeout,
131
+ signal: execOptions?.signal,
132
+ onStdout: execOptions?.onStdout,
133
+ onStderr: execOptions?.onStderr,
134
+ stdin
135
+ });
136
+ }
137
+
138
+ // src/shell.ts
139
+ function sq(value) {
140
+ return `'${value.replace(/'/g, `'\\''`)}'`;
141
+ }
142
+ function resolveDockerPath(path, defaultWorkdir) {
143
+ if (path.startsWith("/")) {
144
+ return path;
145
+ }
146
+ const base = defaultWorkdir.endsWith("/") ? defaultWorkdir : `${defaultWorkdir}/`;
147
+ return `${base}${path}`;
148
+ }
149
+
150
+ // src/host.ts
151
+ var STDIN_WRITE_THRESHOLD = 128 * 1024;
152
+ function createDockerToolHost(options) {
153
+ const runtime = options.runtime;
154
+ const defaultUser = options.user;
155
+ const defaultWorkdir = options.workdir ?? "/";
156
+ async function run(command, execOptions) {
157
+ return await runDockerCommand({
158
+ runtime,
159
+ command,
160
+ defaultUser,
161
+ defaultWorkdir,
162
+ execOptions
163
+ });
164
+ }
165
+ return {
166
+ name: `docker:${runtime.label}`,
167
+ async readFile(filePath) {
168
+ const absPath = resolveDockerPath(filePath, defaultWorkdir);
169
+ const result = await run(`cat ${sq(absPath)}`);
170
+ if (result.exitCode !== 0) {
171
+ throw new Error(`readFile failed (${absPath}): ${result.stderr.trim()}`);
172
+ }
173
+ return result.stdout;
174
+ },
175
+ async readBytes(filePath, offset, length) {
176
+ const absPath = resolveDockerPath(filePath, defaultWorkdir);
177
+ const result = await run(
178
+ `dd if=${sq(absPath)} bs=1 skip=${offset} count=${length} 2>/dev/null`
179
+ );
180
+ if (result.exitCode !== 0) {
181
+ throw new Error(
182
+ `readBytes failed (${absPath}): ${result.stderr.trim()}`
183
+ );
184
+ }
185
+ return Buffer.from(result.stdout, "binary");
186
+ },
187
+ async writeFile(filePath, content) {
188
+ const absPath = resolveDockerPath(filePath, defaultWorkdir);
189
+ const dir = absPath.substring(0, absPath.lastIndexOf("/")) || "/";
190
+ await run(`mkdir -p ${sq(dir)}`);
191
+ const contentBytes = Buffer.from(content, "utf-8");
192
+ if (contentBytes.length > STDIN_WRITE_THRESHOLD) {
193
+ const result = await containerExec(
194
+ runtime,
195
+ `cat > ${sq(absPath)}`,
196
+ { user: defaultUser, workdir: defaultWorkdir, stdin: contentBytes }
197
+ );
198
+ if (result.exitCode !== 0) {
199
+ throw new Error(
200
+ `writeFile failed (${absPath}): ${result.stderr.trim()}`
201
+ );
202
+ }
203
+ } else {
204
+ const encoded = contentBytes.toString("base64");
205
+ const result = await run(
206
+ `echo ${sq(encoded)} | base64 -d > ${sq(absPath)}`
207
+ );
208
+ if (result.exitCode !== 0) {
209
+ throw new Error(
210
+ `writeFile failed (${absPath}): ${result.stderr.trim()}`
211
+ );
212
+ }
213
+ }
214
+ },
215
+ async exists(filePath) {
216
+ const absPath = resolveDockerPath(filePath, defaultWorkdir);
217
+ const result = await run(`test -e ${sq(absPath)}`);
218
+ return result.exitCode === 0;
219
+ },
220
+ async stat(filePath) {
221
+ const absPath = resolveDockerPath(filePath, defaultWorkdir);
222
+ const result = await run(
223
+ `stat -c '%s %Y %F' ${sq(absPath)} 2>/dev/null || stat -f '%z %m %HT' ${sq(absPath)}`
224
+ );
225
+ if (result.exitCode !== 0) {
226
+ throw new Error(`stat failed (${absPath}): ${result.stderr.trim()}`);
227
+ }
228
+ const parts = result.stdout.trim().split(/\s+/);
229
+ if (parts.length < 3) {
230
+ throw new Error(
231
+ `stat: unexpected output format for ${absPath}: ${result.stdout}`
232
+ );
233
+ }
234
+ const size = parseInt(parts[0], 10);
235
+ const mtimeSec = parseInt(parts[1], 10);
236
+ const typeStr = parts.slice(2).join(" ").toLowerCase();
237
+ return {
238
+ size,
239
+ mtime: new Date(mtimeSec * 1e3),
240
+ isDirectory: typeStr.includes("directory"),
241
+ isFile: typeStr.includes("regular") || typeStr.includes("file")
242
+ };
243
+ },
244
+ async readdir(dirPath) {
245
+ const absPath = resolveDockerPath(dirPath, defaultWorkdir);
246
+ const result = await run(
247
+ `find ${sq(absPath)} -maxdepth 1 -mindepth 1 -printf '%f\\t%y\\n' 2>/dev/null || for f in ${sq(absPath)}/*; do [ -e "$f" ] || continue; n=$(basename "$f"); if [ -d "$f" ]; then printf '%s\\td\\n' "$n"; else printf '%s\\tf\\n' "$n"; fi; done`
248
+ );
249
+ if (result.exitCode !== 0) {
250
+ throw new Error(
251
+ `readdir failed (${absPath}): ${result.stderr.trim()}`
252
+ );
253
+ }
254
+ return result.stdout.trim().split("\n").filter(Boolean).map((line) => {
255
+ const [name, type] = line.split(" ");
256
+ return {
257
+ name,
258
+ isDirectory: type === "d",
259
+ isFile: type === "f"
260
+ };
261
+ });
262
+ },
263
+ async mkdir(dirPath) {
264
+ const absPath = resolveDockerPath(dirPath, defaultWorkdir);
265
+ const result = await run(`mkdir -p ${sq(absPath)}`);
266
+ if (result.exitCode !== 0) {
267
+ throw new Error(`mkdir failed (${absPath}): ${result.stderr.trim()}`);
268
+ }
269
+ },
270
+ async exec(command, execOptions) {
271
+ return await run(command, execOptions);
272
+ }
273
+ };
274
+ }
275
+ async function dockerHost(options) {
276
+ const runtime = await resolveDockerRuntime(options);
277
+ return createDockerToolHost({
278
+ runtime,
279
+ user: options.user,
280
+ workdir: options.workdir
281
+ });
282
+ }
283
+
284
+ // src/session.ts
285
+ function ensureExactlyOneSource(options) {
286
+ const hasContainer = options.container !== void 0;
287
+ const hasCreate = options.create !== void 0;
288
+ if (hasContainer === hasCreate) {
289
+ throw new Error(
290
+ "createDockerSandboxSession requires exactly one of 'container' or 'create'."
291
+ );
292
+ }
293
+ }
294
+ function toEnvList(env) {
295
+ if (!env) {
296
+ return void 0;
297
+ }
298
+ const entries = Object.entries(env).filter((entry) => entry[1] !== void 0).map(([key, value]) => `${key}=${value}`);
299
+ return entries.length > 0 ? entries : void 0;
300
+ }
301
+ async function pullImage(docker, image) {
302
+ await new Promise((resolve, reject) => {
303
+ docker.pull(
304
+ image,
305
+ {},
306
+ (error, stream) => {
307
+ if (error || !stream) {
308
+ reject(error ?? new Error("Docker did not return a pull stream"));
309
+ return;
310
+ }
311
+ docker.modem.followProgress(stream, (progressError) => {
312
+ if (progressError) {
313
+ reject(progressError);
314
+ return;
315
+ }
316
+ resolve();
317
+ });
318
+ }
319
+ );
320
+ });
321
+ }
322
+ async function removeExistingNamedContainer(docker, name) {
323
+ const existing = docker.getContainer(name);
324
+ await existing.stop?.({ t: 0 }).catch(() => {
325
+ });
326
+ await existing.remove?.({ force: true }).catch(() => {
327
+ });
328
+ }
329
+ async function provisionDockerRuntime(options) {
330
+ const Dockerode = await loadDockerode();
331
+ const docker = new Dockerode(options.dockerOptions);
332
+ if (options.pull !== false) {
333
+ await pullImage(docker, options.image);
334
+ }
335
+ if (options.name && options.removeExisting) {
336
+ await removeExistingNamedContainer(docker, options.name);
337
+ }
338
+ const container = await docker.createContainer({
339
+ Image: options.image,
340
+ ...options.name ? { name: options.name } : {},
341
+ ...options.command ? { Cmd: options.command } : {},
342
+ ...options.workdir ? { WorkingDir: options.workdir } : {},
343
+ ...options.user ? { User: options.user } : {},
344
+ ...toEnvList(options.env) ? { Env: toEnvList(options.env) } : {},
345
+ ...options.containerOptions ?? {}
346
+ });
347
+ await container.start?.();
348
+ return {
349
+ docker,
350
+ container,
351
+ label: options.name ?? container.id?.slice(0, 12) ?? options.image
352
+ };
353
+ }
354
+ async function ensureRunning(runtime) {
355
+ try {
356
+ const info = await runtime.container.inspect?.();
357
+ if (info?.State?.Running === false) {
358
+ await runtime.container.start?.();
359
+ }
360
+ } catch {
361
+ }
362
+ }
363
+ var DockerSandboxSession = class {
364
+ id;
365
+ host;
366
+ metadata;
367
+ closed = false;
368
+ runtime;
369
+ stopOnClose;
370
+ removeOnStop;
371
+ hostAddress;
372
+ expiresAt;
373
+ timeoutMs;
374
+ snapshotCounter = 0;
375
+ constructor(options) {
376
+ this.runtime = options.runtime;
377
+ this.host = options.host;
378
+ this.stopOnClose = options.stopOnClose;
379
+ this.removeOnStop = options.removeOnStop;
380
+ this.hostAddress = options.hostAddress;
381
+ this.timeoutMs = options.timeoutMs;
382
+ if (options.timeoutMs && options.timeoutMs > 0) {
383
+ this.expiresAt = Date.now() + options.timeoutMs;
384
+ }
385
+ this.id = options.runtime.container.id?.slice(0, 12) ?? options.runtime.label;
386
+ this.metadata = {
387
+ kind: "docker",
388
+ label: options.runtime.label,
389
+ workingDirectory: options.workdir,
390
+ containerId: options.runtime.container.id,
391
+ managed: options.managed,
392
+ ...this.expiresAt !== void 0 ? { expiresAt: this.expiresAt } : {},
393
+ ...this.timeoutMs !== void 0 ? { timeoutMs: this.timeoutMs } : {}
394
+ };
395
+ }
396
+ async stop() {
397
+ if (this.closed) {
398
+ return;
399
+ }
400
+ this.closed = true;
401
+ if (this.removeOnStop) {
402
+ await this.runtime.container.remove?.({ force: true }).catch(() => {
403
+ });
404
+ return;
405
+ }
406
+ if (this.stopOnClose) {
407
+ await this.runtime.container.stop?.({ t: 0 }).catch(() => {
408
+ });
409
+ }
410
+ }
411
+ async snapshot() {
412
+ if (this.closed) {
413
+ throw new Error("Cannot snapshot a stopped session.");
414
+ }
415
+ const commit = this.runtime.container.commit;
416
+ if (!commit) {
417
+ throw new Error(
418
+ "Snapshot is not supported: the container reference does not expose commit()."
419
+ );
420
+ }
421
+ const label = `snapshot-${++this.snapshotCounter}-${Date.now()}`;
422
+ const result = await commit.call(this.runtime.container, {
423
+ repo: `${this.runtime.label}-snapshots`,
424
+ tag: label,
425
+ comment: `Snapshot of ${this.runtime.label} at ${(/* @__PURE__ */ new Date()).toISOString()}`,
426
+ pause: true
427
+ });
428
+ return {
429
+ id: result?.Id ?? label,
430
+ label,
431
+ metadata: {
432
+ repo: `${this.runtime.label}-snapshots`,
433
+ tag: label,
434
+ containerId: this.runtime.container.id
435
+ }
436
+ };
437
+ }
438
+ async extendTimeout(additionalMs) {
439
+ if (this.closed) {
440
+ throw new Error("Cannot extend timeout of a stopped session.");
441
+ }
442
+ if (this.expiresAt === void 0) {
443
+ this.expiresAt = Date.now() + additionalMs;
444
+ } else {
445
+ const base = Math.max(this.expiresAt, Date.now());
446
+ this.expiresAt = base + additionalMs;
447
+ }
448
+ this.metadata.expiresAt = this.expiresAt;
449
+ return { expiresAt: this.expiresAt };
450
+ }
451
+ getPreviewUrl(port) {
452
+ return `http://${this.hostAddress}:${port}`;
453
+ }
454
+ };
455
+ async function createDockerSandboxSession(options) {
456
+ ensureExactlyOneSource(options);
457
+ const managed = options.create !== void 0;
458
+ const runtime = managed ? await provisionDockerRuntime(options.create) : await resolveDockerRuntime({
459
+ container: options.container,
460
+ user: options.user,
461
+ workdir: options.workdir,
462
+ dockerOptions: options.dockerOptions
463
+ });
464
+ await ensureRunning(runtime);
465
+ const workdir = options.workdir ?? options.create?.workdir ?? "/";
466
+ const host = createDockerToolHost({
467
+ runtime,
468
+ user: options.user ?? options.create?.user,
469
+ workdir
470
+ });
471
+ const stopOnClose = options.stopOnClose ?? managed;
472
+ const removeOnStop = options.removeOnStop ?? managed;
473
+ return new DockerSandboxSession({
474
+ runtime,
475
+ host,
476
+ managed,
477
+ workdir,
478
+ stopOnClose,
479
+ removeOnStop,
480
+ hostAddress: options.hostAddress ?? "localhost",
481
+ timeoutMs: options.timeoutMs
482
+ });
483
+ }
484
+
485
+ // src/index.ts
486
+ import { defaultToolHostRegistry } from "@cuylabs/agent-core/tool/host";
487
+ function registerDockerHostProvider(registry = defaultToolHostRegistry) {
488
+ registry.register({
489
+ name: "docker",
490
+ description: "Run tools inside a Docker container. Requires 'dockerode' peer dependency.",
491
+ create: (options) => {
492
+ if (!options?.container) {
493
+ throw new Error(
494
+ 'Docker host provider requires at least { container: "<name-or-id>" }.'
495
+ );
496
+ }
497
+ return dockerHost(options);
498
+ }
499
+ });
500
+ }
501
+ export {
502
+ DockerSandboxSession,
503
+ createDockerSandboxSession,
504
+ dockerHost,
505
+ registerDockerHostProvider
506
+ };
package/package.json ADDED
@@ -0,0 +1,65 @@
1
+ {
2
+ "name": "@cuylabs/agent-sandbox-docker",
3
+ "version": "0.10.0",
4
+ "description": "Docker-backed sandbox sessions and execution hosts for @cuylabs/agent-core",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.js",
12
+ "default": "./dist/index.js"
13
+ }
14
+ },
15
+ "files": [
16
+ "dist",
17
+ "README.md"
18
+ ],
19
+ "dependencies": {
20
+ "@cuylabs/agent-core": "^0.10.0"
21
+ },
22
+ "peerDependencies": {
23
+ "dockerode": "^4.0.9"
24
+ },
25
+ "devDependencies": {
26
+ "@ai-sdk/openai": "^3.0.25",
27
+ "@types/dockerode": "^3.3.47",
28
+ "@types/node": "^22.0.0",
29
+ "dockerode": "^4.0.9",
30
+ "dotenv": "^17.2.3",
31
+ "tsup": "^8.0.0",
32
+ "tsx": "^4.21.0",
33
+ "typescript": "^5.7.0",
34
+ "vitest": "^4.0.18",
35
+ "zod": "^3.25.76 || ^4.1.8"
36
+ },
37
+ "keywords": [
38
+ "agent",
39
+ "docker",
40
+ "sandbox",
41
+ "host",
42
+ "execution",
43
+ "environment"
44
+ ],
45
+ "author": "cuylabs",
46
+ "license": "Apache-2.0",
47
+ "repository": {
48
+ "type": "git",
49
+ "url": "https://github.com/cuylabs-ai/agents-ts.git",
50
+ "directory": "packages/agent-sandbox-docker"
51
+ },
52
+ "engines": {
53
+ "node": ">=20"
54
+ },
55
+ "publishConfig": {
56
+ "access": "public"
57
+ },
58
+ "scripts": {
59
+ "build": "tsup src/index.ts --format esm --dts --clean",
60
+ "dev": "tsup src/index.ts --format esm --dts --watch",
61
+ "typecheck": "tsc --noEmit",
62
+ "test": "vitest run",
63
+ "test:watch": "vitest"
64
+ }
65
+ }