If you have a running sandbox, you can connect to it using the Sandbox.connect() method and then start controlling it with our SDK. This is useful if you want to, for example, reuse the same sandbox instance for the same user after a short period of inactivity.

1. Get the sandbox ID

To connect to a running sandbox, you first need to retrieve its ID. You can do this by calling the Sandbox.list() method.
import { Sandbox } from "novita-sandbox/code-interpreter"

// Get all running sandboxes
const runningSandboxesPaginator = await Sandbox.list({
  query: {
    state: ["running"],
  },
})

const runningSandboxes = await runningSandboxesPaginator.nextItems()
if (runningSandboxes.length === 0) {
  throw new Error("No running sandboxes found")
}
const runningSandboxId = runningSandboxes[0].sandboxId

console.log(`got a running sandbox: ${runningSandboxId}`)

2. Connect to the sandbox

Now that you have the sandbox ID, you can connect to the sandbox using the Sandbox.connect() method.
import { Sandbox } from "novita-sandbox/code-interpreter"

// Get all running sandboxes
const runningSandboxesPaginator = await Sandbox.list({
  query: {
    state: ["running"],
  },
})

const runningSandboxes = await runningSandboxesPaginator.nextItems()
if (runningSandboxes.length === 0) {
  throw new Error("No running sandboxes found")
}
const runningSandboxId = runningSandboxes[0].sandboxId

// connect to the sandbox.
const sandbox = await Sandbox.connect(runningSandboxId)
console.log("connected to sandbox: ", sandbox.sandboxId)

// Now you can use the sandbox as usual
// ...