Run OpenCode in a Modal Sandbox

This example demonstrates how to run OpenCode remotely and connect to it from your local terminal or browser.

Combine self-hosted OpenCode with serving a big, smart model on Modal and you’ve got “coding agents at home”!

Coding agents are most useful when they have context and tools. By default, this script clones the Modal examples repo and gives the agent access to your Modal credentials, so it can run and debug examples (including this one!). Meta.

A screenshot of the OpenCode Web UI showing this coding agent running its own code

Set up OpenCode on Modal 

First, we define a Modal container Image with OpenCode installed.

Clone a GitHub repository 

Next, we clone the code we want the agent to work on. The repository is cloned into the container image at build time, so it’s available when the Sandbox starts.

Grant Modal credentials 

Since the agent is working with Modal code, we also make it easy to provide Modal access. Examples in this repo should run with nothing more than modal installed — except for a few that use fastapi.

Start the Sandbox 

Now, we create a Modal Sandbox to run our coding agent session. This Sandbox has our environment Image and a password for authentication.

We open up the OPENCODE_PORT so that the server can be accessed over the Internet.

OpenCode is truly open — there are many interfaces to the underlying coding agent server. Here we print information for:

  • directly accessing the underlying Modal Sandbox for debugging or “pair coding” with the agent
  • accessing the Web UI from a local browser (with authentication!)
  • accessing the TUI from your local terminal

The server is secured via a password in a Modal Secret. You can create one by heading to the Secrets Dashboard and creating a new “Custom” Secret. Use OPENCODE_SERVER_PASSWORD as the key and the password as the value.

The CLI will also give you a helpful one-liner you can use to recover the password with your Modal credentials in case you forget it.

Putting it all together 

Command-line options 

This script supports configuration via command-line arguments. Run with --help to see all options.

To grant the agent the same GitHub permissions you have, you can pass a GitHub personal access token. If you use the gh CLI, you can use shell command substitution to pass your current auth: