@groundbox/sandcastle 0.0.0-stage → 0.1.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 +9 -0
- package/README.md +125 -2
- package/dist/client.d.ts +14 -0
- package/dist/client.js +11 -0
- package/dist/exec.d.ts +47 -0
- package/dist/exec.js +90 -0
- package/dist/files.d.ts +16 -0
- package/dist/files.js +62 -0
- package/dist/index.d.ts +53 -0
- package/dist/index.js +128 -0
- package/dist/interactive.d.ts +16 -0
- package/dist/interactive.js +63 -0
- package/package.json +56 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Groundbox
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
|
6
|
+
|
|
7
|
+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
|
8
|
+
|
|
9
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,126 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @groundbox/sandcastle
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A [Groundbox](https://groundbox.dev) sandbox provider for [Sandcastle](https://github.com/mattpocock/sandcastle). Each run gets its own Groundbox sandbox, a Firecracker microVM with dedicated cores. Sandcastle copies your repo in, the agent works there, and its commits come back to a branch on your machine.
|
|
4
|
+
|
|
5
|
+
`groundbox()` is an isolated provider, like Sandcastle's own `e2b()`, `modal()` and `vercel()`. It works with `run()`, `createSandbox()` and `interactive()`.
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
npm install @ai-hero/sandcastle @groundbox/sandcastle
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
Node 22 or later.
|
|
14
|
+
|
|
15
|
+
## API key
|
|
16
|
+
|
|
17
|
+
Create a key at https://app.groundbox.dev/keys and set it in your shell:
|
|
18
|
+
|
|
19
|
+
```bash
|
|
20
|
+
export GROUNDBOX_API_KEY=gbx_...
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
Or pass `apiKey` to `groundbox()`. Don't put the key in `.sandcastle/.env`: Sandcastle forwards the keys declared there into the sandbox, where the agent can read them.
|
|
24
|
+
|
|
25
|
+
No account yet? `npx -y @groundbox/cli signup --name my-agent` gets a key with $1 of free sandbox use and no card.
|
|
26
|
+
|
|
27
|
+
## Use it
|
|
28
|
+
|
|
29
|
+
```typescript
|
|
30
|
+
import { run, claudeCode } from "@ai-hero/sandcastle";
|
|
31
|
+
import { groundbox } from "@groundbox/sandcastle";
|
|
32
|
+
|
|
33
|
+
await run({
|
|
34
|
+
agent: claudeCode("claude-opus-4-8"),
|
|
35
|
+
sandbox: groundbox(),
|
|
36
|
+
prompt: "Fix issue #42 in this repo.",
|
|
37
|
+
hooks: {
|
|
38
|
+
sandbox: {
|
|
39
|
+
onSandboxReady: [
|
|
40
|
+
// The default image has no agent CLI: install the one you use.
|
|
41
|
+
{ command: "npm install -g @anthropic-ai/claude-code", sudo: true, timeoutMs: 300_000 },
|
|
42
|
+
{ command: "npm install", timeoutMs: 300_000 },
|
|
43
|
+
],
|
|
44
|
+
},
|
|
45
|
+
},
|
|
46
|
+
});
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
Put the agent's own login (`ANTHROPIC_API_KEY`, `CLAUDE_CODE_OAUTH_TOKEN` and so on) in `.sandcastle/.env` as usual; Sandcastle passes it into the sandbox.
|
|
50
|
+
|
|
51
|
+
`createSandbox()` keeps one sandbox for several runs:
|
|
52
|
+
|
|
53
|
+
```typescript
|
|
54
|
+
import { createSandbox, claudeCode } from "@ai-hero/sandcastle";
|
|
55
|
+
import { groundbox } from "@groundbox/sandcastle";
|
|
56
|
+
|
|
57
|
+
await using sandbox = await createSandbox({
|
|
58
|
+
branch: "agent/fix-42",
|
|
59
|
+
sandbox: groundbox({ cpus: 4, memory_gb: 8 }),
|
|
60
|
+
});
|
|
61
|
+
await sandbox.run({ agent: claudeCode("claude-opus-4-8"), prompt: "Fix issue #42." });
|
|
62
|
+
const tests = await sandbox.exec("npm test");
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
## Options
|
|
66
|
+
|
|
67
|
+
Every `create_sandbox` option of [`@groundbox/sdk`](https://www.npmjs.com/package/@groundbox/sdk) passes through, so a sandbox can be sized, started from an image or a template, and fenced in:
|
|
68
|
+
|
|
69
|
+
```typescript
|
|
70
|
+
groundbox({
|
|
71
|
+
cpus: 4, // vCPUs (memory up to 4 GB per vCPU is included)
|
|
72
|
+
memory_gb: 8,
|
|
73
|
+
disk_gb: 20,
|
|
74
|
+
image: "node:22-bookworm", // start from a public Docker image (runs as root)
|
|
75
|
+
template: "my-template", // or from a Groundbox template you built
|
|
76
|
+
allow_hosts: ["github.com", "registry.npmjs.org", "api.anthropic.com"], // egress allowlist
|
|
77
|
+
secrets: ["GITHUB_TOKEN"], // team secrets, set as env vars in the sandbox
|
|
78
|
+
metadata: { project: "alpha" },
|
|
79
|
+
timeout_minutes: 60, // the sandbox's whole lifetime (default 60)
|
|
80
|
+
|
|
81
|
+
// Provider options
|
|
82
|
+
apiKey: process.env.GROUNDBOX_API_KEY,
|
|
83
|
+
env: { MY_VAR: "value" }, // merged at launch, like docker()'s env
|
|
84
|
+
maxOutputTailChars: 65_536, // output kept per stream in ExecResult when streaming
|
|
85
|
+
commandTimeoutSeconds: 3600, // one command's limit (default: timeout_minutes)
|
|
86
|
+
});
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
## How it maps
|
|
90
|
+
|
|
91
|
+
| Sandcastle | Groundbox |
|
|
92
|
+
| --- | --- |
|
|
93
|
+
| `create()` | `create_sandbox`, then `wait_for_sandbox` if it is still coming up. Makes `$HOME/workspace`. |
|
|
94
|
+
| `worktreePath` | `/home/runner/workspace` on the default image, `/root/workspace` from a Docker image |
|
|
95
|
+
| `exec` with `onLine` | an exec stream: stdout reaches `onLine` line by line while the command runs. Resumable, so a dropped connection doesn't end the agent. |
|
|
96
|
+
| `exec` with `stdin` | written to the command's stdin, which is then closed |
|
|
97
|
+
| `exec` with `sudo: true` | the image's passwordless `sudo` (the default image runs as `runner`); nothing to do from a Docker image, where commands already run as root |
|
|
98
|
+
| `interactiveExec` | the same stream on a terminal (`tty`) when your stdin is a TTY, with raw keys and window resizes passed through |
|
|
99
|
+
| `copyIn` | `write_file` for a file (mode kept), `upload_files` (one tar.gz) for a directory, symlinks and empty folders included |
|
|
100
|
+
| `copyFileOut` | `read_file` |
|
|
101
|
+
| `close()` | `delete_sandbox` |
|
|
102
|
+
| `sandboxId` | the Groundbox sandbox id (`sbx_...`), for `groundbox sandbox exec` or the dashboard |
|
|
103
|
+
|
|
104
|
+
The default image is Ubuntu 24.04 with git, Node 22 and npm. From a Docker image, the provider sets `IS_SANDBOX=1`, which Claude Code needs before it skips its permission checks as root; the image needs `sh` and `git`.
|
|
105
|
+
|
|
106
|
+
## Limits
|
|
107
|
+
|
|
108
|
+
- **No agent CLI in the default image.** Install it in a `sandbox.onSandboxReady` hook (Claude Code installs in about 7 seconds), use a Docker image that has it, or build a Groundbox template with it once (`npm: ["@anthropic-ai/claude-code"]`) for a warm start.
|
|
109
|
+
- **Lifetime.** A sandbox lives for `timeout_minutes` (default 60) and is then deleted by Groundbox, so the timeout must cover setup, the agent run and syncing commits back. It is also the backstop when the host process dies without `close()`: there is no background reaper.
|
|
110
|
+
- **Free trial.** $1 of use, 2 sandboxes at a time, up to 2 vCPU and 4 GB, 60 minutes each. Templates, volumes and snapshots need the paid plan.
|
|
111
|
+
- **`interactive()`** is implemented on Groundbox's terminal stream and was tested on a real pseudo-terminal (keys in, output out, exit code back), but not yet with a logged-in agent's full TUI.
|
|
112
|
+
- **Git identity on the host.** Sandcastle needs `git config user.name` and `user.email` on the machine that calls `run()`. On a bare CI machine without them, a run finishes but brings back no commits.
|
|
113
|
+
- Groundbox features Sandcastle has no place for (pause and resume, fork, save points, previews) aren't used. Reach them with `@groundbox/sdk` and the handle's `sandboxId`.
|
|
114
|
+
|
|
115
|
+
## Tests
|
|
116
|
+
|
|
117
|
+
```bash
|
|
118
|
+
npm test # unit tests on a fake Groundbox, incl. a full Sandcastle run()
|
|
119
|
+
GROUNDBOX_API_KEY=gbx_... npm test # plus live tests against the real API
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
The live tests start real sandboxes (and delete them): the handle contract, `run()` and `createSandbox()` with a scripted agent that commits, and a run from a Docker image.
|
|
123
|
+
|
|
124
|
+
## License
|
|
125
|
+
|
|
126
|
+
MIT. See [LICENSE](./LICENSE).
|
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The part of the `@groundbox/sdk` client this provider uses. Tests pass a
|
|
3
|
+
* fake with the same shape through the `client` option.
|
|
4
|
+
*/
|
|
5
|
+
import type { Groundbox } from "@groundbox/sdk";
|
|
6
|
+
export type GroundboxClient = Pick<Groundbox, "create_sandbox" | "wait_for_sandbox" | "delete_sandbox" | "stream_command" | "write_file" | "read_file" | "upload_files">;
|
|
7
|
+
/** A file for `upload_files`: a path relative to the folder, and bytes or a symlink target. */
|
|
8
|
+
export type UploadFile = Parameters<Groundbox["upload_files"]>[2][number];
|
|
9
|
+
/** A running command, as `stream_command` returns it. */
|
|
10
|
+
export type CommandStream = ReturnType<Groundbox["stream_command"]>;
|
|
11
|
+
/** Single-quote a string for a POSIX shell. */
|
|
12
|
+
export declare const shellEscape: (s: string) => string;
|
|
13
|
+
/** Whether an error is the API's "nothing there" answer. */
|
|
14
|
+
export declare const isNotFound: (error: unknown) => boolean;
|
package/dist/client.js
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The part of the `@groundbox/sdk` client this provider uses. Tests pass a
|
|
3
|
+
* fake with the same shape through the `client` option.
|
|
4
|
+
*/
|
|
5
|
+
/** Single-quote a string for a POSIX shell. */
|
|
6
|
+
export const shellEscape = (s) => `'${s.replaceAll("'", String.raw `'\''`)}'`;
|
|
7
|
+
/** Whether an error is the API's "nothing there" answer. */
|
|
8
|
+
export const isNotFound = (error) => typeof error === "object" &&
|
|
9
|
+
error !== null &&
|
|
10
|
+
(("code" in error && error.code === "not_found") ||
|
|
11
|
+
("status" in error && error.status === 404));
|
package/dist/exec.d.ts
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The handle's `exec`: each command runs over a Groundbox exec stream, so
|
|
3
|
+
* stdout reaches `onLine` line by line while the command runs. `stdin` is
|
|
4
|
+
* written to the command and then closed.
|
|
5
|
+
*/
|
|
6
|
+
import type { ExecResult } from "@ai-hero/sandcastle";
|
|
7
|
+
import { type GroundboxClient } from "./client.js";
|
|
8
|
+
/** Default characters of output kept per stream when `onLine` is given. */
|
|
9
|
+
export declare const MAX_TAIL_CHARS: number;
|
|
10
|
+
/** The options Sandcastle passes to `exec`. */
|
|
11
|
+
export interface ExecOptions {
|
|
12
|
+
onLine?: (line: string) => void;
|
|
13
|
+
cwd?: string;
|
|
14
|
+
sudo?: boolean;
|
|
15
|
+
stdin?: string;
|
|
16
|
+
}
|
|
17
|
+
/** A rolling tail of text, at most `max` characters long. */
|
|
18
|
+
export declare class Tail {
|
|
19
|
+
private readonly max;
|
|
20
|
+
private text;
|
|
21
|
+
constructor(max: number);
|
|
22
|
+
push(chunk: string): void;
|
|
23
|
+
toString(): string;
|
|
24
|
+
}
|
|
25
|
+
/** Split streamed stdout into lines for `onLine`. */
|
|
26
|
+
export declare class LineSplitter {
|
|
27
|
+
private readonly onLine;
|
|
28
|
+
private partial;
|
|
29
|
+
constructor(onLine: (line: string) => void);
|
|
30
|
+
push(chunk: string): void;
|
|
31
|
+
flush(): void;
|
|
32
|
+
}
|
|
33
|
+
/** What `exec` needs from the provider. */
|
|
34
|
+
export interface ExecContext {
|
|
35
|
+
readonly client: GroundboxClient;
|
|
36
|
+
readonly sandboxId: string;
|
|
37
|
+
readonly worktreePath: string;
|
|
38
|
+
/** True when commands already run as root (a sandbox from a Docker image). */
|
|
39
|
+
readonly isRoot: boolean;
|
|
40
|
+
/** Seconds a command may run; the sandbox's own lifetime by default. */
|
|
41
|
+
readonly timeoutSeconds: number;
|
|
42
|
+
readonly maxTail: number;
|
|
43
|
+
}
|
|
44
|
+
/** Wrap a command so it runs as root through the sandbox's `sudo`. */
|
|
45
|
+
export declare const asRoot: (command: string) => string;
|
|
46
|
+
/** The handle's `exec`, bound to one sandbox and its worktree. */
|
|
47
|
+
export declare const makeExec: (ctx: ExecContext) => (command: string, opts?: ExecOptions) => Promise<ExecResult>;
|
package/dist/exec.js
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The handle's `exec`: each command runs over a Groundbox exec stream, so
|
|
3
|
+
* stdout reaches `onLine` line by line while the command runs. `stdin` is
|
|
4
|
+
* written to the command and then closed.
|
|
5
|
+
*/
|
|
6
|
+
import { shellEscape } from "./client.js";
|
|
7
|
+
/** Default characters of output kept per stream when `onLine` is given. */
|
|
8
|
+
export const MAX_TAIL_CHARS = 64 * 1024;
|
|
9
|
+
/** A rolling tail of text, at most `max` characters long. */
|
|
10
|
+
export class Tail {
|
|
11
|
+
max;
|
|
12
|
+
text = "";
|
|
13
|
+
constructor(max) {
|
|
14
|
+
this.max = max;
|
|
15
|
+
}
|
|
16
|
+
push(chunk) {
|
|
17
|
+
this.text += chunk;
|
|
18
|
+
if (this.text.length > this.max) {
|
|
19
|
+
this.text = this.text.slice(this.text.length - this.max);
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
toString() {
|
|
23
|
+
return this.text;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
/** Split streamed stdout into lines for `onLine`. */
|
|
27
|
+
export class LineSplitter {
|
|
28
|
+
onLine;
|
|
29
|
+
partial = "";
|
|
30
|
+
constructor(onLine) {
|
|
31
|
+
this.onLine = onLine;
|
|
32
|
+
}
|
|
33
|
+
push(chunk) {
|
|
34
|
+
const lines = (this.partial + chunk).split("\n");
|
|
35
|
+
this.partial = lines.pop() ?? "";
|
|
36
|
+
for (const line of lines) {
|
|
37
|
+
this.onLine(line.endsWith("\r") ? line.slice(0, -1) : line);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
flush() {
|
|
41
|
+
if (this.partial !== "") {
|
|
42
|
+
const last = this.partial;
|
|
43
|
+
this.partial = "";
|
|
44
|
+
this.onLine(last);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
/** Wrap a command so it runs as root through the sandbox's `sudo`. */
|
|
49
|
+
export const asRoot = (command) => `sudo -E -- sh -c ${shellEscape(command)}`;
|
|
50
|
+
/** The handle's `exec`, bound to one sandbox and its worktree. */
|
|
51
|
+
export const makeExec = (ctx) => async (command, opts) => {
|
|
52
|
+
const onLine = opts?.onLine;
|
|
53
|
+
// Without onLine the whole output is returned, like the SDK's own run_command.
|
|
54
|
+
const limit = onLine === undefined ? Number.POSITIVE_INFINITY : ctx.maxTail;
|
|
55
|
+
const stdout = new Tail(limit);
|
|
56
|
+
const stderr = new Tail(limit);
|
|
57
|
+
const lines = onLine === undefined ? undefined : new LineSplitter(onLine);
|
|
58
|
+
const withStdin = opts?.stdin !== undefined;
|
|
59
|
+
const stream = ctx.client.stream_command(ctx.sandboxId, opts?.sudo === true && !ctx.isRoot ? asRoot(command) : command, {
|
|
60
|
+
cwd: opts?.cwd ?? ctx.worktreePath,
|
|
61
|
+
timeout_s: ctx.timeoutSeconds,
|
|
62
|
+
// Resumable: the command keeps running through a dropped connection.
|
|
63
|
+
resumable: true,
|
|
64
|
+
...(withStdin ? { stdin: true } : {}),
|
|
65
|
+
}, {
|
|
66
|
+
onStdout: (text) => {
|
|
67
|
+
stdout.push(text);
|
|
68
|
+
lines?.push(text);
|
|
69
|
+
},
|
|
70
|
+
onStderr: (text) => {
|
|
71
|
+
stderr.push(text);
|
|
72
|
+
},
|
|
73
|
+
});
|
|
74
|
+
const input = opts?.stdin;
|
|
75
|
+
if (input !== undefined) {
|
|
76
|
+
if (input !== "") {
|
|
77
|
+
stream.write(input);
|
|
78
|
+
}
|
|
79
|
+
stream.end();
|
|
80
|
+
}
|
|
81
|
+
const done = await stream.done;
|
|
82
|
+
lines?.flush();
|
|
83
|
+
// A command the API stopped at its timeout reports non-zero.
|
|
84
|
+
const exitCode = done.timed_out && done.exit_code === 0 ? 124 : done.exit_code;
|
|
85
|
+
return {
|
|
86
|
+
stdout: stdout.toString(),
|
|
87
|
+
stderr: stderr.toString(),
|
|
88
|
+
exitCode,
|
|
89
|
+
};
|
|
90
|
+
};
|
package/dist/files.d.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Moving files between the host and a Groundbox sandbox: `copyIn` (a file or
|
|
3
|
+
* a whole directory) and `copyFileOut`.
|
|
4
|
+
*/
|
|
5
|
+
import { type GroundboxClient, type UploadFile } from "./client.js";
|
|
6
|
+
/** Runs a shell command in the sandbox and fails on a non-zero exit. */
|
|
7
|
+
export type RunChecked = (command: string) => Promise<void>;
|
|
8
|
+
/** A directory's files and symlinks, plus the empty folders tar would not make. */
|
|
9
|
+
export declare const walk: (root: string) => Promise<{
|
|
10
|
+
files: UploadFile[];
|
|
11
|
+
emptyDirs: string[];
|
|
12
|
+
}>;
|
|
13
|
+
/** The handle's `copyIn`: a file or a directory, keeping the host's modes. */
|
|
14
|
+
export declare const makeCopyIn: (client: GroundboxClient, sandboxId: string, run: RunChecked) => (hostPath: string, sandboxPath: string) => Promise<void>;
|
|
15
|
+
/** The handle's `copyFileOut`: one file, parent folders made on the host. */
|
|
16
|
+
export declare const makeCopyFileOut: (client: GroundboxClient, sandboxId: string) => (sandboxPath: string, hostPath: string) => Promise<void>;
|
package/dist/files.js
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Moving files between the host and a Groundbox sandbox: `copyIn` (a file or
|
|
3
|
+
* a whole directory) and `copyFileOut`.
|
|
4
|
+
*/
|
|
5
|
+
import { lstat, mkdir, readFile, readdir, readlink, stat, writeFile } from "node:fs/promises";
|
|
6
|
+
import { dirname, join } from "node:path";
|
|
7
|
+
import { shellEscape } from "./client.js";
|
|
8
|
+
/** A directory's files and symlinks, plus the empty folders tar would not make. */
|
|
9
|
+
export const walk = async (root) => {
|
|
10
|
+
const files = [];
|
|
11
|
+
const emptyDirs = [];
|
|
12
|
+
const visit = async (rel) => {
|
|
13
|
+
const entries = await readdir(rel === "" ? root : join(root, rel), {
|
|
14
|
+
withFileTypes: true,
|
|
15
|
+
});
|
|
16
|
+
if (entries.length === 0 && rel !== "") {
|
|
17
|
+
emptyDirs.push(rel);
|
|
18
|
+
}
|
|
19
|
+
for (const entry of entries) {
|
|
20
|
+
const path = rel === "" ? entry.name : `${rel}/${entry.name}`;
|
|
21
|
+
const full = join(root, path);
|
|
22
|
+
if (entry.isDirectory()) {
|
|
23
|
+
await visit(path);
|
|
24
|
+
}
|
|
25
|
+
else if (entry.isSymbolicLink()) {
|
|
26
|
+
files.push({ path, symlink: await readlink(full) });
|
|
27
|
+
}
|
|
28
|
+
else if (entry.isFile()) {
|
|
29
|
+
const info = await lstat(full);
|
|
30
|
+
files.push({ path, content: await readFile(full), mode: info.mode & 0o777 });
|
|
31
|
+
}
|
|
32
|
+
// Sockets, FIFOs and devices are skipped.
|
|
33
|
+
}
|
|
34
|
+
};
|
|
35
|
+
await visit("");
|
|
36
|
+
return { files, emptyDirs };
|
|
37
|
+
};
|
|
38
|
+
/** The handle's `copyIn`: a file or a directory, keeping the host's modes. */
|
|
39
|
+
export const makeCopyIn = (client, sandboxId, run) => async (hostPath, sandboxPath) => {
|
|
40
|
+
const info = await stat(hostPath);
|
|
41
|
+
if (info.isDirectory()) {
|
|
42
|
+
const { files, emptyDirs } = await walk(hostPath);
|
|
43
|
+
await run(`mkdir -p ${shellEscape(sandboxPath)}`);
|
|
44
|
+
if (files.length > 0) {
|
|
45
|
+
await client.upload_files(sandboxId, sandboxPath, files);
|
|
46
|
+
}
|
|
47
|
+
if (emptyDirs.length > 0) {
|
|
48
|
+
const dirs = emptyDirs.map((d) => shellEscape(`${sandboxPath}/${d}`));
|
|
49
|
+
await run(`mkdir -p ${dirs.join(" ")}`);
|
|
50
|
+
}
|
|
51
|
+
return;
|
|
52
|
+
}
|
|
53
|
+
await client.write_file(sandboxId, sandboxPath, await readFile(hostPath));
|
|
54
|
+
const mode = (info.mode & 0o777).toString(8);
|
|
55
|
+
await run(`chmod ${mode} ${shellEscape(sandboxPath)}`);
|
|
56
|
+
};
|
|
57
|
+
/** The handle's `copyFileOut`: one file, parent folders made on the host. */
|
|
58
|
+
export const makeCopyFileOut = (client, sandboxId) => async (sandboxPath, hostPath) => {
|
|
59
|
+
const content = await client.read_file(sandboxId, sandboxPath);
|
|
60
|
+
await mkdir(dirname(hostPath), { recursive: true });
|
|
61
|
+
await writeFile(hostPath, content);
|
|
62
|
+
};
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Groundbox sandbox provider for Sandcastle (`@ai-hero/sandcastle`).
|
|
3
|
+
*
|
|
4
|
+
* `groundbox()` is an isolated provider: each sandbox is a Groundbox
|
|
5
|
+
* Firecracker microVM. Sandcastle copies the repo in as a git bundle, the
|
|
6
|
+
* agent works in `$HOME/workspace`, and its commits come back out.
|
|
7
|
+
*/
|
|
8
|
+
import { type IsolatedSandboxProvider } from "@ai-hero/sandcastle";
|
|
9
|
+
import { type CreateSandboxRequest } from "@groundbox/sdk";
|
|
10
|
+
import { type GroundboxClient } from "./client.js";
|
|
11
|
+
export type { GroundboxClient } from "./client.js";
|
|
12
|
+
/**
|
|
13
|
+
* Options for the Groundbox sandbox provider.
|
|
14
|
+
*
|
|
15
|
+
* Every `create_sandbox` option of `@groundbox/sdk` passes through (`cpus`,
|
|
16
|
+
* `memory_gb`, `disk_gb`, `template`, `image`, `snapshot_id`, `allow_hosts`,
|
|
17
|
+
* `secrets`, `metadata`, `timeout_minutes`, ...), except `env`: use the `env`
|
|
18
|
+
* option below, which Sandcastle merges with its own.
|
|
19
|
+
*/
|
|
20
|
+
export interface GroundboxOptions extends Omit<CreateSandboxRequest, "env"> {
|
|
21
|
+
/** A `gbx_...` key. Defaults to the `GROUNDBOX_API_KEY` environment variable. */
|
|
22
|
+
readonly apiKey?: string;
|
|
23
|
+
/** The API's base URL, ending in /v1. Defaults to `GROUNDBOX_API_URL`, then https://api.groundbox.dev/v1. */
|
|
24
|
+
readonly baseUrl?: string;
|
|
25
|
+
/** Environment variables injected by this provider. Merged at launch with Sandcastle's env resolver and the agent's env. */
|
|
26
|
+
readonly env?: Record<string, string>;
|
|
27
|
+
/**
|
|
28
|
+
* Maximum characters of streamed `exec` output kept per stream for the
|
|
29
|
+
* returned `ExecResult` when `onLine` is supplied (default: 64KiB). `onLine`
|
|
30
|
+
* still gets every line.
|
|
31
|
+
*/
|
|
32
|
+
readonly maxOutputTailChars?: number;
|
|
33
|
+
/**
|
|
34
|
+
* Seconds one command may run before Groundbox ends it. Defaults to the
|
|
35
|
+
* sandbox's whole lifetime (`timeout_minutes`).
|
|
36
|
+
*/
|
|
37
|
+
readonly commandTimeoutSeconds?: number;
|
|
38
|
+
/** A client to use instead of `new Groundbox(...)`, for tests. */
|
|
39
|
+
readonly client?: GroundboxClient;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Create a Groundbox sandbox provider for `run()`, `createSandbox()` and
|
|
43
|
+
* `interactive()`.
|
|
44
|
+
*
|
|
45
|
+
* Each sandbox is new: `create()` starts a Groundbox sandbox and `close()`
|
|
46
|
+
* deletes it. It is also deleted by Groundbox when `timeout_minutes`
|
|
47
|
+
* (default 60) runs out, so a crashed host never leaves one running.
|
|
48
|
+
*
|
|
49
|
+
* The default image is Ubuntu 24.04 with git, Node and npm, running as the
|
|
50
|
+
* user `runner` with passwordless `sudo`. It has no agent CLI: install one in
|
|
51
|
+
* a `sandbox.onSandboxReady` hook, or start from a template that has it.
|
|
52
|
+
*/
|
|
53
|
+
export declare const groundbox: (options?: GroundboxOptions) => IsolatedSandboxProvider;
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Groundbox sandbox provider for Sandcastle (`@ai-hero/sandcastle`).
|
|
3
|
+
*
|
|
4
|
+
* `groundbox()` is an isolated provider: each sandbox is a Groundbox
|
|
5
|
+
* Firecracker microVM. Sandcastle copies the repo in as a git bundle, the
|
|
6
|
+
* agent works in `$HOME/workspace`, and its commits come back out.
|
|
7
|
+
*/
|
|
8
|
+
import { createIsolatedSandboxProvider, } from "@ai-hero/sandcastle";
|
|
9
|
+
import { Groundbox } from "@groundbox/sdk";
|
|
10
|
+
import { isNotFound } from "./client.js";
|
|
11
|
+
import { MAX_TAIL_CHARS, makeExec } from "./exec.js";
|
|
12
|
+
import { makeCopyFileOut, makeCopyIn } from "./files.js";
|
|
13
|
+
import { makeInteractiveExec } from "./interactive.js";
|
|
14
|
+
/** One hour: the trial's limit, and room for setup, a run and syncing back. */
|
|
15
|
+
const DEFAULT_TIMEOUT_MINUTES = 60;
|
|
16
|
+
/** States a new sandbox passes through on its way to `running`. */
|
|
17
|
+
const COMING_UP = new Set(["queued", "starting", "resuming"]);
|
|
18
|
+
/**
|
|
19
|
+
* Create a Groundbox sandbox provider for `run()`, `createSandbox()` and
|
|
20
|
+
* `interactive()`.
|
|
21
|
+
*
|
|
22
|
+
* Each sandbox is new: `create()` starts a Groundbox sandbox and `close()`
|
|
23
|
+
* deletes it. It is also deleted by Groundbox when `timeout_minutes`
|
|
24
|
+
* (default 60) runs out, so a crashed host never leaves one running.
|
|
25
|
+
*
|
|
26
|
+
* The default image is Ubuntu 24.04 with git, Node and npm, running as the
|
|
27
|
+
* user `runner` with passwordless `sudo`. It has no agent CLI: install one in
|
|
28
|
+
* a `sandbox.onSandboxReady` hook, or start from a template that has it.
|
|
29
|
+
*/
|
|
30
|
+
export const groundbox = (options) => {
|
|
31
|
+
const { apiKey, baseUrl, env, maxOutputTailChars = MAX_TAIL_CHARS, commandTimeoutSeconds, client: givenClient, ...spec } = options ?? {};
|
|
32
|
+
const timeoutMinutes = spec.timeout_minutes ?? DEFAULT_TIMEOUT_MINUTES;
|
|
33
|
+
const timeoutSeconds = commandTimeoutSeconds ?? timeoutMinutes * 60;
|
|
34
|
+
return createIsolatedSandboxProvider({
|
|
35
|
+
name: "groundbox",
|
|
36
|
+
// From a Docker image commands run as root, where Claude Code refuses
|
|
37
|
+
// --dangerously-skip-permissions unless it knows it is in a sandbox.
|
|
38
|
+
env: spec.image === undefined ? env : { IS_SANDBOX: "1", ...env },
|
|
39
|
+
create: async (createOptions) => {
|
|
40
|
+
const client = givenClient ??
|
|
41
|
+
new Groundbox({
|
|
42
|
+
// An empty key counts as unset, so the SDK reads GROUNDBOX_API_KEY
|
|
43
|
+
...(apiKey === undefined || apiKey === "" ? {} : { apiKey }),
|
|
44
|
+
...(baseUrl === undefined ? {} : { baseUrl }),
|
|
45
|
+
});
|
|
46
|
+
let sandbox = await client.create_sandbox({
|
|
47
|
+
...spec,
|
|
48
|
+
timeout_minutes: timeoutMinutes,
|
|
49
|
+
on_timeout: spec.on_timeout ?? "delete",
|
|
50
|
+
metadata: { created_by: "sandcastle", ...spec.metadata },
|
|
51
|
+
env: createOptions.env,
|
|
52
|
+
});
|
|
53
|
+
const sandboxId = sandbox.id;
|
|
54
|
+
const bootstrap = makeExec({
|
|
55
|
+
client,
|
|
56
|
+
sandboxId,
|
|
57
|
+
worktreePath: "/",
|
|
58
|
+
isRoot: true,
|
|
59
|
+
timeoutSeconds: 300,
|
|
60
|
+
maxTail: maxOutputTailChars,
|
|
61
|
+
});
|
|
62
|
+
let worktreePath;
|
|
63
|
+
let isRoot;
|
|
64
|
+
try {
|
|
65
|
+
if (COMING_UP.has(sandbox.status)) {
|
|
66
|
+
sandbox = await client.wait_for_sandbox(sandboxId);
|
|
67
|
+
}
|
|
68
|
+
if (sandbox.status !== "running") {
|
|
69
|
+
const why = sandbox.error ? `: ${String(sandbox.error)}` : "";
|
|
70
|
+
throw new Error(`sandbox ${sandboxId} is ${sandbox.status}${why}`);
|
|
71
|
+
}
|
|
72
|
+
const prepared = await bootstrap('mkdir -p "$HOME/workspace" && cd "$HOME/workspace" && pwd && id -u');
|
|
73
|
+
if (prepared.exitCode !== 0) {
|
|
74
|
+
throw new Error(`could not create $HOME/workspace: ${prepared.stderr.trim() || `exit ${prepared.exitCode}`}`);
|
|
75
|
+
}
|
|
76
|
+
const [path, uid] = prepared.stdout.trim().split("\n");
|
|
77
|
+
if (path === undefined || path === "") {
|
|
78
|
+
throw new Error("could not read the path of $HOME/workspace");
|
|
79
|
+
}
|
|
80
|
+
worktreePath = path.trim();
|
|
81
|
+
isRoot = uid?.trim() === "0";
|
|
82
|
+
}
|
|
83
|
+
catch (error) {
|
|
84
|
+
// No handle exists yet, so nothing else could delete it.
|
|
85
|
+
await client.delete_sandbox(sandboxId).catch(() => undefined);
|
|
86
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
87
|
+
throw new Error(`groundbox(): ${message}`, { cause: error });
|
|
88
|
+
}
|
|
89
|
+
const exec = makeExec({
|
|
90
|
+
client,
|
|
91
|
+
sandboxId,
|
|
92
|
+
worktreePath,
|
|
93
|
+
isRoot,
|
|
94
|
+
timeoutSeconds,
|
|
95
|
+
maxTail: maxOutputTailChars,
|
|
96
|
+
});
|
|
97
|
+
const runChecked = async (command) => {
|
|
98
|
+
const result = await exec(command, { cwd: "/" });
|
|
99
|
+
if (result.exitCode !== 0) {
|
|
100
|
+
throw new Error(`${command} exited with ${result.exitCode}: ${result.stderr.trim()}`);
|
|
101
|
+
}
|
|
102
|
+
};
|
|
103
|
+
return {
|
|
104
|
+
worktreePath,
|
|
105
|
+
sandboxId,
|
|
106
|
+
exec,
|
|
107
|
+
interactiveExec: makeInteractiveExec({
|
|
108
|
+
client,
|
|
109
|
+
sandboxId,
|
|
110
|
+
worktreePath,
|
|
111
|
+
timeoutSeconds,
|
|
112
|
+
}),
|
|
113
|
+
copyIn: makeCopyIn(client, sandboxId, runChecked),
|
|
114
|
+
copyFileOut: makeCopyFileOut(client, sandboxId),
|
|
115
|
+
close: async () => {
|
|
116
|
+
try {
|
|
117
|
+
await client.delete_sandbox(sandboxId);
|
|
118
|
+
}
|
|
119
|
+
catch (error) {
|
|
120
|
+
if (!isNotFound(error)) {
|
|
121
|
+
throw error;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
},
|
|
125
|
+
};
|
|
126
|
+
},
|
|
127
|
+
});
|
|
128
|
+
};
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The handle's `interactiveExec`, for Sandcastle's `interactive()`: the agent
|
|
3
|
+
* runs on a terminal in the sandbox when the host's stdin is a TTY, with
|
|
4
|
+
* keystrokes, output and window size passed through.
|
|
5
|
+
*/
|
|
6
|
+
import type { InteractiveExecOptions } from "@ai-hero/sandcastle";
|
|
7
|
+
import type { GroundboxClient } from "./client.js";
|
|
8
|
+
export interface InteractiveContext {
|
|
9
|
+
readonly client: GroundboxClient;
|
|
10
|
+
readonly sandboxId: string;
|
|
11
|
+
readonly worktreePath: string;
|
|
12
|
+
readonly timeoutSeconds: number;
|
|
13
|
+
}
|
|
14
|
+
export declare const makeInteractiveExec: (ctx: InteractiveContext) => (args: string[], opts: InteractiveExecOptions) => Promise<{
|
|
15
|
+
exitCode: number;
|
|
16
|
+
}>;
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The handle's `interactiveExec`, for Sandcastle's `interactive()`: the agent
|
|
3
|
+
* runs on a terminal in the sandbox when the host's stdin is a TTY, with
|
|
4
|
+
* keystrokes, output and window size passed through.
|
|
5
|
+
*/
|
|
6
|
+
const positive = (n) => n !== undefined && n > 0 ? n : undefined;
|
|
7
|
+
export const makeInteractiveExec = (ctx) => async (args, opts) => {
|
|
8
|
+
if (args.length === 0) {
|
|
9
|
+
throw new Error("interactiveExec needs a command to run");
|
|
10
|
+
}
|
|
11
|
+
const stdin = opts.stdin;
|
|
12
|
+
const stdout = opts.stdout;
|
|
13
|
+
const tty = stdin.isTTY === true;
|
|
14
|
+
// A terminal can report 0x0 (under `script`, for one): fall back to 24x80.
|
|
15
|
+
const size = {
|
|
16
|
+
rows: positive(stdout.rows) ?? 24,
|
|
17
|
+
cols: positive(stdout.columns) ?? 80,
|
|
18
|
+
};
|
|
19
|
+
const stream = ctx.client.stream_command(ctx.sandboxId, args, {
|
|
20
|
+
cwd: opts.cwd ?? ctx.worktreePath,
|
|
21
|
+
timeout_s: ctx.timeoutSeconds,
|
|
22
|
+
stdin: true,
|
|
23
|
+
resumable: true,
|
|
24
|
+
...(tty ? { tty: size } : {}),
|
|
25
|
+
}, {
|
|
26
|
+
onStdout: (text) => {
|
|
27
|
+
opts.stdout.write(text);
|
|
28
|
+
},
|
|
29
|
+
onStderr: (text) => {
|
|
30
|
+
opts.stderr.write(text);
|
|
31
|
+
},
|
|
32
|
+
});
|
|
33
|
+
const onData = (chunk) => {
|
|
34
|
+
stream.write(typeof chunk === "string" ? chunk : new Uint8Array(chunk));
|
|
35
|
+
};
|
|
36
|
+
const onEnd = () => {
|
|
37
|
+
stream.end();
|
|
38
|
+
};
|
|
39
|
+
const onResize = () => {
|
|
40
|
+
stream.resize(positive(stdout.rows) ?? size.rows, positive(stdout.columns) ?? size.cols);
|
|
41
|
+
};
|
|
42
|
+
const wasRaw = stdin.isRaw === true;
|
|
43
|
+
if (tty) {
|
|
44
|
+
stdin.setRawMode?.(true);
|
|
45
|
+
stdout.on?.("resize", onResize);
|
|
46
|
+
}
|
|
47
|
+
stdin.on("data", onData);
|
|
48
|
+
stdin.on("end", onEnd);
|
|
49
|
+
stdin.resume();
|
|
50
|
+
try {
|
|
51
|
+
const done = await stream.done;
|
|
52
|
+
return { exitCode: done.exit_code };
|
|
53
|
+
}
|
|
54
|
+
finally {
|
|
55
|
+
stdin.off("data", onData);
|
|
56
|
+
stdin.off("end", onEnd);
|
|
57
|
+
if (tty) {
|
|
58
|
+
stdin.setRawMode?.(wasRaw);
|
|
59
|
+
stdout.off?.("resize", onResize);
|
|
60
|
+
}
|
|
61
|
+
stdin.pause();
|
|
62
|
+
}
|
|
63
|
+
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,58 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@groundbox/sandcastle",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Groundbox sandbox provider for Sandcastle: run coding agents in Groundbox Firecracker microVMs.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"groundbox",
|
|
7
|
+
"sandcastle",
|
|
8
|
+
"sandbox",
|
|
9
|
+
"agents",
|
|
10
|
+
"firecracker",
|
|
11
|
+
"microvm"
|
|
12
|
+
],
|
|
13
|
+
"license": "MIT",
|
|
14
|
+
"homepage": "https://groundbox.dev/docs",
|
|
15
|
+
"repository": {
|
|
16
|
+
"type": "git",
|
|
17
|
+
"url": "git+https://github.com/Ground-box/groundbox-integrations.git",
|
|
18
|
+
"directory": "packages/sandcastle"
|
|
19
|
+
},
|
|
20
|
+
"type": "module",
|
|
21
|
+
"main": "./dist/index.js",
|
|
22
|
+
"types": "./dist/index.d.ts",
|
|
23
|
+
"exports": {
|
|
24
|
+
".": {
|
|
25
|
+
"types": "./dist/index.d.ts",
|
|
26
|
+
"import": "./dist/index.js"
|
|
27
|
+
}
|
|
28
|
+
},
|
|
29
|
+
"files": [
|
|
30
|
+
"dist",
|
|
31
|
+
"README.md",
|
|
32
|
+
"LICENSE"
|
|
33
|
+
],
|
|
34
|
+
"engines": {
|
|
35
|
+
"node": ">=22"
|
|
36
|
+
},
|
|
37
|
+
"scripts": {
|
|
38
|
+
"build": "tsc -p tsconfig.build.json",
|
|
39
|
+
"typecheck": "tsc -p tsconfig.json --noEmit",
|
|
40
|
+
"test": "vitest run",
|
|
41
|
+
"prepack": "npm run build"
|
|
42
|
+
},
|
|
43
|
+
"dependencies": {
|
|
44
|
+
"@groundbox/sdk": "^0.4.2"
|
|
45
|
+
},
|
|
46
|
+
"peerDependencies": {
|
|
47
|
+
"@ai-hero/sandcastle": ">=0.14.0 <1.0.0"
|
|
48
|
+
},
|
|
49
|
+
"devDependencies": {
|
|
50
|
+
"@ai-hero/sandcastle": "0.14.0",
|
|
51
|
+
"@types/node": "^22.10.0",
|
|
52
|
+
"typescript": "^5.7.0",
|
|
53
|
+
"vitest": "^3.2.0"
|
|
54
|
+
},
|
|
55
|
+
"publishConfig": {
|
|
56
|
+
"access": "public"
|
|
57
|
+
}
|
|
58
|
+
}
|