@groundbox/opencode 0.0.0-stage → 0.1.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,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,136 @@
1
- # Temporary Holding Version
1
+ # @groundbox/opencode
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
+ Run [OpenCode](https://opencode.ai) sessions in [Groundbox](https://groundbox.dev) sandboxes.
4
+
5
+ The plugin adds a `groundbox` type to OpenCode's workspace API. OpenCode keeps running on your
6
+ machine. Each workspace is a Groundbox sandbox (a Firecracker microVM) running an OpenCode server
7
+ on a copy of your project. Start a session inside it, or move a local session into it with `/warp`.
8
+
9
+ ## Install
10
+
11
+ Add the plugin to `opencode.json` (in the project, or `~/.config/opencode/opencode.json` for all
12
+ projects). The second element of the tuple holds options and can be left out.
13
+
14
+ ```json
15
+ {
16
+ "$schema": "https://opencode.ai/config.json",
17
+ "plugin": [["@groundbox/opencode", { "cpus": 2, "idleTimeoutSeconds": 600 }]]
18
+ }
19
+ ```
20
+
21
+ Start OpenCode with your Groundbox API key and workspaces turned on:
22
+
23
+ ```bash
24
+ export GROUNDBOX_API_KEY=gbx_... # https://app.groundbox.dev/keys
25
+ OPENCODE_EXPERIMENTAL_WORKSPACES=true opencode
26
+ ```
27
+
28
+ Needs OpenCode 1.16 or newer (`opencode-ai`), a macOS or Linux host, and the Groundbox paid plan:
29
+ the plugin reaches the sandbox through a [preview](https://groundbox.dev/docs/previews), and
30
+ previews are not in the free trial.
31
+
32
+ ## Use
33
+
34
+ 1. In OpenCode, run `/warp` and choose **Groundbox Sandbox**. The plugin starts a sandbox, copies
35
+ your project in, installs the same OpenCode version you run locally, and starts its server.
36
+ That takes about 10 to 20 seconds. The workspace is named after your branch, for example
37
+ `groundbox-main`.
38
+ 2. Send a prompt. The agent's commands, edits and tools run in the sandbox.
39
+ 3. To bring a session home, run `/warp` and choose **None**. OpenCode offers to apply the
40
+ sandbox's file changes to your project as a patch (your project must be a git repository).
41
+ 4. Removing the workspace deletes its sandbox.
42
+
43
+ The same works without the TUI, through OpenCode's HTTP API:
44
+
45
+ ```bash
46
+ # with `opencode serve` running on :4096 in the project
47
+ curl -X POST "localhost:4096/experimental/workspace?directory=$PWD" \
48
+ -H 'content-type: application/json' -d '{"type":"groundbox","branch":null}'
49
+ # then create sessions with ?workspace=<id>
50
+ ```
51
+
52
+ ## How it works
53
+
54
+ - **Sandbox**: one per workspace, from Groundbox's default Ubuntu image (user `runner`, with
55
+ sudo), a template, or a Docker image. Tagged with the metadata `opencode_workspace_id`, which is
56
+ how the plugin finds it again after OpenCode restarts. No local state file.
57
+ - **Project copy**: in a git repository, git decides what is sent: tracked files plus untracked
58
+ files that are not ignored, so `.gitignore`d files (`node_modules`, `.env`) stay on your
59
+ machine. `.git` itself is not sent; the sandbox commits the copy as `Workspace snapshot`, so
60
+ moving a session home carries only the agent's changes. The project lives at the same path as
61
+ on your machine (on Windows: `/home/runner/project`), which is what lets a session move between
62
+ the two.
63
+ - **Server**: `opencode serve` runs in the background in the sandbox with the environment OpenCode
64
+ hands the workspace (your `opencode auth` credentials, the workspace id), plus anything in
65
+ `forwardEnv` and `env`. They are written to `~/.groundbox-opencode/env` (mode 600) in the sandbox.
66
+ - **Connection**: the local OpenCode talks to the sandbox through a private Groundbox preview,
67
+ `https://<slug>-4096.groundbox.page`. Every request carries the preview's share token and a
68
+ random basic-auth password for the OpenCode server, made per workspace and kept in the
69
+ workspace's `extra` field in your local OpenCode database. Share tokens last 24 hours; the
70
+ plugin renews them before they run out.
71
+ - **Idle and timeout**: the sandbox pauses after 10 idle minutes (memory and processes kept,
72
+ billed as storage) and the next request wakes it. It also pauses at its timeout (2 hours,
73
+ counted from the last start or wake). When OpenCode next reaches a paused or stopped sandbox,
74
+ the plugin resumes or starts it, and restarts the server after a stop. See Limits for why the
75
+ timeout, not the idle pause, is what usually ends a session today.
76
+
77
+ ## Options
78
+
79
+ | Option | Default | Meaning |
80
+ | --- | --- | --- |
81
+ | `cpus` | `2` | vCPUs (1 to 16). |
82
+ | `memoryGb` | Groundbox default | Memory, up to 4 GB per vCPU. |
83
+ | `diskGb` | Groundbox default (20) | Minimum disk size. |
84
+ | `template` | none | Start from a Groundbox template. |
85
+ | `image` | none | Start from a public Docker image (linux/amd64). Runs as root; needs `npm`, or `curl` and `bash`, to install OpenCode. |
86
+ | `timeoutMinutes` | `120` | Lifetime, counted from the last start or wake. At most 43200. While OpenCode is open, a paused sandbox is resumed on its next request, so this mostly bounds what an abandoned workspace costs. |
87
+ | `onTimeout` | `"pause"` | `"pause"`, `"stop"` (keeps the disk) or `"delete"`. |
88
+ | `idleTimeoutSeconds` | `600` | Pause after this many idle seconds; a request wakes it. `null` turns it off. |
89
+ | `projectPath` | your host path | Project folder in the sandbox. |
90
+ | `serverPort` | `4096` | Port of the OpenCode server in the sandbox. |
91
+ | `opencodeVersion` | your local version | OpenCode version installed in the sandbox. |
92
+ | `forwardEnv` | `[]` | Names of local environment variables to copy to the sandbox's OpenCode server, for example `["ANTHROPIC_API_KEY"]` if your model key comes from the environment rather than `opencode auth login`. |
93
+ | `env` | `{}` | Extra environment variables for the sandbox's OpenCode server. |
94
+ | `prepareCommands` | `[]` | Shell commands run in the project folder after the copy and before the server starts, for example `["npm ci"]`. |
95
+ | `allowHosts` | no limit | Egress allowlist for the sandbox. |
96
+ | `metadata` | `{}` | Extra sandbox metadata. |
97
+ | `uploadIgnore` | `.git`, `node_modules`, `dist`, `build`, ... | Skipped names when the project is not a git repository. |
98
+ | `maxFileBytes` | 50 MB | Larger files are not copied. |
99
+ | `readyTimeoutMs` | `90000` | How long to wait for the sandbox's OpenCode server. |
100
+
101
+ ## Limits
102
+
103
+ - OpenCode's workspace API is experimental (`OPENCODE_EXPERIMENTAL_WORKSPACES=true`) and can
104
+ change without notice.
105
+ - OpenCode 2 (`@opencode/cli`) has no workspace API for plugins, so this package is for
106
+ OpenCode 1 only.
107
+ - Moving an existing local session into a workspace with `/warp` did not work in our tests with
108
+ OpenCode 1.19.6: the warp itself succeeds, but the next command times out with "Timed out
109
+ waiting for sync fence". Sessions started in the workspace work. See the PR for details.
110
+ - Idle pause does not fire once OpenCode has connected: OpenCode holds an event stream
111
+ (`/global/event`) to the workspace, and a stream through a Groundbox preview keeps the sandbox
112
+ active, even after OpenCode closes. Until that changes, the sandbox runs until its timeout
113
+ (`timeoutMinutes`, 2 hours by default) and then pauses. Remove workspaces you are done with.
114
+ - The copy is one-way at create time. Changes you make locally later do not reach the sandbox;
115
+ commits made inside the sandbox do not come home (the file changes do, through `/warp`).
116
+ - Needs the paid plan (previews). A deleted or expired sandbox makes the workspace unavailable:
117
+ remove it and create a new one.
118
+ - Windows hosts: the project cannot live at the same path in the sandbox, so a new session
119
+ started from a warped one may not open locally.
120
+
121
+ ## Development
122
+
123
+ ```bash
124
+ npm install
125
+ npm run typecheck
126
+ npm test # unit tests, with a fake Groundbox
127
+ GROUNDBOX_API_KEY=gbx_... npm run test:live # one real sandbox, deleted at the end
128
+ npm run build
129
+ ```
130
+
131
+ To try a checkout in OpenCode, build it and put the folder's absolute path in place of
132
+ `@groundbox/opencode` in `opencode.json`.
133
+
134
+ ## License
135
+
136
+ MIT. See [LICENSE](LICENSE).
@@ -0,0 +1,48 @@
1
+ import type { Groundbox } from "@groundbox/sdk";
2
+ import type { WorkspaceAdapter, WorkspaceInfo } from "@opencode-ai/plugin";
3
+ import { type ResolvedOptions } from "./options.js";
4
+ /** The part of the Groundbox SDK the adapter uses. Tests pass a fake. */
5
+ export type GroundboxClient = Pick<Groundbox, "create_sandbox" | "wait_for_sandbox" | "get_sandbox" | "list_sandboxes" | "delete_sandbox" | "resume_sandbox" | "start_sandbox" | "run_command" | "write_file" | "upload_files" | "expose_port" | "delete_preview">;
6
+ type Preview = Awaited<ReturnType<Groundbox["expose_port"]>>;
7
+ export type Logger = {
8
+ info(message: string, extra?: Record<string, unknown>): Promise<void>;
9
+ warn(message: string, extra?: Record<string, unknown>): Promise<void>;
10
+ error(message: string, extra?: Record<string, unknown>): Promise<void>;
11
+ };
12
+ /** What the workspace row keeps in `extra`. Stored locally by OpenCode, never sent to Groundbox as metadata. */
13
+ export type PersistedExtra = {
14
+ groundbox: {
15
+ v: 1;
16
+ runtimeVersion: string;
17
+ projectPath: string;
18
+ serverPort: number;
19
+ /** Basic-auth password of the remote OpenCode server. */
20
+ password: string;
21
+ };
22
+ };
23
+ export type AdapterDeps = {
24
+ /** The local project folder (the plugin input's `directory`). */
25
+ directory: string;
26
+ options: ResolvedOptions;
27
+ /** Made on first use, so loading the plugin never needs a key. */
28
+ groundbox: () => GroundboxClient;
29
+ /** The local OpenCode version, so the sandbox runs the same one. */
30
+ resolveRuntimeVersion: () => Promise<string>;
31
+ logger: Logger;
32
+ fetch?: typeof fetch;
33
+ env?: NodeJS.ProcessEnv;
34
+ /** Milliseconds between readiness polls. Tests set it low. */
35
+ pollMs?: number;
36
+ };
37
+ export declare const METADATA_KEY = "opencode_workspace_id";
38
+ export declare function readExtra(info: WorkspaceInfo): PersistedExtra["groundbox"] | undefined;
39
+ export declare function workspaceName(info: Pick<WorkspaceInfo, "id" | "branch">): string;
40
+ export declare function targetHeaders(preview: Preview, password: string): Record<string, string>;
41
+ export declare function createGroundboxWorkspaceAdapter(deps: AdapterDeps): WorkspaceAdapter;
42
+ /**
43
+ * Retries a call the API refused with 429 (rate limit), waiting as long as it asks, up to 5
44
+ * times. A key shared by several agents can hit the limit in bursts.
45
+ */
46
+ export declare function withRateLimitRetry<T extends object>(target: T, maxWaitMs?: number): T;
47
+ export declare function errorMessage(error: unknown): string;
48
+ export {};
@@ -0,0 +1,330 @@
1
+ import { execFile } from "node:child_process";
2
+ import { randomBytes, randomUUID } from "node:crypto";
3
+ import { promisify } from "node:util";
4
+ import { resolveProjectPath } from "./options.js";
5
+ import { STATE_DIR, prepareDirScript, renderEnvFile, serveScript, serverLogTailScript, setupScript, startServerScript, } from "./remote.js";
6
+ import { batchFiles, planSnapshot, readBatch } from "./upload.js";
7
+ export const METADATA_KEY = "opencode_workspace_id";
8
+ const PREVIEW_TOKEN_HEADER = "X-Groundbox-Preview-Token";
9
+ const PREVIEW_RENEW_MS = 60 * 60_000;
10
+ const STATUS_CACHE_MS = 10_000;
11
+ const execFileP = promisify(execFile);
12
+ export function readExtra(info) {
13
+ const extra = info.extra;
14
+ const g = extra?.groundbox;
15
+ if (!g || g.v !== 1 || typeof g.password !== "string" || typeof g.projectPath !== "string")
16
+ return undefined;
17
+ return g;
18
+ }
19
+ export function workspaceName(info) {
20
+ const slug = (info.branch ?? "")
21
+ .toLowerCase()
22
+ .replace(/[^a-z0-9._-]+/g, "-")
23
+ .replace(/^-+|-+$/g, "");
24
+ return `groundbox-${slug || info.id.slice(-8).toLowerCase()}`;
25
+ }
26
+ export function targetHeaders(preview, password) {
27
+ const token = preview.share_url ? new URL(preview.share_url).searchParams.get("gb_token") : null;
28
+ const headers = {
29
+ authorization: `Basic ${Buffer.from(`opencode:${password}`).toString("base64")}`,
30
+ };
31
+ if (token)
32
+ headers[PREVIEW_TOKEN_HEADER] = token;
33
+ return headers;
34
+ }
35
+ export function createGroundboxWorkspaceAdapter(deps) {
36
+ const fetchFn = deps.fetch ?? fetch;
37
+ const env = deps.env ?? process.env;
38
+ const pollMs = deps.pollMs ?? 750;
39
+ const cache = new Map();
40
+ const client = () => {
41
+ const key = env.GROUNDBOX_API_KEY;
42
+ if (!key || key.trim() === "") {
43
+ throw new Error("GROUNDBOX_API_KEY is not set. Export it before starting OpenCode. Create a key at https://app.groundbox.dev/keys");
44
+ }
45
+ return withRateLimitRetry(deps.groundbox());
46
+ };
47
+ async function findLive(gb, workspaceID) {
48
+ const { data } = await gb.list_sandboxes({ live: true, metadata: { [METADATA_KEY]: workspaceID } });
49
+ return data;
50
+ }
51
+ async function exposePreview(gb, sandboxId, port) {
52
+ let preview = await gb.expose_port(sandboxId, port);
53
+ if (expiresSoon(preview)) {
54
+ // A private preview's share token lasts 24 hours; a new preview gets a new one.
55
+ await gb.delete_preview(sandboxId, port);
56
+ preview = await gb.expose_port(sandboxId, port);
57
+ }
58
+ return preview;
59
+ }
60
+ async function waitReady(gb, sandboxId, preview, password) {
61
+ const headers = targetHeaders(preview, password);
62
+ const base = preview.url;
63
+ const deadline = Date.now() + deps.options.readyTimeoutMs;
64
+ let last = "no answer yet";
65
+ // No probe of the /global/event stream: a stream opened through a preview keeps the
66
+ // sandbox from idling even after the client goes (seen on Groundbox, November 2026).
67
+ while (Date.now() < deadline) {
68
+ try {
69
+ await probe(fetchFn, new URL("/global/health", base), { headers });
70
+ await probe(fetchFn, new URL("/sync/history", base), {
71
+ method: "POST",
72
+ headers: { ...headers, "content-type": "application/json" },
73
+ body: "{}",
74
+ });
75
+ return;
76
+ }
77
+ catch (error) {
78
+ last = errorMessage(error);
79
+ }
80
+ await sleep(pollMs);
81
+ }
82
+ const tail = await gb
83
+ .run_command(sandboxId, serverLogTailScript())
84
+ .then((r) => r.stdout.trim())
85
+ .catch(() => "");
86
+ throw new Error(`The OpenCode server in sandbox ${sandboxId} did not answer at ${base} (${last})` +
87
+ (tail ? `\nLast lines of ~/${STATE_DIR}/server.log:\n${tail}` : ""));
88
+ }
89
+ async function runChecked(gb, sandboxId, script, timeout_s = 600) {
90
+ const r = await gb.run_command(sandboxId, script, { timeout_s });
91
+ if (r.exit_code !== 0) {
92
+ const detail = [r.stderr.trim(), r.stdout.trim()].filter(Boolean).join("\n").slice(-4000);
93
+ throw new Error(`Command in sandbox ${sandboxId} failed (exit ${r.exit_code})${detail ? `:\n${detail}` : ""}`);
94
+ }
95
+ return r.stdout;
96
+ }
97
+ async function provision(gb, info, extra, coreEnv) {
98
+ const o = deps.options;
99
+ let sandbox = await gb.create_sandbox({
100
+ cpus: o.cpus,
101
+ ...(o.memoryGb ? { memory_gb: o.memoryGb } : {}),
102
+ ...(o.diskGb ? { disk_gb: o.diskGb } : {}),
103
+ ...(o.template ? { template: o.template } : {}),
104
+ ...(o.image ? { image: o.image } : {}),
105
+ timeout_minutes: o.timeoutMinutes,
106
+ on_timeout: o.onTimeout,
107
+ ...(o.idleTimeoutSeconds !== null ? { idle_timeout_seconds: o.idleTimeoutSeconds, wake_on_request: true } : {}),
108
+ ...(o.allowHosts ? { allow_hosts: o.allowHosts } : {}),
109
+ metadata: {
110
+ ...o.metadata,
111
+ [METADATA_KEY]: info.id,
112
+ opencode_project_id: info.projectID,
113
+ created_by: "groundbox-opencode",
114
+ },
115
+ }, { idempotencyKey: randomUUID() });
116
+ await deps.logger.info("sandbox created", { workspaceID: info.id, sandboxID: sandbox.id, status: sandbox.status });
117
+ try {
118
+ if (sandbox.status !== "running")
119
+ sandbox = await gb.wait_for_sandbox(sandbox.id);
120
+ if (sandbox.status !== "running") {
121
+ throw new Error(`Sandbox ${sandbox.id} did not start (${sandbox.status}${sandbox.error ? `: ${sandbox.error}` : ""})`);
122
+ }
123
+ const home = (await runChecked(gb, sandbox.id, prepareDirScript(extra.projectPath))).trim();
124
+ const plan = await planSnapshot(deps.directory, o.uploadIgnore, o.maxFileBytes);
125
+ if (plan.skipped.length > 0) {
126
+ await deps.logger.warn("files not uploaded", { skipped: plan.skipped.slice(0, 20), count: plan.skipped.length });
127
+ }
128
+ for (const batch of batchFiles(plan.files)) {
129
+ await gb.upload_files(sandbox.id, extra.projectPath, await readBatch(deps.directory, batch), { timeout_s: 600 });
130
+ }
131
+ await deps.logger.info("project uploaded", { sandboxID: sandbox.id, files: plan.files.length, source: plan.source });
132
+ const branch = info.branch ?? "main";
133
+ const setupOut = await runChecked(gb, sandbox.id, setupScript({
134
+ projectPath: extra.projectPath,
135
+ branch,
136
+ projectID: info.projectID,
137
+ prepareCommands: o.prepareCommands,
138
+ opencodeVersion: extra.runtimeVersion,
139
+ }), 1800);
140
+ const bin = setupOut.trim().split("\n").pop()?.trim();
141
+ if (!bin)
142
+ throw new Error(`OpenCode was not found in sandbox ${sandbox.id} after install`);
143
+ const forwarded = Object.fromEntries(o.forwardEnv.map((name) => [name, env[name]]));
144
+ const serverEnv = {
145
+ ...forwarded,
146
+ ...o.env,
147
+ ...coreEnv,
148
+ OPENCODE_SERVER_USERNAME: "opencode",
149
+ OPENCODE_SERVER_PASSWORD: extra.password,
150
+ };
151
+ await gb.write_file(sandbox.id, `${home}/${STATE_DIR}/env`, renderEnvFile(serverEnv));
152
+ await gb.write_file(sandbox.id, `${home}/${STATE_DIR}/serve.sh`, serveScript({ home, projectPath: extra.projectPath, bin, port: extra.serverPort }));
153
+ await runChecked(gb, sandbox.id, startServerScript());
154
+ const preview = await exposePreview(gb, sandbox.id, extra.serverPort);
155
+ await waitReady(gb, sandbox.id, preview, extra.password);
156
+ cache.set(info.id, { sandboxId: sandbox.id, checkedAt: Date.now(), preview });
157
+ await deps.logger.info("workspace ready", { workspaceID: info.id, sandboxID: sandbox.id, url: preview.url });
158
+ }
159
+ catch (error) {
160
+ await deps.logger.error("workspace create failed; deleting its sandbox", {
161
+ workspaceID: info.id,
162
+ sandboxID: sandbox.id,
163
+ error: errorMessage(error),
164
+ });
165
+ await gb.delete_sandbox(sandbox.id).catch(() => { });
166
+ throw error;
167
+ }
168
+ }
169
+ /** Brings the workspace's sandbox to running, restarting the server after a stop. */
170
+ async function ensureRunning(gb, info, extra) {
171
+ const cached = cache.get(info.id);
172
+ if (cached && Date.now() - cached.checkedAt < STATUS_CACHE_MS)
173
+ return cached;
174
+ let sandbox;
175
+ if (cached)
176
+ sandbox = await gb.get_sandbox(cached.sandboxId).catch(() => undefined);
177
+ if (!sandbox || sandbox.status === "stopped" || sandbox.status === "failed")
178
+ sandbox = (await findLive(gb, info.id))[0];
179
+ if (!sandbox) {
180
+ cache.delete(info.id);
181
+ throw new Error(`The Groundbox sandbox of workspace ${info.name} is gone (deleted, or past its timeout). Remove the workspace and create a new one.`);
182
+ }
183
+ switch (sandbox.status) {
184
+ case "paused":
185
+ case "pausing":
186
+ // An idle pause wakes on the next preview request; anything else needs a resume.
187
+ if (!sandbox.wakes_on_request)
188
+ sandbox = await gb.resume_sandbox(sandbox.id);
189
+ break;
190
+ case "shut_down":
191
+ case "shutting_down": {
192
+ await deps.logger.info("starting stopped sandbox", { workspaceID: info.id, sandboxID: sandbox.id });
193
+ if (sandbox.status === "shutting_down")
194
+ sandbox = await gb.wait_for_sandbox(sandbox.id);
195
+ sandbox = await gb.start_sandbox(sandbox.id);
196
+ if (sandbox.status !== "running")
197
+ sandbox = await gb.wait_for_sandbox(sandbox.id);
198
+ await runChecked(gb, sandbox.id, startServerScript());
199
+ const preview = await exposePreview(gb, sandbox.id, extra.serverPort);
200
+ await waitReady(gb, sandbox.id, preview, extra.password);
201
+ break;
202
+ }
203
+ case "queued":
204
+ case "starting":
205
+ case "resuming":
206
+ sandbox = await gb.wait_for_sandbox(sandbox.id);
207
+ break;
208
+ default:
209
+ break;
210
+ }
211
+ const entry = { sandboxId: sandbox.id, checkedAt: Date.now(), preview: cached?.sandboxId === sandbox.id ? cached.preview : undefined };
212
+ cache.set(info.id, entry);
213
+ return entry;
214
+ }
215
+ return {
216
+ name: "Groundbox Sandbox",
217
+ description: "Run this workspace's OpenCode in a Groundbox sandbox (a Firecracker microVM)",
218
+ async configure(info) {
219
+ const projectPath = resolveProjectPath(deps.options, deps.directory);
220
+ const branch = info.branch ?? (await readLocalBranch(deps.directory));
221
+ const runtimeVersion = deps.options.opencodeVersion ?? (await deps.resolveRuntimeVersion());
222
+ const configured = { ...info, branch: branch ?? info.branch };
223
+ const extra = {
224
+ groundbox: {
225
+ v: 1,
226
+ runtimeVersion,
227
+ projectPath,
228
+ serverPort: deps.options.serverPort,
229
+ password: randomBytes(24).toString("base64url"),
230
+ },
231
+ };
232
+ return { ...configured, name: workspaceName(configured), directory: projectPath, extra };
233
+ },
234
+ async create(info, coreEnv) {
235
+ const gb = client();
236
+ const extra = readExtra(info);
237
+ if (!extra)
238
+ throw new Error(`Workspace ${info.id} was not configured by @groundbox/opencode`);
239
+ for (const old of await findLive(gb, info.id)) {
240
+ // A sandbox left from an earlier attempt: start clean.
241
+ await deps.logger.warn("deleting earlier sandbox of this workspace", { workspaceID: info.id, sandboxID: old.id });
242
+ await gb.delete_sandbox(old.id).catch(() => { });
243
+ }
244
+ cache.delete(info.id);
245
+ await provision(gb, info, extra, coreEnv);
246
+ },
247
+ async remove(info) {
248
+ const gb = client();
249
+ const ids = new Set();
250
+ const cached = cache.get(info.id);
251
+ if (cached)
252
+ ids.add(cached.sandboxId);
253
+ for (const s of await findLive(gb, info.id))
254
+ ids.add(s.id);
255
+ for (const id of ids)
256
+ await gb.delete_sandbox(id).catch(() => { });
257
+ cache.delete(info.id);
258
+ await deps.logger.info("workspace removed", { workspaceID: info.id, sandboxes: [...ids] });
259
+ },
260
+ async target(info) {
261
+ const gb = client();
262
+ const extra = readExtra(info);
263
+ if (!extra)
264
+ throw new Error(`Workspace ${info.id} was not configured by @groundbox/opencode`);
265
+ const entry = await ensureRunning(gb, info, extra);
266
+ if (!entry.preview || expiresSoon(entry.preview)) {
267
+ entry.preview = await exposePreview(gb, entry.sandboxId, extra.serverPort);
268
+ }
269
+ return { type: "remote", url: entry.preview.url, headers: targetHeaders(entry.preview, extra.password) };
270
+ },
271
+ };
272
+ }
273
+ /**
274
+ * Retries a call the API refused with 429 (rate limit), waiting as long as it asks, up to 5
275
+ * times. A key shared by several agents can hit the limit in bursts.
276
+ */
277
+ export function withRateLimitRetry(target, maxWaitMs = 30_000) {
278
+ return new Proxy(target, {
279
+ get(obj, prop, receiver) {
280
+ const value = Reflect.get(obj, prop, receiver);
281
+ if (typeof value !== "function")
282
+ return value;
283
+ return async (...args) => {
284
+ for (let attempt = 0;; attempt++) {
285
+ try {
286
+ return await value.apply(obj, args);
287
+ }
288
+ catch (error) {
289
+ const e = error;
290
+ if (e?.status !== 429 || attempt >= 5)
291
+ throw error;
292
+ const seconds = Number(/in (\d+) seconds?/.exec(e.message ?? "")?.[1] ?? 2 ** attempt);
293
+ await sleep(Math.min(maxWaitMs, Math.max(500, seconds * 1000)));
294
+ }
295
+ }
296
+ };
297
+ },
298
+ });
299
+ }
300
+ function expiresSoon(preview) {
301
+ if (preview.public || !preview.expires_at)
302
+ return false;
303
+ return Date.parse(preview.expires_at) - Date.now() < PREVIEW_RENEW_MS;
304
+ }
305
+ async function probe(fetchFn, url, init) {
306
+ const res = await fetchFn(url, { ...init, signal: AbortSignal.timeout(5000) });
307
+ try {
308
+ if (!res.ok)
309
+ throw new Error(`${url.pathname} answered HTTP ${res.status}`);
310
+ }
311
+ finally {
312
+ await res.body?.cancel().catch(() => { });
313
+ }
314
+ }
315
+ async function readLocalBranch(directory) {
316
+ try {
317
+ const { stdout } = await execFileP("git", ["-C", directory, "rev-parse", "--abbrev-ref", "HEAD"]);
318
+ const branch = stdout.trim();
319
+ return branch && branch !== "HEAD" ? branch : null;
320
+ }
321
+ catch {
322
+ return null;
323
+ }
324
+ }
325
+ export function errorMessage(error) {
326
+ return error instanceof Error ? error.message : String(error);
327
+ }
328
+ function sleep(ms) {
329
+ return new Promise((resolve) => setTimeout(resolve, ms));
330
+ }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * @groundbox/opencode: registers a "groundbox" type with OpenCode's experimental workspace API.
3
+ * Each workspace is a Groundbox sandbox running a remote OpenCode server on a copy of the
4
+ * project; the local OpenCode reaches it through a private Groundbox preview.
5
+ *
6
+ * OpenCode 1 reads `server` from the default export (its PluginModule).
7
+ */
8
+ import type { PluginModule } from "@opencode-ai/plugin";
9
+ export type { GroundboxWorkspaceOptions } from "./options.js";
10
+ export declare const PLUGIN_VERSION = "0.1.0";
11
+ declare const plugin: PluginModule;
12
+ export default plugin;
package/dist/index.js ADDED
@@ -0,0 +1,64 @@
1
+ /**
2
+ * @groundbox/opencode: registers a "groundbox" type with OpenCode's experimental workspace API.
3
+ * Each workspace is a Groundbox sandbox running a remote OpenCode server on a copy of the
4
+ * project; the local OpenCode reaches it through a private Groundbox preview.
5
+ *
6
+ * OpenCode 1 reads `server` from the default export (its PluginModule).
7
+ */
8
+ import { Groundbox } from "@groundbox/sdk";
9
+ import { createGroundboxWorkspaceAdapter, errorMessage } from "./adapter.js";
10
+ import { resolveOptions } from "./options.js";
11
+ export const PLUGIN_VERSION = "0.1.0";
12
+ const server = async (input, rawOptions) => {
13
+ const options = resolveOptions(rawOptions);
14
+ const logger = createLogger(input.client);
15
+ let groundbox;
16
+ const adapter = createGroundboxWorkspaceAdapter({
17
+ directory: input.directory,
18
+ options,
19
+ logger,
20
+ groundbox: () => (groundbox ??= new Groundbox({ userAgent: `groundbox-opencode/${PLUGIN_VERSION}` })),
21
+ resolveRuntimeVersion: () => resolveRuntimeVersion(input, logger),
22
+ });
23
+ input.experimental_workspace.register("groundbox", adapter);
24
+ await logger.info("registered groundbox workspace type", { directory: input.directory });
25
+ return {};
26
+ };
27
+ const plugin = { id: "groundbox", server };
28
+ export default plugin;
29
+ function createLogger(client) {
30
+ const write = (level) => async (message, extra) => {
31
+ await client.app.log({ body: { service: "groundbox-workspace", level, message, extra } }).catch(() => { });
32
+ };
33
+ return { info: write("info"), warn: write("warn"), error: write("error") };
34
+ }
35
+ let runtimeVersion;
36
+ /** The local OpenCode's version, from its own /global/health. Falls back to "latest". */
37
+ function resolveRuntimeVersion(input, logger) {
38
+ runtimeVersion ??= (async () => {
39
+ const raw = input.client
40
+ ._client;
41
+ try {
42
+ if (raw) {
43
+ const result = (await raw.get({ url: "/global/health", signal: AbortSignal.timeout(2000) }));
44
+ if (typeof result?.data?.version === "string")
45
+ return result.data.version;
46
+ }
47
+ }
48
+ catch (error) {
49
+ await logger.warn("health probe through the client failed", { error: errorMessage(error) });
50
+ }
51
+ try {
52
+ const res = await fetch(new URL("/global/health", input.serverUrl), { signal: AbortSignal.timeout(2000) });
53
+ const body = (await res.json());
54
+ if (typeof body.version === "string")
55
+ return body.version;
56
+ }
57
+ catch (error) {
58
+ await logger.warn("health probe on serverUrl failed", { error: errorMessage(error) });
59
+ }
60
+ await logger.warn("local OpenCode version unknown; the sandbox installs the latest. Set opencodeVersion to pin it.");
61
+ return "latest";
62
+ })();
63
+ return runtimeVersion;
64
+ }
@@ -0,0 +1,66 @@
1
+ /** Plugin options, as given in the second element of the `opencode.json` plugin tuple. */
2
+ export type GroundboxWorkspaceOptions = {
3
+ /** vCPUs for each workspace sandbox (1 to 16). Default 2. */
4
+ cpus?: number;
5
+ /** GB of memory; up to 4 per vCPU. Default: Groundbox's default for `cpus`. */
6
+ memoryGb?: number;
7
+ /** Minimum disk size in GB. Default: Groundbox's default (20). */
8
+ diskGb?: number;
9
+ /** Start from a Groundbox template instead of the default image. */
10
+ template?: string;
11
+ /** Start from a public Docker image (linux/amd64). Commands then run as root. Needs Node.js/npm or curl+bash. */
12
+ image?: string;
13
+ /** Sandbox lifetime in minutes, counted from its last start or wake. Default 120. */
14
+ timeoutMinutes?: number;
15
+ /** What the timeout does: "pause" (default, keeps memory), "stop" (keeps the disk) or "delete". */
16
+ onTimeout?: "pause" | "stop" | "delete";
17
+ /** Pause the sandbox after this many idle seconds; the next request wakes it. Default 600. `null` turns it off. */
18
+ idleTimeoutSeconds?: number | null;
19
+ /** Project path inside the sandbox. Default: the same path as on this machine. */
20
+ projectPath?: string;
21
+ /** Port of the OpenCode server in the sandbox. Default 4096. */
22
+ serverPort?: number;
23
+ /** OpenCode version to install in the sandbox. Default: the version of the local OpenCode. */
24
+ opencodeVersion?: string;
25
+ /** Names of local environment variables to copy into the remote OpenCode server (for example ANTHROPIC_API_KEY). */
26
+ forwardEnv?: string[];
27
+ /** Extra environment variables for the remote OpenCode server. */
28
+ env?: Record<string, string>;
29
+ /** Shell commands run in the project folder after upload and before the server starts (for example `npm ci`). */
30
+ prepareCommands?: string[];
31
+ /** Hosts the sandbox may reach (egress allowlist). Default: no limit. */
32
+ allowHosts?: string[];
33
+ /** Extra sandbox metadata. */
34
+ metadata?: Record<string, string>;
35
+ /** Paths (or path segments) not uploaded when the project is not a git repository. */
36
+ uploadIgnore?: string[];
37
+ /** Files larger than this are not uploaded. Default 50 MB. */
38
+ maxFileBytes?: number;
39
+ /** How long to wait for the remote OpenCode server, in ms. Default 90000. */
40
+ readyTimeoutMs?: number;
41
+ };
42
+ export type ResolvedOptions = {
43
+ cpus: number;
44
+ memoryGb?: number;
45
+ diskGb?: number;
46
+ template?: string;
47
+ image?: string;
48
+ timeoutMinutes: number;
49
+ onTimeout: "pause" | "stop" | "delete";
50
+ idleTimeoutSeconds: number | null;
51
+ projectPath?: string;
52
+ serverPort: number;
53
+ opencodeVersion?: string;
54
+ forwardEnv: string[];
55
+ env: Record<string, string>;
56
+ prepareCommands: string[];
57
+ allowHosts?: string[];
58
+ metadata: Record<string, string>;
59
+ uploadIgnore: string[];
60
+ maxFileBytes: number;
61
+ readyTimeoutMs: number;
62
+ };
63
+ export declare const DEFAULT_UPLOAD_IGNORE: string[];
64
+ export declare function resolveOptions(raw: unknown): ResolvedOptions;
65
+ /** Where the project lives in the sandbox: the host path when it can be mirrored on Linux. */
66
+ export declare function resolveProjectPath(options: ResolvedOptions, localDirectory: string, platform?: NodeJS.Platform): string;
@@ -0,0 +1,104 @@
1
+ export const DEFAULT_UPLOAD_IGNORE = [
2
+ ".git",
3
+ "node_modules",
4
+ "dist",
5
+ "build",
6
+ ".next",
7
+ ".turbo",
8
+ ".cache",
9
+ ".venv",
10
+ "__pycache__",
11
+ ".DS_Store",
12
+ ];
13
+ const ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
14
+ export function resolveOptions(raw) {
15
+ const o = (raw ?? {});
16
+ if (typeof o !== "object" || Array.isArray(o))
17
+ throw new Error("@groundbox/opencode: options must be an object");
18
+ const num = (key, min, max) => {
19
+ const v = o[key];
20
+ if (v === undefined)
21
+ return undefined;
22
+ if (typeof v !== "number" || !Number.isFinite(v) || v < min || v > max) {
23
+ throw new Error(`@groundbox/opencode: ${key} must be a number from ${min} to ${max}`);
24
+ }
25
+ return v;
26
+ };
27
+ const str = (key) => {
28
+ const v = o[key];
29
+ if (v === undefined)
30
+ return undefined;
31
+ if (typeof v !== "string" || v.trim() === "")
32
+ throw new Error(`@groundbox/opencode: ${key} must be a non-empty string`);
33
+ return v.trim();
34
+ };
35
+ const strList = (key) => {
36
+ const v = o[key];
37
+ if (v === undefined)
38
+ return undefined;
39
+ if (!Array.isArray(v) || v.some((x) => typeof x !== "string")) {
40
+ throw new Error(`@groundbox/opencode: ${key} must be a list of strings`);
41
+ }
42
+ return v;
43
+ };
44
+ const strMap = (key) => {
45
+ const v = o[key];
46
+ if (v === undefined)
47
+ return undefined;
48
+ if (typeof v !== "object" || v === null || Array.isArray(v) || Object.values(v).some((x) => typeof x !== "string")) {
49
+ throw new Error(`@groundbox/opencode: ${key} must be an object of strings`);
50
+ }
51
+ return v;
52
+ };
53
+ const template = str("template");
54
+ const image = str("image");
55
+ if (template && image)
56
+ throw new Error("@groundbox/opencode: set template or image, not both");
57
+ const onTimeout = o.onTimeout ?? "pause";
58
+ if (onTimeout !== "pause" && onTimeout !== "stop" && onTimeout !== "delete") {
59
+ throw new Error('@groundbox/opencode: onTimeout must be "pause", "stop" or "delete"');
60
+ }
61
+ let idleTimeoutSeconds = 600;
62
+ if (o.idleTimeoutSeconds === null)
63
+ idleTimeoutSeconds = null;
64
+ else if (o.idleTimeoutSeconds !== undefined)
65
+ idleTimeoutSeconds = num("idleTimeoutSeconds", 30, 30 * 24 * 3600);
66
+ const projectPath = str("projectPath");
67
+ if (projectPath && !projectPath.startsWith("/"))
68
+ throw new Error("@groundbox/opencode: projectPath must be absolute");
69
+ const forwardEnv = strList("forwardEnv") ?? [];
70
+ const env = strMap("env") ?? {};
71
+ for (const name of [...forwardEnv, ...Object.keys(env)]) {
72
+ if (!ENV_NAME.test(name))
73
+ throw new Error(`@groundbox/opencode: ${name} is not a valid environment variable name`);
74
+ }
75
+ return {
76
+ cpus: num("cpus", 1, 16) ?? 2,
77
+ memoryGb: num("memoryGb", 1, 64),
78
+ diskGb: num("diskGb", 1, 2000),
79
+ template,
80
+ image,
81
+ timeoutMinutes: num("timeoutMinutes", 1, 43_200) ?? 120,
82
+ onTimeout,
83
+ idleTimeoutSeconds,
84
+ projectPath,
85
+ serverPort: num("serverPort", 1024, 65_535) ?? 4096,
86
+ opencodeVersion: str("opencodeVersion"),
87
+ forwardEnv,
88
+ env,
89
+ prepareCommands: strList("prepareCommands") ?? [],
90
+ allowHosts: strList("allowHosts"),
91
+ metadata: strMap("metadata") ?? {},
92
+ uploadIgnore: strList("uploadIgnore") ?? DEFAULT_UPLOAD_IGNORE,
93
+ maxFileBytes: num("maxFileBytes", 1, 1024 ** 3) ?? 50 * 1024 * 1024,
94
+ readyTimeoutMs: num("readyTimeoutMs", 1000, 30 * 60_000) ?? 90_000,
95
+ };
96
+ }
97
+ /** Where the project lives in the sandbox: the host path when it can be mirrored on Linux. */
98
+ export function resolveProjectPath(options, localDirectory, platform = process.platform) {
99
+ if (options.projectPath)
100
+ return options.projectPath;
101
+ if (platform === "win32" || !localDirectory.startsWith("/"))
102
+ return "/home/runner/project";
103
+ return localDirectory;
104
+ }
@@ -0,0 +1,32 @@
1
+ /** Shell scripts run in the sandbox, and the env file the remote OpenCode server reads. */
2
+ export declare const STATE_DIR = ".groundbox-opencode";
3
+ export declare function shq(value: string): string;
4
+ /** Makes the project folder (it may mirror a host path like /Users/...) owned by the sandbox user. Prints $HOME. */
5
+ export declare function prepareDirScript(projectPath: string): string;
6
+ /**
7
+ * Runs the user's prepare commands, commits the uploaded snapshot (so moving a session back
8
+ * home carries only the agent's changes), marks the project id, and installs OpenCode.
9
+ * Prints the path of the opencode binary on its last line.
10
+ */
11
+ export declare function setupScript(params: {
12
+ projectPath: string;
13
+ branch: string;
14
+ projectID: string;
15
+ prepareCommands: string[];
16
+ opencodeVersion: string;
17
+ }): string;
18
+ /** The launcher the server runs from. It reads the env file each start, so a stopped sandbox can start again. */
19
+ export declare function serveScript(params: {
20
+ home: string;
21
+ projectPath: string;
22
+ bin: string;
23
+ port: number;
24
+ }): string;
25
+ /**
26
+ * Starts (or restarts) the server in the background. The command returns at once, so the
27
+ * sandbox can still pause when idle; the server pauses with it and goes on when it wakes.
28
+ */
29
+ export declare function startServerScript(): string;
30
+ export declare function serverLogTailScript(): string;
31
+ /** The env file for the remote server. Values are single-quoted, so nothing in them is expanded. */
32
+ export declare function renderEnvFile(env: Record<string, string | undefined>): string;
package/dist/remote.js ADDED
@@ -0,0 +1,84 @@
1
+ /** Shell scripts run in the sandbox, and the env file the remote OpenCode server reads. */
2
+ export const STATE_DIR = ".groundbox-opencode";
3
+ export function shq(value) {
4
+ return `'${value.replace(/'/g, `'\\''`)}'`;
5
+ }
6
+ const SUDO = `if [ "$(id -u)" = 0 ]; then SUDO=; else SUDO="sudo -n"; fi`;
7
+ /** Makes the project folder (it may mirror a host path like /Users/...) owned by the sandbox user. Prints $HOME. */
8
+ export function prepareDirScript(projectPath) {
9
+ return [
10
+ "set -e",
11
+ SUDO,
12
+ `$SUDO mkdir -p ${shq(projectPath)}`,
13
+ `$SUDO chown "$(id -u):$(id -g)" ${shq(projectPath)}`,
14
+ `mkdir -p "$HOME/${STATE_DIR}"`,
15
+ `chmod 700 "$HOME/${STATE_DIR}"`,
16
+ `printf '%s' "$HOME"`,
17
+ ].join("\n");
18
+ }
19
+ /**
20
+ * Runs the user's prepare commands, commits the uploaded snapshot (so moving a session back
21
+ * home carries only the agent's changes), marks the project id, and installs OpenCode.
22
+ * Prints the path of the opencode binary on its last line.
23
+ */
24
+ export function setupScript(params) {
25
+ const version = params.opencodeVersion;
26
+ const pkg = version === "latest" ? "opencode-ai@latest" : `opencode-ai@${version}`;
27
+ const installFlag = version === "latest" ? "" : ` --version ${shq(version)}`;
28
+ return [
29
+ "set -e",
30
+ SUDO,
31
+ `cd ${shq(params.projectPath)}`,
32
+ ...params.prepareCommands.map((c) => c.trim()).filter(Boolean).map((c) => `(${c}) >&2`),
33
+ `if [ ! -d .git ]; then git init -q -b ${shq(params.branch)} && git add -A && git -c user.name=opencode -c user.email=opencode@groundbox.local commit -q --allow-empty -m 'Workspace snapshot'; fi`,
34
+ `printf '%s' ${shq(params.projectID)} > .git/opencode`,
35
+ `oc_bin() { command -v opencode 2>/dev/null || { [ -x "$HOME/.opencode/bin/opencode" ] && echo "$HOME/.opencode/bin/opencode"; }; }`,
36
+ `BIN=$(oc_bin || true)`,
37
+ `if [ -z "$BIN" ] || [ ${shq(version)} = latest ] || [ "$("$BIN" --version 2>/dev/null)" != ${shq(version)} ]; then`,
38
+ ` if command -v npm >/dev/null 2>&1; then $SUDO npm install -g --no-fund --no-audit ${shq(pkg)} >&2`,
39
+ ` elif command -v curl >/dev/null 2>&1 && command -v bash >/dev/null 2>&1; then curl -fsSL https://opencode.ai/install | bash -s --${installFlag} >&2`,
40
+ ` else echo "OpenCode cannot be installed: the sandbox has neither npm nor curl and bash" >&2; exit 3; fi`,
41
+ ` hash -r 2>/dev/null || true`,
42
+ ` BIN=$(oc_bin)`,
43
+ `fi`,
44
+ `echo "$BIN"`,
45
+ ].join("\n");
46
+ }
47
+ /** The launcher the server runs from. It reads the env file each start, so a stopped sandbox can start again. */
48
+ export function serveScript(params) {
49
+ return [
50
+ "#!/bin/sh",
51
+ "set -a",
52
+ `. ${shq(`${params.home}/${STATE_DIR}/env`)}`,
53
+ "set +a",
54
+ `cd ${shq(params.projectPath)}`,
55
+ `exec ${shq(params.bin)} serve --hostname 0.0.0.0 --port ${params.port}`,
56
+ "",
57
+ ].join("\n");
58
+ }
59
+ /**
60
+ * Starts (or restarts) the server in the background. The command returns at once, so the
61
+ * sandbox can still pause when idle; the server pauses with it and goes on when it wakes.
62
+ */
63
+ export function startServerScript() {
64
+ return [
65
+ `D="$HOME/${STATE_DIR}"`,
66
+ `chmod 600 "$D/env"`,
67
+ `if [ -f "$D/server.pid" ] && kill -0 "$(cat "$D/server.pid")" 2>/dev/null; then kill "$(cat "$D/server.pid")" || true; sleep 1; fi`,
68
+ `nohup sh "$D/serve.sh" > "$D/server.log" 2>&1 < /dev/null &`,
69
+ `echo $! > "$D/server.pid"`,
70
+ ].join("\n");
71
+ }
72
+ export function serverLogTailScript() {
73
+ return `tail -n 40 "$HOME/${STATE_DIR}/server.log" 2>/dev/null || true`;
74
+ }
75
+ /** The env file for the remote server. Values are single-quoted, so nothing in them is expanded. */
76
+ export function renderEnvFile(env) {
77
+ const lines = ["# Written by @groundbox/opencode. Regenerated on every workspace create."];
78
+ for (const [key, value] of Object.entries(env)) {
79
+ if (value === undefined || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(key))
80
+ continue;
81
+ lines.push(`${key}=${shq(value)}`);
82
+ }
83
+ return lines.join("\n") + "\n";
84
+ }
@@ -0,0 +1,34 @@
1
+ export type LocalFile = {
2
+ /** Path relative to the project folder, with `/` separators. */
3
+ path: string;
4
+ size: number;
5
+ mode: number;
6
+ symlink?: string;
7
+ };
8
+ export type SnapshotPlan = {
9
+ files: LocalFile[];
10
+ skipped: {
11
+ path: string;
12
+ reason: string;
13
+ }[];
14
+ source: "git" | "walk";
15
+ };
16
+ /**
17
+ * The files to copy into the sandbox. In a git repository, git decides: tracked files plus
18
+ * untracked ones that are not ignored, so `.gitignore`d output and secrets in ignored files
19
+ * stay on this machine. Elsewhere, a walk that skips `ignore`.
20
+ */
21
+ export declare function planSnapshot(root: string, ignore: string[], maxFileBytes: number): Promise<SnapshotPlan>;
22
+ /** Groups files into upload batches of at most `maxFiles` files and about `maxBytes` bytes. */
23
+ export declare function batchFiles(files: LocalFile[], maxFiles?: number, maxBytes?: number): LocalFile[][];
24
+ export declare function readBatch(root: string, batch: LocalFile[]): Promise<({
25
+ path: string;
26
+ symlink: string;
27
+ content?: undefined;
28
+ mode?: undefined;
29
+ } | {
30
+ path: string;
31
+ content: Uint8Array<ArrayBuffer>;
32
+ mode: number;
33
+ symlink?: undefined;
34
+ })[]>;
package/dist/upload.js ADDED
@@ -0,0 +1,89 @@
1
+ import { execFile } from "node:child_process";
2
+ import { lstat, readFile, readdir, readlink } from "node:fs/promises";
3
+ import { join, relative, sep } from "node:path";
4
+ import { promisify } from "node:util";
5
+ const run = promisify(execFile);
6
+ /**
7
+ * The files to copy into the sandbox. In a git repository, git decides: tracked files plus
8
+ * untracked ones that are not ignored, so `.gitignore`d output and secrets in ignored files
9
+ * stay on this machine. Elsewhere, a walk that skips `ignore`.
10
+ */
11
+ export async function planSnapshot(root, ignore, maxFileBytes) {
12
+ const listed = await gitListFiles(root);
13
+ const paths = listed ?? (await walk(root, ignore));
14
+ const files = [];
15
+ const skipped = [];
16
+ for (const path of paths) {
17
+ const abs = join(root, ...path.split("/"));
18
+ let st;
19
+ try {
20
+ st = await lstat(abs);
21
+ }
22
+ catch {
23
+ continue; // tracked but deleted in the working tree
24
+ }
25
+ if (st.isSymbolicLink()) {
26
+ files.push({ path, size: 0, mode: 0o777, symlink: await readlink(abs) });
27
+ }
28
+ else if (st.isFile()) {
29
+ if (st.size > maxFileBytes) {
30
+ skipped.push({ path, reason: `larger than ${maxFileBytes} bytes` });
31
+ continue;
32
+ }
33
+ files.push({ path, size: st.size, mode: st.mode & 0o777 });
34
+ }
35
+ }
36
+ return { files, skipped, source: listed ? "git" : "walk" };
37
+ }
38
+ async function gitListFiles(root) {
39
+ try {
40
+ const { stdout } = await run("git", ["-C", root, "ls-files", "-z", "--cached", "--others", "--exclude-standard"], {
41
+ maxBuffer: 256 * 1024 * 1024,
42
+ });
43
+ return [...new Set(stdout.split("\0").filter(Boolean))];
44
+ }
45
+ catch {
46
+ return undefined;
47
+ }
48
+ }
49
+ async function walk(root, ignore) {
50
+ const out = [];
51
+ const skip = (rel, name) => ignore.includes(name) || ignore.includes(rel);
52
+ async function visit(dir) {
53
+ for (const entry of await readdir(dir, { withFileTypes: true })) {
54
+ const abs = join(dir, entry.name);
55
+ const rel = relative(root, abs).split(sep).join("/");
56
+ if (skip(rel, entry.name))
57
+ continue;
58
+ if (entry.isDirectory())
59
+ await visit(abs);
60
+ else if (entry.isFile() || entry.isSymbolicLink())
61
+ out.push(rel);
62
+ }
63
+ }
64
+ await visit(root);
65
+ return out;
66
+ }
67
+ /** Groups files into upload batches of at most `maxFiles` files and about `maxBytes` bytes. */
68
+ export function batchFiles(files, maxFiles = 500, maxBytes = 48 * 1024 * 1024) {
69
+ const batches = [];
70
+ let current = [];
71
+ let bytes = 0;
72
+ for (const file of files) {
73
+ if (current.length > 0 && (current.length >= maxFiles || bytes + file.size > maxBytes)) {
74
+ batches.push(current);
75
+ current = [];
76
+ bytes = 0;
77
+ }
78
+ current.push(file);
79
+ bytes += file.size;
80
+ }
81
+ if (current.length > 0)
82
+ batches.push(current);
83
+ return batches;
84
+ }
85
+ export async function readBatch(root, batch) {
86
+ return Promise.all(batch.map(async (f) => f.symlink !== undefined
87
+ ? { path: f.path, symlink: f.symlink }
88
+ : { path: f.path, content: new Uint8Array(await readFile(join(root, ...f.path.split("/")))), mode: f.mode }));
89
+ }
package/package.json CHANGED
@@ -1,6 +1,76 @@
1
1
  {
2
2
  "name": "@groundbox/opencode",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "OpenCode workspace plugin: run OpenCode sessions in Groundbox sandboxes (Firecracker microVMs)",
5
+ "keywords": [
6
+ "groundbox",
7
+ "opencode",
8
+ "opencode-plugin",
9
+ "sandbox",
10
+ "workspace"
11
+ ],
12
+ "homepage": "https://github.com/Ground-box/groundbox-integrations/tree/main/packages/opencode#readme",
13
+ "bugs": {
14
+ "url": "https://github.com/Ground-box/groundbox-integrations/issues"
15
+ },
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "git+https://github.com/Ground-box/groundbox-integrations.git",
19
+ "directory": "packages/opencode"
20
+ },
21
+ "license": "MIT",
22
+ "type": "module",
23
+ "main": "./dist/index.js",
24
+ "types": "./dist/index.d.ts",
25
+ "exports": {
26
+ ".": {
27
+ "types": "./dist/index.d.ts",
28
+ "default": "./dist/index.js"
29
+ },
30
+ "./server": {
31
+ "types": "./dist/index.d.ts",
32
+ "default": "./dist/index.js"
33
+ }
34
+ },
35
+ "files": [
36
+ "dist",
37
+ "README.md",
38
+ "LICENSE"
39
+ ],
40
+ "publishConfig": {
41
+ "access": "public"
42
+ },
43
+ "scripts": {
44
+ "build": "rm -rf dist && tsc -p tsconfig.build.json",
45
+ "typecheck": "tsc -p tsconfig.json --noEmit",
46
+ "test": "vitest run",
47
+ "test:live": "vitest run test/live.test.ts",
48
+ "prepack": "npm run build"
49
+ },
50
+ "dependencies": {
51
+ "@groundbox/sdk": "^0.4.2"
52
+ },
53
+ "peerDependencies": {
54
+ "@opencode-ai/plugin": ">=1.16.0"
55
+ },
56
+ "peerDependenciesMeta": {
57
+ "@opencode-ai/plugin": {
58
+ "optional": true
59
+ }
60
+ },
61
+ "devDependencies": {
62
+ "@opencode-ai/plugin": "1.19.6",
63
+ "@types/node": "^22.10.0",
64
+ "typescript": "^5.9.2",
65
+ "vitest": "^4.1.12"
66
+ },
67
+ "engines": {
68
+ "node": ">=20",
69
+ "opencode": ">=1.16.0"
70
+ },
71
+ "overrides": {
72
+ "toml": "^5.0.1",
73
+ "effect": "4.0.0-beta.107",
74
+ "zod": "^4.6.6"
75
+ }
76
+ }