Skip to content

Run OpenCode in a sandbox

Run the OpenCode coding agent in a sandbox and use it from your browser.

This program creates a sandbox, installs the OpenCode coding agent in it and starts its web UI on a public port. You use OpenCode from your browser, and everything it runs stays in the sandbox.

Before you start

  • An API key and a project, set as SUTRA_API_KEY and SUTRA_PROJECT. See Projects and API keys.
  • Node.js 22 or later.
  • The SDK: npm install @mistrive/anchor.

The program

Save it as opencode.ts and run it with npx tsx opencode.ts.

import { AnchorClient, type SandboxHandle } from "@mistrive/anchor";

// Port for the OpenCode web UI
const OPENCODE_PORT = 3000;

async function main() {
  const client = new AnchorClient({
    baseUrl: "https://anchor.jgcp.mistrivedev.com",
    token: process.env.SUTRA_API_KEY,
    project: process.env.SUTRA_PROJECT,
  });

  let sandbox: SandboxHandle | undefined;

  try {
    sandbox = await client.create({
      sandbox: {
        resources: {
          $typeName: "anchor.types.v1.ResourceAllocation",
          vcpus: 2,
          memoryMb: BigInt(2048),
          diskMb: BigInt(2048),
        },
      },
    });

    // Install opencode
    console.log("Installing opencode...");
    console.log(
      await sandbox.exec({
        command: "/bin/sh",
        args: ["-c", "sudo -E sh -c 'umask 022 && npm install -g opencode-ai'"],
      }),
    );

    // Open the OpenCode port and, through the same host, every other port of
    // the sandbox, so servers the agent starts are reachable too. All of them
    // are public.
    const preview = await client.openPreviewBinding({
      sandbox: sandbox.name,
      binding: {
        key: "opencode",
        sandboxPort: OPENCODE_PORT,
        accessMode: "PUBLIC",
        allPorts: true,
      },
    });

    // Configure the system prompt
    const systemPrompt = [
      "You are running in a Sutra sandbox.",
      `When running services on localhost, they will be accessible at ${preview.generatedHost} where the initial ${OPENCODE_PORT}- can be replaced with the port of the service you are starting.`,
      "When starting a server, always give the user the preview URL to access it.",
      "When starting a server, start it in the background with & so the command does not block further instructions.",
    ].join(" ");

    // OpenCode config with a sandbox-aware agent
    const opencodeConfig = {
      $schema: "https://opencode.ai/config.json",
      agent: {
        build: {
          description: "Sutra sandbox-aware coding agent",
          mode: "primary",
          prompt: systemPrompt,
        },
      },
      server: {
        cors: [preview.generatedHost],
        port: OPENCODE_PORT,
      },
    };

    console.log("Starting OpenCode web server...");
    const configJson = JSON.stringify(opencodeConfig);

    // Pass the config as inline JSON via OPENCODE_CONFIG_CONTENT. This goes
    // directly into the process environment, so there are no quoting/escaping
    // issues and no need to write a config file first.
    await sandbox.processes.start({
      command: "/usr/local/bin/opencode",
      args: ["web", "--port", OPENCODE_PORT.toString(), "--hostname", "0.0.0.0"],
      env: {
        OPENCODE_CONFIG_CONTENT: configJson,
      },
    });

    console.log(`OpenCode web server started at https://${preview.generatedHost}`);

    // Clean up the sandbox on Ctrl+C (SIGINT) or termination (SIGTERM).
    let cleaningUp = false;
    const shutdown = async (signal: string) => {
      if (cleaningUp) return;
      cleaningUp = true;
      console.log(`\nReceived ${signal}. Deleting sandbox...`);
      try {
        if (sandbox) {
          await sandbox.delete();
        }
      } catch (err) {
        console.error("Error during cleanup:", err);
      } finally {
        process.exit(0);
      }
    };

    process.on("SIGINT", () => void shutdown("SIGINT"));
    process.on("SIGTERM", () => void shutdown("SIGTERM"));

    // Keep the process running until Ctrl+C is pressed
    console.log("Press Ctrl+C to stop.\n");

    setInterval(() => {}, 1000);
  } catch (error) {
    console.error("Error:", error);
    if (sandbox) {
      console.log("Deleting sandbox...");
      await sandbox.delete();
    }
    process.exit(1);
  }
}

main().catch((error) => {
  console.error("Error:", error);
  process.exit(1);
});
import { Sutra, type Sandbox } from "@mistrive/sutra";

const OPENCODE_PORT = 3000;

const sutra = new Sutra({
  baseUrl: "https://anchor.jgcp.mistrivedev.com",
});

const sandbox: Sandbox = await sutra.sandboxes.create({
  resources: { milliCpus: 2000, memoryBytes: 2 * 1024 ** 3, diskBytes: 2 * 1024 ** 3 },
  lifecycle: { idleTimeout: { seconds: 1800, action: "STOP" } },
});

console.log("Installing OpenCode...");
await sandbox.processes.run({ shellCommand: "npm install -g opencode-ai", user: "root" });

const port = await sandbox.ports.create({ port: OPENCODE_PORT, access: "PUBLIC" });

const config = {
  $schema: "https://opencode.ai/config.json",
  agent: {
    build: {
      description: "Sutra sandbox-aware coding agent",
      mode: "primary",
      prompt: [
        "You are running in a Sutra sandbox.",
        `Services you start on a port are reachable once the port is created. This one is at ${port.uri}.`,
        "Start servers in the background so the command does not block.",
      ].join(" "),
    },
  },
  server: { cors: [port.uri], port: OPENCODE_PORT },
};

await sandbox.processes.start({
  argv: ["opencode", "web", "--port", String(OPENCODE_PORT), "--hostname", "0.0.0.0"],
  env: { OPENCODE_CONFIG_CONTENT: JSON.stringify(config) },
});

console.log(`OpenCode is running at ${port.uri}. Press Ctrl+C to stop.`);

const shutdown = async () => {
  await sandbox.delete();
  process.exit(0);
};
process.on("SIGINT", shutdown);
process.on("SIGTERM", shutdown);

// Keep the program running until it receives a signal.
setInterval(() => {}, 1000);

What to expect

The program prints a URL when OpenCode is ready. Open it in your browser to use OpenCode. The agent knows it runs in a sandbox: when it starts a server, it gives you the address to reach it.

Stop it

Press Ctrl+C. The program deletes the sandbox and everything in it.

Type to search…

↑↓ navigate↵ selectEsc close