@quietrobot/sandboxes-ai 0.0.0-stage → 0.2.1

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 CHANGED
@@ -1,3 +1,86 @@
1
- # Temporary Holding Version
1
+ # @quietrobot/sandboxes-ai
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Quiet Robot sandboxes as tools for your agent framework. Each adapter gives
4
+ the model the same six tools on one sandbox, started on first use:
5
+ `run_command`, `run_code`, `read_file`, `write_file`, `list_files` and
6
+ `expose_port`. Every command goes through your organization's policy.
7
+
8
+ ```sh
9
+ npm install @quietrobot/sandboxes-ai zod
10
+ export QR_API_KEY=qr_live_... # quietrobot.ai/app → API keys
11
+ ```
12
+
13
+ Each `sandboxTools(options)` returns `{ tools, session }`. Call
14
+ `session.close()` when the agent is done to destroy the sandbox.
15
+
16
+ ## Vercel AI SDK
17
+
18
+ ```ts
19
+ import { generateText, stepCountIs } from "ai";
20
+ import { sandboxTools } from "@quietrobot/sandboxes-ai/vercel-ai";
21
+
22
+ const { tools, session } = sandboxTools();
23
+ try {
24
+ const r = await generateText({ model, tools, stopWhen: stepCountIs(20), prompt: "Write and run a script that prints the first 10 primes." });
25
+ console.log(r.text);
26
+ } finally {
27
+ await session.close();
28
+ }
29
+ ```
30
+
31
+ ## OpenAI Agents SDK
32
+
33
+ ```ts
34
+ import { Agent, run } from "@openai/agents";
35
+ import { sandboxTools } from "@quietrobot/sandboxes-ai/openai-agents";
36
+
37
+ const { tools, session } = sandboxTools();
38
+ const agent = new Agent({ name: "coder", instructions: "Use the sandbox to run code.", tools });
39
+ console.log((await run(agent, "How many lines does /etc/passwd have?")).finalOutput);
40
+ await session.close();
41
+ ```
42
+
43
+ ## LangChain
44
+
45
+ ```ts
46
+ import { sandboxTools } from "@quietrobot/sandboxes-ai/langchain";
47
+ const { tools, session } = sandboxTools(); // DynamicStructuredTool[]
48
+ const agent = createReactAgent({ llm, tools });
49
+ ```
50
+
51
+ ## Mastra
52
+
53
+ ```ts
54
+ import { Agent } from "@mastra/core/agent";
55
+ import { sandboxTools } from "@quietrobot/sandboxes-ai/mastra";
56
+
57
+ const { tools, session } = sandboxTools();
58
+ const agent = new Agent({ name: "coder", instructions: "Use the sandbox to run code.", model, tools });
59
+ ```
60
+
61
+ ## ComputeSDK
62
+
63
+ ```ts
64
+ import { quietrobot } from "@quietrobot/sandboxes-ai/computesdk";
65
+
66
+ const provider = quietrobot({ apiKey: process.env.QR_API_KEY });
67
+ const sbx = await provider.instances.create();
68
+ console.log((await sbx.runCommand("echo hi")).stdout);
69
+ await sbx.filesystem.writeFile("notes.txt", "hello");
70
+ await sbx.destroy();
71
+ ```
72
+
73
+ ## Options
74
+
75
+ ```ts
76
+ sandboxTools({
77
+ create: { egress: { mode: "allowlist", allow: ["pypi.org", "github.com"] }, timeoutSec: 3600 },
78
+ tools: ["run_command", "read_file", "write_file"], // a subset
79
+ noWaitForApproval: true, // tell the model a command is waiting instead of waiting for the decision
80
+ sandbox, // or work in a sandbox you already have (close() leaves it alone)
81
+ });
82
+ ```
83
+
84
+ Pass the same `session` to two adapters to share one sandbox between them.
85
+
86
+ Licensed under Apache 2.0.
@@ -0,0 +1,11 @@
1
+ import { type CreateOptions, Sandbox } from "@quietrobot/sandboxes";
2
+ export interface QuietRobotConfig {
3
+ apiKey?: string;
4
+ baseUrl?: string;
5
+ /** Defaults for every sandbox: egress, region, secrets... */
6
+ create?: CreateOptions;
7
+ }
8
+ export declare const quietrobot: (config: QuietRobotConfig & import("computesdk").ProcessRuntimeOptions) => import("computesdk").Provider<Sandbox, any, any, import("computesdk").Volume> & {
9
+ readonly sizes: import("computesdk").InstanceSizeManager;
10
+ readonly regions: import("computesdk").RegionManager;
11
+ };
@@ -0,0 +1,112 @@
1
+ /**
2
+ * A ComputeSDK provider, so code written for ComputeSDK runs on Quiet Robot
3
+ * Sandboxes.
4
+ *
5
+ * import { createCompute } from "computesdk";
6
+ * import { quietrobot } from "@quietrobot/sandboxes-ai/computesdk";
7
+ * const compute = createCompute({ provider: quietrobot({ apiKey: process.env.QR_API_KEY }) });
8
+ * const sbx = await compute.sandbox.create();
9
+ * const r = await sbx.runCommand("echo hi");
10
+ */
11
+ import { defineProvider } from "computesdk";
12
+ import { Sandboxes } from "@quietrobot/sandboxes";
13
+ const clients = new WeakMap();
14
+ const client = (c) => {
15
+ let x = clients.get(c);
16
+ if (!x)
17
+ clients.set(c, (x = new Sandboxes({ apiKey: c.apiKey, baseUrl: c.baseUrl })));
18
+ return x;
19
+ };
20
+ const STATUS = { running: "running", starting: "running", error: "error" };
21
+ async function runCommand(s, command, o = {}) {
22
+ const t = Date.now();
23
+ if (o.background) {
24
+ await s.spawn(command, { cwd: o.cwd, env: o.env, timeoutMs: o.timeout ?? 0 });
25
+ return { stdout: "", stderr: "", exitCode: 0, durationMs: Date.now() - t };
26
+ }
27
+ const e = await s.exec(command, { cwd: o.cwd, env: o.env, timeoutMs: o.timeout, onStdout: o.onStdout, onStderr: o.onStderr });
28
+ return { stdout: e.stdout ?? "", stderr: e.stderr ?? "", exitCode: e.exitCode ?? (e.status === "completed" ? 0 : 1), durationMs: e.durationMs ?? Date.now() - t };
29
+ }
30
+ export const quietrobot = defineProvider({
31
+ name: "quietrobot",
32
+ methods: {
33
+ instances: {
34
+ create: async (config, options = {}) => {
35
+ const o = options;
36
+ const s = await client(config).create({
37
+ ...config.create,
38
+ name: o.name,
39
+ timeoutSec: o.timeout ? Math.max(10, Math.round(o.timeout / 1000)) : config.create?.timeoutSec,
40
+ snapshotId: o.snapshotId ?? config.create?.snapshotId,
41
+ template: o.templateId === "minimal" || o.templateId === "base" ? o.templateId : config.create?.template,
42
+ env: { ...config.create?.env, ...o.envs },
43
+ metadata: { ...config.create?.metadata, ...o.metadata },
44
+ cpus: o.cpus ?? o.cpu ?? o.vcpus ?? config.create?.cpus,
45
+ memoryMb: o.memoryMb ?? o.memoryMiB ?? o.memory ?? config.create?.memoryMb,
46
+ });
47
+ return { instance: s, instanceId: s.id };
48
+ },
49
+ getById: async (config, id) => {
50
+ try {
51
+ const s = await client(config).get(id);
52
+ return { instance: s, instanceId: s.id };
53
+ }
54
+ catch {
55
+ return null;
56
+ }
57
+ },
58
+ list: async (config) => {
59
+ const rows = await client(config).list("running");
60
+ return Promise.all(rows.map(async (r) => ({ instance: await client(config).get(r.id), instanceId: r.id })));
61
+ },
62
+ destroy: async (config, id) => {
63
+ await (await client(config).get(id)).destroy();
64
+ },
65
+ runCommand: (s, command, options) => runCommand(s, command, options),
66
+ streamCommand: (s, command, options) => runCommand(s, command, options),
67
+ getInfo: async (s) => {
68
+ const i = await s.refresh();
69
+ return {
70
+ id: i.id,
71
+ provider: "quietrobot",
72
+ status: STATUS[i.status] ?? "stopped",
73
+ createdAt: new Date(i.createdAt),
74
+ timeout: Math.max(0, new Date(i.deadlineAt).getTime() - Date.now()),
75
+ metadata: i.metadata,
76
+ };
77
+ },
78
+ getUrl: async (s, { port, public: isPublic }) => (await s.ports.expose(port, isPublic === false ? "private" : "public")).url,
79
+ pause: async (s) => {
80
+ await s.pause();
81
+ },
82
+ resume: async (s) => {
83
+ await s.resume();
84
+ },
85
+ pauseCapabilities: { memory: true },
86
+ extendLifetime: async (s, ms) => {
87
+ const left = new Date(s.info.deadlineAt).getTime() - Date.now();
88
+ await s.setTimeout(Math.max(10, Math.round((left + ms) / 1000)));
89
+ },
90
+ getInstance: (s) => s,
91
+ filesystem: {
92
+ readFile: async (s, path) => s.files.readText(path),
93
+ writeFile: async (s, path, content) => {
94
+ await s.files.write(path, content);
95
+ },
96
+ mkdir: async (s, path) => {
97
+ await s.exec(`mkdir -p '${path.replace(/'/g, `'\\''`)}'`);
98
+ },
99
+ readdir: async (s, path) => (await s.files.list(path)).entries.map((e) => ({
100
+ name: e.name,
101
+ type: e.type === "dir" || e.type === "directory" ? "directory" : "file",
102
+ size: e.size,
103
+ modified: e.modified ? new Date(e.modified) : undefined,
104
+ })),
105
+ exists: async (s, path) => (await s.exec(`test -e '${path.replace(/'/g, `'\\''`)}'`)).exitCode === 0,
106
+ remove: async (s, path) => {
107
+ await s.files.remove(path);
108
+ },
109
+ },
110
+ },
111
+ },
112
+ });
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Sandbox tools for agent frameworks. Each framework has its own entry:
3
+ *
4
+ * import { sandboxTools } from "@quietrobot/sandboxes-ai/vercel-ai";
5
+ * import { sandboxTools } from "@quietrobot/sandboxes-ai/openai-agents";
6
+ * import { sandboxTools } from "@quietrobot/sandboxes-ai/langchain";
7
+ * import { sandboxTools } from "@quietrobot/sandboxes-ai/mastra";
8
+ * import { quietrobot } from "@quietrobot/sandboxes-ai/computesdk";
9
+ *
10
+ * The tools share one SandboxSession: a sandbox started on first use and
11
+ * destroyed by session.close(). Every command goes through the
12
+ * organization's policy; one a person denies comes back to the model as a
13
+ * plain "Denied" answer rather than an exception.
14
+ */
15
+ import { type CreateOptions, Sandbox, Sandboxes } from "@quietrobot/sandboxes";
16
+ import { z } from "zod";
17
+ export interface SessionOptions {
18
+ /** Use this sandbox instead of starting one (it is not destroyed by close()). */
19
+ sandbox?: Sandbox;
20
+ client?: Sandboxes;
21
+ /** Settings for the sandbox started on first use: egress, secrets, timeoutSec, region... */
22
+ create?: CreateOptions;
23
+ /** Don't wait for a person when a rule holds a command: tell the model it's waiting. Default false (wait). */
24
+ noWaitForApproval?: boolean;
25
+ }
26
+ /** One sandbox an agent works in, started on first use. */
27
+ export declare class SandboxSession {
28
+ private opts;
29
+ private s?;
30
+ private own;
31
+ constructor(opts?: SessionOptions);
32
+ sandbox(): Promise<Sandbox>;
33
+ /** Destroys the sandbox this session started. */
34
+ close(): Promise<void>;
35
+ [Symbol.asyncDispose](): Promise<void>;
36
+ /** @internal */
37
+ get waitForApproval(): boolean;
38
+ }
39
+ export type FieldType = "string" | "number" | "boolean";
40
+ export interface Field {
41
+ type: FieldType;
42
+ description: string;
43
+ optional?: boolean;
44
+ }
45
+ export interface ToolSpec {
46
+ name: string;
47
+ description: string;
48
+ fields: Record<string, Field>;
49
+ run: (session: SandboxSession, input: Record<string, any>) => Promise<string>;
50
+ }
51
+ export declare const TOOLS: ToolSpec[];
52
+ export type ToolName = "run_command" | "run_code" | "read_file" | "write_file" | "list_files" | "expose_port";
53
+ /**
54
+ * The zod object for a tool's input. strict: every field required, optional
55
+ * ones as nullable (what OpenAI's strict function calling wants).
56
+ */
57
+ export declare function schemaFor(spec: ToolSpec, strict?: boolean): z.ZodObject<{
58
+ [x: string]: z.ZodTypeAny<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>;
59
+ }, z.core.$strip>;
60
+ export declare function pick(names?: ToolName[]): ToolSpec[];
61
+ export { Sandbox, Sandboxes };
package/dist/index.js ADDED
@@ -0,0 +1,156 @@
1
+ /**
2
+ * Sandbox tools for agent frameworks. Each framework has its own entry:
3
+ *
4
+ * import { sandboxTools } from "@quietrobot/sandboxes-ai/vercel-ai";
5
+ * import { sandboxTools } from "@quietrobot/sandboxes-ai/openai-agents";
6
+ * import { sandboxTools } from "@quietrobot/sandboxes-ai/langchain";
7
+ * import { sandboxTools } from "@quietrobot/sandboxes-ai/mastra";
8
+ * import { quietrobot } from "@quietrobot/sandboxes-ai/computesdk";
9
+ *
10
+ * The tools share one SandboxSession: a sandbox started on first use and
11
+ * destroyed by session.close(). Every command goes through the
12
+ * organization's policy; one a person denies comes back to the model as a
13
+ * plain "Denied" answer rather than an exception.
14
+ */
15
+ import { CommandDeniedError, Sandbox, Sandboxes, SandboxesError } from "@quietrobot/sandboxes";
16
+ import { z } from "zod";
17
+ const MAX = 20_000;
18
+ const clip = (s) => {
19
+ s ??= "";
20
+ return s.length <= MAX ? s : `${s.slice(0, MAX / 2)}\n...[${s.length - MAX} characters cut]...\n${s.slice(-MAX / 2)}`;
21
+ };
22
+ /** One sandbox an agent works in, started on first use. */
23
+ export class SandboxSession {
24
+ opts;
25
+ s;
26
+ own;
27
+ constructor(opts = {}) {
28
+ this.opts = opts;
29
+ this.own = !opts.sandbox;
30
+ if (opts.sandbox)
31
+ this.s = Promise.resolve(opts.sandbox);
32
+ }
33
+ sandbox() {
34
+ this.s ??= (this.opts.client ?? new Sandboxes()).create({ timeoutSec: 1800, ...this.opts.create });
35
+ return this.s;
36
+ }
37
+ /** Destroys the sandbox this session started. */
38
+ async close() {
39
+ if (this.s && this.own)
40
+ await (await this.s).destroy().catch(() => { });
41
+ this.s = undefined;
42
+ }
43
+ async [Symbol.asyncDispose]() {
44
+ await this.close();
45
+ }
46
+ /** @internal */
47
+ get waitForApproval() {
48
+ return !this.opts.noWaitForApproval;
49
+ }
50
+ }
51
+ async function guard(f) {
52
+ try {
53
+ return await f();
54
+ }
55
+ catch (e) {
56
+ if (e instanceof CommandDeniedError)
57
+ return `Denied: ${e.message}. Don't retry it; try another way or ask the user.`;
58
+ if (e instanceof SandboxesError)
59
+ return `Error ${e.status} ${e.code}: ${e.message}`;
60
+ throw e;
61
+ }
62
+ }
63
+ const pending = (id) => `Waiting for a person to approve this command (execution ${id}). Don't run it again.`;
64
+ export const TOOLS = [
65
+ {
66
+ name: "run_command",
67
+ description: "Run a shell command in the sandbox (a Linux microVM; home is /home/sandbox) and get its exit code, stdout and stderr.",
68
+ fields: {
69
+ command: { type: "string", description: "The shell command" },
70
+ cwd: { type: "string", description: "Working directory", optional: true },
71
+ timeoutSeconds: { type: "number", description: "Time limit in seconds (default 60, up to 3600)", optional: true },
72
+ },
73
+ run: (session, i) => guard(async () => {
74
+ const s = await session.sandbox();
75
+ const e = await s.exec(i.command, { cwd: i.cwd ?? undefined, timeoutMs: i.timeoutSeconds ? i.timeoutSeconds * 1000 : undefined, waitForApproval: session.waitForApproval });
76
+ if (e.status === "pending_approval")
77
+ return pending(e.id);
78
+ return JSON.stringify({ exitCode: e.exitCode, timedOut: e.timedOut || undefined, stdout: clip(e.stdout), stderr: clip(e.stderr) });
79
+ }),
80
+ },
81
+ {
82
+ name: "run_code",
83
+ description: "Run Python in a notebook-style kernel in the sandbox. Variables persist between calls. Returns printed output, the last expression's value and any error.",
84
+ fields: { code: { type: "string", description: "Python code" } },
85
+ run: (session, i) => guard(async () => {
86
+ const s = await session.sandbox();
87
+ const r = await s.runCode(i.code, { waitForApproval: session.waitForApproval });
88
+ if (r.execution.status === "pending_approval")
89
+ return pending(r.execution.id);
90
+ const value = r.results.find((x) => !x.png)?.text;
91
+ const figures = r.results.filter((x) => x.png).length;
92
+ return JSON.stringify({
93
+ stdout: clip(r.stdout),
94
+ stderr: r.stderr ? clip(r.stderr) : undefined,
95
+ result: value !== undefined ? clip(value) : undefined,
96
+ figures: figures || undefined,
97
+ error: r.error ? clip(r.error.traceback || `${r.error.name}: ${r.error.value}`) : undefined,
98
+ });
99
+ }),
100
+ },
101
+ {
102
+ name: "read_file",
103
+ description: "Read a text file from the sandbox.",
104
+ fields: { path: { type: "string", description: "File path; relative paths are in /home/sandbox" } },
105
+ run: (session, i) => guard(async () => clip(await (await session.sandbox()).files.readText(i.path))),
106
+ },
107
+ {
108
+ name: "write_file",
109
+ description: "Create or replace a text file in the sandbox.",
110
+ fields: { path: { type: "string", description: "File path" }, content: { type: "string", description: "The file's text" } },
111
+ run: (session, i) => guard(async () => {
112
+ const r = await (await session.sandbox()).files.write(i.path, i.content);
113
+ return `Wrote ${r.bytes} bytes to ${r.path}`;
114
+ }),
115
+ },
116
+ {
117
+ name: "list_files",
118
+ description: "List a folder in the sandbox.",
119
+ fields: { path: { type: "string", description: "Folder; the home folder if left out", optional: true } },
120
+ run: (session, i) => guard(async () => {
121
+ const r = await (await session.sandbox()).files.list(i.path ?? undefined);
122
+ return r.entries.map((e) => `${e.type}\t${e.size}\t${e.path}`).join("\n") || "(empty)";
123
+ }),
124
+ },
125
+ {
126
+ name: "expose_port",
127
+ description: "Give a web server running in the sandbox (bound to 0.0.0.0) a URL. Private URLs need a token; shareUrl signs a browser in. Public ones are open to anyone.",
128
+ fields: {
129
+ port: { type: "number", description: "The port" },
130
+ public: { type: "boolean", description: "Anyone with the URL may open it", optional: true },
131
+ },
132
+ run: (session, i) => guard(async () => {
133
+ const p = await (await session.sandbox()).ports.expose(i.port, i.public ? "public" : "private");
134
+ return JSON.stringify({ url: p.url, shareUrl: p.shareUrl ?? undefined });
135
+ }),
136
+ },
137
+ ];
138
+ /**
139
+ * The zod object for a tool's input. strict: every field required, optional
140
+ * ones as nullable (what OpenAI's strict function calling wants).
141
+ */
142
+ export function schemaFor(spec, strict = false) {
143
+ const shape = {};
144
+ for (const [k, f] of Object.entries(spec.fields)) {
145
+ let t = f.type === "string" ? z.string() : f.type === "number" ? z.number() : z.boolean();
146
+ t = t.describe(f.description);
147
+ if (f.optional)
148
+ t = strict ? t.nullable() : t.optional();
149
+ shape[k] = t;
150
+ }
151
+ return z.object(shape);
152
+ }
153
+ export function pick(names) {
154
+ return names ? TOOLS.filter((t) => names.includes(t.name)) : TOOLS;
155
+ }
156
+ export { Sandbox, Sandboxes };
@@ -0,0 +1,9 @@
1
+ import { SandboxSession, type SessionOptions, type ToolName } from "./index.js";
2
+ export declare function sandboxTools(opts?: SessionOptions & {
3
+ tools?: ToolName[];
4
+ session?: SandboxSession;
5
+ }): {
6
+ tools: import("@langchain/core/tools").DynamicStructuredTool<any, Record<string, unknown>, unknown, string, unknown, string>[];
7
+ session: SandboxSession;
8
+ };
9
+ export { SandboxSession };
@@ -0,0 +1,16 @@
1
+ /**
2
+ * LangChain / LangGraph tools.
3
+ *
4
+ * import { createAgent } from "langchain";
5
+ * import { sandboxTools } from "@quietrobot/sandboxes-ai/langchain";
6
+ * const { tools, session } = sandboxTools();
7
+ * const agent = createAgent({ model, tools });
8
+ */
9
+ import { tool } from "@langchain/core/tools";
10
+ import { pick, schemaFor, SandboxSession } from "./index.js";
11
+ export function sandboxTools(opts = {}) {
12
+ const session = opts.session ?? new SandboxSession(opts);
13
+ const tools = pick(opts.tools).map((spec) => tool((input) => spec.run(session, input), { name: spec.name, description: spec.description, schema: schemaFor(spec) }));
14
+ return { tools, session };
15
+ }
16
+ export { SandboxSession };
@@ -0,0 +1,9 @@
1
+ import { SandboxSession, type SessionOptions, type ToolName } from "./index.js";
2
+ export declare function sandboxTools(opts?: SessionOptions & {
3
+ tools?: ToolName[];
4
+ session?: SandboxSession;
5
+ }): {
6
+ tools: Record<string, import("@mastra/core/tools").Tool<any, any, any, any, import("@mastra/core/tools").ToolExecutionContext<any, any, unknown>, string, unknown>>;
7
+ session: SandboxSession;
8
+ };
9
+ export { SandboxSession };
package/dist/mastra.js ADDED
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Mastra tools.
3
+ *
4
+ * import { Agent } from "@mastra/core/agent";
5
+ * import { sandboxTools } from "@quietrobot/sandboxes-ai/mastra";
6
+ * const { tools, session } = sandboxTools();
7
+ * const agent = new Agent({ name: "coder", instructions: "...", model, tools });
8
+ */
9
+ import { createTool } from "@mastra/core/tools";
10
+ import { pick, schemaFor, SandboxSession } from "./index.js";
11
+ export function sandboxTools(opts = {}) {
12
+ const session = opts.session ?? new SandboxSession(opts);
13
+ const tools = {};
14
+ for (const spec of pick(opts.tools)) {
15
+ tools[spec.name] = createTool({
16
+ id: spec.name,
17
+ description: spec.description,
18
+ inputSchema: schemaFor(spec),
19
+ execute: async (input) => spec.run(session, input),
20
+ });
21
+ }
22
+ return { tools, session };
23
+ }
24
+ export { SandboxSession };
@@ -0,0 +1,9 @@
1
+ import { SandboxSession, type SessionOptions, type ToolName } from "./index.js";
2
+ export declare function sandboxTools(opts?: SessionOptions & {
3
+ tools?: ToolName[];
4
+ session?: SandboxSession;
5
+ }): {
6
+ tools: import("@openai/agents-core").FunctionTool<unknown, any, string>[];
7
+ session: SandboxSession;
8
+ };
9
+ export { SandboxSession };
@@ -0,0 +1,23 @@
1
+ /**
2
+ * OpenAI Agents SDK tools.
3
+ *
4
+ * import { Agent, run } from "@openai/agents";
5
+ * import { sandboxTools } from "@quietrobot/sandboxes-ai/openai-agents";
6
+ * const { tools, session } = sandboxTools();
7
+ * const agent = new Agent({ name: "coder", instructions: "...", tools });
8
+ * await run(agent, "...");
9
+ * await session.close();
10
+ */
11
+ import { tool } from "@openai/agents";
12
+ import { pick, schemaFor, SandboxSession } from "./index.js";
13
+ export function sandboxTools(opts = {}) {
14
+ const session = opts.session ?? new SandboxSession(opts);
15
+ const tools = pick(opts.tools).map((spec) => tool({
16
+ name: spec.name,
17
+ description: spec.description,
18
+ parameters: schemaFor(spec, true),
19
+ execute: (input) => spec.run(session, input),
20
+ }));
21
+ return { tools, session };
22
+ }
23
+ export { SandboxSession };
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Vercel AI SDK tools.
3
+ *
4
+ * import { generateText } from "ai";
5
+ * import { sandboxTools } from "@quietrobot/sandboxes-ai/vercel-ai";
6
+ * const { tools, session } = sandboxTools();
7
+ * const r = await generateText({ model, tools, prompt: "...", stopWhen: stepCountIs(10) });
8
+ * await session.close();
9
+ */
10
+ import { type Tool } from "ai";
11
+ import { SandboxSession, type SessionOptions, type ToolName } from "./index.js";
12
+ export declare function sandboxTools(opts?: SessionOptions & {
13
+ tools?: ToolName[];
14
+ session?: SandboxSession;
15
+ }): {
16
+ tools: Record<string, Tool>;
17
+ session: SandboxSession;
18
+ };
19
+ export { SandboxSession };
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Vercel AI SDK tools.
3
+ *
4
+ * import { generateText } from "ai";
5
+ * import { sandboxTools } from "@quietrobot/sandboxes-ai/vercel-ai";
6
+ * const { tools, session } = sandboxTools();
7
+ * const r = await generateText({ model, tools, prompt: "...", stopWhen: stepCountIs(10) });
8
+ * await session.close();
9
+ */
10
+ import { tool } from "ai";
11
+ import { pick, schemaFor, SandboxSession } from "./index.js";
12
+ export function sandboxTools(opts = {}) {
13
+ const session = opts.session ?? new SandboxSession(opts);
14
+ const tools = {};
15
+ for (const spec of pick(opts.tools)) {
16
+ tools[spec.name] = tool({
17
+ description: spec.description,
18
+ inputSchema: schemaFor(spec),
19
+ execute: (input) => spec.run(session, input),
20
+ });
21
+ }
22
+ return { tools, session };
23
+ }
24
+ export { SandboxSession };
package/package.json CHANGED
@@ -1,6 +1,59 @@
1
1
  {
2
2
  "name": "@quietrobot/sandboxes-ai",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.1",
4
+ "description": "Quiet Robot Sandboxes tools for the Vercel AI SDK, OpenAI Agents SDK, LangChain, Mastra and ComputeSDK",
5
+ "keywords": ["ai-sdk", "openai-agents", "langchain", "mastra", "computesdk", "sandbox", "tools", "quietrobot"],
6
+ "homepage": "https://quietrobot.ai/sandboxes",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/Quiet-Robot/sandboxes-sdk.git",
10
+ "directory": "ai"
11
+ },
12
+ "type": "module",
13
+ "main": "dist/index.js",
14
+ "types": "dist/index.d.ts",
15
+ "exports": {
16
+ ".": { "types": "./dist/index.d.ts", "import": "./dist/index.js" },
17
+ "./vercel-ai": { "types": "./dist/vercel-ai.d.ts", "import": "./dist/vercel-ai.js" },
18
+ "./openai-agents": { "types": "./dist/openai-agents.d.ts", "import": "./dist/openai-agents.js" },
19
+ "./langchain": { "types": "./dist/langchain.d.ts", "import": "./dist/langchain.js" },
20
+ "./mastra": { "types": "./dist/mastra.d.ts", "import": "./dist/mastra.js" },
21
+ "./computesdk": { "types": "./dist/computesdk.d.ts", "import": "./dist/computesdk.js" }
22
+ },
23
+ "files": ["dist", "README.md", "LICENSE"],
24
+ "sideEffects": false,
25
+ "scripts": {
26
+ "build": "tsc -p .",
27
+ "prepack": "tsc -p ."
28
+ },
29
+ "dependencies": {
30
+ "@quietrobot/sandboxes": "^0.2.1"
31
+ },
32
+ "peerDependencies": {
33
+ "zod": "^3.25.0 || ^4.0.0",
34
+ "ai": ">=5",
35
+ "@openai/agents": ">=0.1",
36
+ "@langchain/core": ">=0.3",
37
+ "@mastra/core": ">=0.20",
38
+ "computesdk": ">=4"
39
+ },
40
+ "peerDependenciesMeta": {
41
+ "ai": { "optional": true },
42
+ "@openai/agents": { "optional": true },
43
+ "@langchain/core": { "optional": true },
44
+ "@mastra/core": { "optional": true },
45
+ "computesdk": { "optional": true }
46
+ },
47
+ "devDependencies": {
48
+ "@langchain/core": "^1.5.1",
49
+ "@mastra/core": "^1.86.0",
50
+ "@openai/agents": "^0.23.1",
51
+ "ai": "^7.0.0",
52
+ "computesdk": "^4.1.27",
53
+ "typescript": "~5.9.0",
54
+ "zod": "^4.0.0"
55
+ },
56
+ "publishConfig": { "access": "public" },
57
+ "license": "Apache-2.0",
58
+ "engines": { "node": ">=20" }
59
+ }