> ## Documentation Index
> Fetch the complete documentation index at: https://docs.novita.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Cross-Region Migration

You can move a sandbox from the [v1 region](https://docs.novita.ai/guides/sandbox-overview.md#regions) (`us-va-1`) to the [v2 region](https://docs.novita.ai/guides/sandbox-overview.md#regions) (`us-phx-1`) with the SDK. The migration copies the sandbox filesystem and the template it depends on to the target region, where the sandbox is paused under the same Sandbox ID until you resume it. You can also distribute one of your own templates to the target region on its own, without moving any sandbox.

Migration requires `novita-sandbox` 2.1.3 or later.

## Before You Start

Your account needs access to both regions and the migration feature. You also need an API key, the source region name, and the Sandbox ID you want to move.

```bash JavaScript & TypeScript icon="js" theme={"system"}
npm i 'novita-sandbox@>=2.1.3'
```

```bash Python icon="python" theme={"system"}
pip install 'novita-sandbox>=2.1.3'
```

Create one client for each region. The source region name and the domain of each region are listed in the [Regions](https://docs.novita.ai/guides/sandbox-overview.md#regions) table. Use the name from that table as the source region. Do not derive it from the domain.

```js JavaScript & TypeScript icon="js" theme={"system"}
import { Novita } from 'novita-sandbox'

const sourceRegion = 'us-va-1' // source region name, see the Regions table
const source = new Novita({
  apiKey: process.env.NOVITA_API_KEY,
  domain: 'sandbox.novita.ai', // v1 region (us-va-1)
})
const target = new Novita({
  apiKey: process.env.NOVITA_API_KEY,
  domain: 'us-phx-1.sandbox.novita.ai', // v2 region (us-phx-1)
})
```

```python Python icon="python" theme={"system"}
import os
from novita_sandbox.core import Novita

source_region = "us-va-1"  # source region name, see the Regions table
source = Novita(
    api_key=os.environ["NOVITA_API_KEY"],
    domain="sandbox.novita.ai",  # v1 region (us-va-1)
)
target = Novita(
    api_key=os.environ["NOVITA_API_KEY"],
    domain="us-phx-1.sandbox.novita.ai",  # v2 region (us-phx-1)
)
```

The source client pauses the sandbox. The target client starts the migration, polls the job, and connects to the migrated sandbox. The target region is whichever region the `target` client points at, so there is no separate target region parameter. The rest of this guide uses these two clients.

## Migrate Sandboxes

> [!WARNING]
>
> Once the migration completes, the sandbox is no longer available in the source region. In the target region it is `paused`, and you need to resume it yourself. If the sandbox was created with [auto resume](https://docs.novita.ai/guides/sandbox-pause-resume.md#auto-pause-and-resume) enabled, that setting carries over, and the sandbox resumes on the next request without a manual step.

### Migrate a Sandbox

Only a sandbox in the paused state can be migrated. The service copies the files from the source sandbox and the template it was built from to the target region. When migration completes, the sandbox is paused in the target region under the same Sandbox ID. Connect through the target client to resume it.

| Item | After migration |
| - | - |
| Files, installed packages, and configuration in the sandbox filesystem | Kept, as they were when you paused the sandbox |
| Sandbox ID | Unchanged. Connect through the target domain |
| Running processes, in-memory variables, and in-flight tasks | Not kept. Restart them or recover from files you saved before pausing |
| Default command user | Commands run as `root` with `/root` as the working directory. Pass `user` and `cwd` to keep the original user |
| External databases and object storage | Not part of the migration. Check that the target region can reach them |

```mermaid theme={"system"}
flowchart LR
    A["Pause the source sandbox"] --> B["Start the migration, save the job ID"]
    B --> C["Poll the job until it finishes"]
    C --> D["Connect with the target domain and the same Sandbox ID"]
    style A fill:#f3f4f6,stroke:#9ca3af,color:#111827
    style B fill:#f3f4f6,stroke:#9ca3af,color:#111827
    style C fill:#f3f4f6,stroke:#9ca3af,color:#111827
    style D fill:#f3f4f6,stroke:#9ca3af,color:#111827
```

The template's start command (`start_cmd`) runs again in the target region and launches a fresh application process. Commands you started by hand, for example with `sandbox.commands.run`, are not replayed. If the template has no start command, or your application is started some other way, connect to the migrated sandbox and start it yourself.

**1. Pause the Source Sandbox**

Stop your workload, save the state you need to files, then pause the sandbox. `pause` returns before the sandbox has finished pausing, so poll `getInfo` / `get_info` until the state is `paused` before you submit the migration. If the sandbox is already `paused`, skip to the next step.

```js JavaScript & TypeScript icon="js" theme={"system"}
const sandboxId = '<source Sandbox ID>'

await source.sandbox.pause(sandboxId)

const deadline = Date.now() + 120_000
let state = (await source.sandbox.getInfo(sandboxId)).state
while (state !== 'paused') {
  if (Date.now() > deadline) {
    throw new Error(`Sandbox ${sandboxId} is still ${state} after 120s`)
  }
  await new Promise((resolve) => setTimeout(resolve, 2_000))
  state = (await source.sandbox.getInfo(sandboxId)).state
}
console.log('Source sandbox state:', state)
```

```python Python icon="python" theme={"system"}
import time

sandbox_id = "<source Sandbox ID>"

source.sandbox.pause(sandbox_id)

deadline = time.monotonic() + 120
state = source.sandbox.get_info(sandbox_id).state
while state != "paused":
    if time.monotonic() > deadline:
        raise RuntimeError(f"Sandbox {sandbox_id} is still {state} after 120s")
    time.sleep(2)
    state = source.sandbox.get_info(sandbox_id).state
print("Source sandbox state:", state)
```

**2. Start the Migration**

```js JavaScript & TypeScript icon="js" theme={"system"}
const jobId = await target.job.migrateSandbox(sandboxId, {
  sourceRegion,
})
console.log('Migration job ID:', jobId)
```

```python Python icon="python" theme={"system"}
job_id = target.job.migrate_sandbox(
    sandbox_id,
    source_region=source_region,
)
print("Migration job ID:", job_id)
```

The template the sandbox depends on is handled as part of the migration, so you do not need to distribute it first. If the target region reports a template name conflict, you can rename the template there by passing an optional template alias (`templateAlias` in JavaScript, `template_alias` in Python). This only works for templates you own, not for public templates owned by another account. See [Template Alias](#template-alias-and-public-templates) for the naming rules.

**3. Wait for the Job**

> [!NOTE]
>
> **Migration time:** Plan for approximately 5–15 minutes to migrate a single sandbox. Larger snapshots, more layers, or batch migrations may take longer. This estimate is for planning purposes only; actual duration depends on how the job progresses.

While the migration runs, leave the source sandbox alone. That includes SDK commands, file operations, and direct requests to the sandbox URL. Do not use the source sandbox to judge progress.

| Phase | Source sandbox |
| - | - |
| Migrating or cancelling | Requests to resume the paused sandbox are blocked by the migration. Poll the job from the target client and wait |
| Migration completed | The source side no longer allows connecting or resuming. Lookups return not found and the sandbox disappears from the list. Use the target domain with the same Sandbox ID |
| Failed or cancelled | Stop here. Check the job result and the source sandbox state before you resume it or submit a new migration. Do not connect in the target region |

The code below keeps waiting on the same job ID after a timeout, and stops the flow if the job fails or is cancelled. Only continue to the next step when `wait` returns a result.

```js JavaScript & TypeScript icon="js" theme={"system"}
import { JobCancelledError, JobFailedError, TimeoutError } from 'novita-sandbox'

let result
while (result === undefined) {
  try {
    result = await target.job.wait(jobId, {
      timeoutMs: 1_800_000,
      pollIntervalMs: 10_000,
    })
  } catch (err) {
    if (err instanceof TimeoutError) {
      // The server-side job is still running. Wait for the same job again.
      console.log('Wait timed out, keep polling the same job:', jobId)
      continue
    }
    if (err instanceof JobFailedError) {
      console.error('Migration failed, keep the job ID for troubleshooting:', jobId, err.status.status)
    } else if (err instanceof JobCancelledError) {
      console.error('Job cancelled:', jobId, err.status.status)
    }
    // Stop here. Do not connect in the target region and do not create a new job.
    throw err
  }
}
console.log('Migration result:', result.status)
console.log('Completed:', result.completed, 'Failed:', result.failed, 'Total:', result.total)
```

```python Python icon="python" theme={"system"}
from novita_sandbox.core import JobCancelledError, JobFailedError
from novita_sandbox.core.exceptions import TimeoutException

result = None
while result is None:
    try:
        result = target.job.wait(job_id, timeout=1800, poll_interval=10)
    except TimeoutException:
        # The server-side job is still running. Wait for the same job again.
        print("Wait timed out, keep polling the same job:", job_id)
    except JobFailedError as exc:
        print("Migration failed, keep the job ID for troubleshooting:", job_id, exc.status)
        # Stop here. Do not connect in the target region and do not create a new job.
        raise
    except JobCancelledError as exc:
        print("Job cancelled:", job_id, exc.status)
        raise
print("Migration result:", result.status)
print("Completed:", result.completed, "Failed:", result.failed, "Total:", result.total)
```

A timeout on `wait` does not cancel the server-side job and does not mean the migration failed. The loop above calls `wait` again with the same job ID. **Do not create a new job.** If the job fails or is cancelled, the code raises and the flow ends. Keep the job ID, check the job items with `job.get`, and check the source sandbox state before you decide what to do next.

To check progress at any time:

```js JavaScript & TypeScript icon="js" theme={"system"}
const progress = await target.job.get(jobId)
console.log(progress.status, progress.completed, progress.failed, progress.cancelled, progress.total)
for (const item of progress.items) {
  console.log(item.resourceType, item.resourceId, item.status)
}
```

```python Python icon="python" theme={"system"}
progress = target.job.get(job_id)
print(progress.status, progress.completed, progress.failed, progress.cancelled, progress.total)
for item in progress.items:
    print(item.resource_type, item.resource_id, item.status)
```

**4. Connect in the Target Region**

Only connect once the job is `completed`, has no failed or cancelled items, and the item for your sandbox is `completed`. Check this in code before you call `connect`, then connect with the same Sandbox ID through the target client:

```js JavaScript & TypeScript icon="js" theme={"system"}
const item = result.items.find((i) => i.resourceId === sandboxId)
if (
  result.status !== 'completed' ||
  result.failed > 0 ||
  result.cancelled > 0 ||
  item?.status !== 'completed'
) {
  throw new Error(`Job ${jobId} did not migrate sandbox ${sandboxId}, do not connect`)
}

const sandbox = await target.sandbox.connect(sandboxId, { timeoutMs: 300_000 })
const output = await sandbox.commands.run('ls -la', { user: 'user', cwd: '/home/user' })
console.log(output.stdout)
```

```python Python icon="python" theme={"system"}
item = next((i for i in result.items if i.resource_id == sandbox_id), None)
if (
    result.status != "completed"
    or result.failed > 0
    or result.cancelled > 0
    or item is None
    or item.status != "completed"
):
    raise RuntimeError(f"Job {job_id} did not migrate sandbox {sandbox_id}, do not connect")

sandbox = target.sandbox.connect(sandbox_id, timeout=300)
output = sandbox.commands.run("ls -la", user="user", cwd="/home/user")
print(output.stdout)
```

`connect` resumes the sandbox from its paused state. In the migrated sandbox, commands run as `root` by default, with `/root` as the working directory. The example passes `user` and `cwd` explicitly to keep the user and working directory the source sandbox used. Pass them on every command and file operation that depends on the original user. Check your files, the application state, and access to external services. If the application is not running, start it with `sandbox.commands.run`. Send all further requests to the target domain.

### Migrate Several Sandboxes

You can submit several sandboxes in one job:

```js JavaScript & TypeScript icon="js" theme={"system"}
// Make sure every sandbox is paused before you run this.
const sandboxIds = ['<Sandbox ID 1>', '<Sandbox ID 2>']
const jobId = await target.job.migrateSandboxes(sandboxIds, {
  sourceRegion,
})
console.log('Batch job ID:', jobId)
```

```python Python icon="python" theme={"system"}
# Make sure every sandbox is paused before you run this.
sandbox_ids = ["<Sandbox ID 1>", "<Sandbox ID 2>"]
job_id = target.job.migrate_sandboxes(
    sandbox_ids,
    source_region=source_region,
)
print("Batch job ID:", job_id)
```

## Distribute Templates

> [!NOTE]
>
> Distribution copies the template. It only migrates data that has been persisted to disk; in-memory data is not migrated. After it completes, the template is available in both the source and the target region.

### Distribute a Template

You can distribute a template to the target region on its own, without migrating any sandbox. The template becomes available there under the alias you choose, and you can create new sandboxes from it right away. Distribution takes the Template ID, and the template alias is required:

```js JavaScript & TypeScript icon="js" theme={"system"}
const templateId = '<source Template ID>'
const targetAlias = 'my-agent-base'

const jobId = await target.job.distributeTemplate(templateId, {
  sourceRegion,
  templateAlias: targetAlias,
})
const result = await target.job.wait(jobId, {
  timeoutMs: 1_800_000,
  pollIntervalMs: 10_000,
})
console.log('Distribution result:', result.status, 'Failed:', result.failed)

const item = result.items.find((i) => i.resourceId === templateId)
if (
  result.status !== 'completed' ||
  result.failed > 0 ||
  result.cancelled > 0 ||
  item?.status !== 'completed'
) {
  throw new Error(`Job ${jobId} did not distribute template ${templateId}`)
}
```

```python Python icon="python" theme={"system"}
template_id = "<source Template ID>"
target_alias = "my-agent-base"

job_id = target.job.distribute_template(
    template_id,
    source_region=source_region,
    template_alias=target_alias,
)
result = target.job.wait(job_id, timeout=1800, poll_interval=10)
print("Distribution result:", result.status, "Failed:", result.failed)

item = next((i for i in result.items if i.resource_id == template_id), None)
if (
    result.status != "completed"
    or result.failed > 0
    or result.cancelled > 0
    or item is None
    or item.status != "completed"
):
    raise RuntimeError(f"Job {job_id} did not distribute template {template_id}")
```

The check above only passes when the job is `completed`, has no failed or cancelled items, and the template item is `completed`. Then create a sandbox from the alias:

```js JavaScript & TypeScript icon="js" theme={"system"}
const sandbox = await target.sandbox.create(targetAlias, { timeoutMs: 300_000 })
console.log('New Sandbox ID:', sandbox.sandboxId)
```

```python Python icon="python" theme={"system"}
sandbox = target.sandbox.create(template=target_alias, timeout=300)
print("New Sandbox ID:", sandbox.sandbox_id)
```

### Distribute Several Templates

You can submit several templates in one job. The batch uses one source region, and the target region comes from the `target` client's domain.

```js JavaScript & TypeScript icon="js" theme={"system"}
const aliases = new Map([
  ['<source Template ID 1>', 'my-agent-base-a'],
  ['<source Template ID 2>', 'my-agent-base-b'],
])

const jobId = await target.job.distributeTemplates(Array.from(aliases.keys()), {
  sourceRegion,
  templateAlias: (templateId) => {
    const alias = aliases.get(templateId)
    if (alias === undefined) throw new Error(`Missing alias for ${templateId}`)
    return alias
  },
})
console.log('Batch job ID:', jobId)

const result = await target.job.wait(jobId, {
  timeoutMs: 1_800_000,
  pollIntervalMs: 10_000,
})
console.log('Job status:', result.status)
console.log('Completed:', result.completed, 'Failed:', result.failed, 'Total:', result.total)
for (const item of result.items) {
  console.log(item.resourceType, item.resourceId, item.status)
}
```

```python Python icon="python" theme={"system"}
aliases = {
    "<source Template ID 1>": "my-agent-base-a",
    "<source Template ID 2>": "my-agent-base-b",
}

job_id = target.job.distribute_templates(
    list(aliases),
    source_region=source_region,
    template_alias=lambda template_id: aliases[template_id],
)
print("Batch job ID:", job_id)

result = target.job.wait(job_id, timeout=1800, poll_interval=10)
print("Job status:", result.status)
print("Completed:", result.completed, "Failed:", result.failed, "Total:", result.total)
for item in result.items:
    print(item.resource_type, item.resource_id, item.status)
```

Every alias in the batch is checked for conflicts and ownership in the same way as a single alias. See [Template Alias](#template-alias-and-public-templates).

## Template Alias and Public Templates

### Choosing an Alias

An alias is the template name you pass when creating a sandbox, such as `my-agent-base`. To migrate a sandbox you only need its Sandbox ID. The service looks up the template it depends on and decides whether the target name can be reused. You only need a Template ID when you distribute a template on its own.

* If the name is free, or the existing name can be reused, the migration goes ahead.
* If the name conflicts, the request is rejected and no job is created. Change the alias and submit again.

A name conflict returns:

| Field | Value |
| - | - |
| HTTP status | `409` |
| Reason | `MIGRATION_TEMPLATE_ALIAS_CONFLICT` |
| Message | `template alias already taken in the target region` |
| SDK exception | `TemplateAliasConflictError` |

```js JavaScript & TypeScript icon="js" theme={"system"}
import { TemplateAliasConflictError } from 'novita-sandbox'

let jobId
try {
  jobId = await target.job.migrateSandbox(sandboxId, {
    sourceRegion,
    templateAlias: 'my-agent-base',
  })
  console.log('Migration job ID:', jobId)
} catch (err) {
  if (err instanceof TemplateAliasConflictError) {
    console.log('Template alias conflict in the target region. Change templateAlias and submit again.')
    console.log(err.message)
  } else {
    throw err
  }
}
```

```python Python icon="python" theme={"system"}
from novita_sandbox.core import TemplateAliasConflictError

try:
    job_id = target.job.migrate_sandbox(
        sandbox_id,
        source_region=source_region,
        template_alias="my-agent-base",
    )
    print("Migration job ID:", job_id)
except TemplateAliasConflictError as exc:
    print("Template alias conflict in the target region. Change template_alias and submit again.")
    print(exc)
```

You can leave the alias out when migrating a sandbox. The service then uses the source name, or the Template ID if there is no source name. The default name is still checked for conflicts, and the SDK does not generate a new name for you.

### Sandboxes Built on Another Account's Public Template

In regions that support cross-account template migration, the service resolves the template dependency based on who owns the template and whether it is public. The migrated sandbox is still yours, and you connect to it with the target domain and the same Sandbox ID.

Migrating a sandbox does not transfer someone else's template to you, and it does not create an alias for that template under your account. Passing a template alias does not change ownership either. The alias check still runs when the request is accepted, and a conflict returns the error above.

A completed migration does not guarantee that the source alias is available in the target region, or that the template stays public. To create new sandboxes from it, use a Template ID or alias you can access in the target region. If the owner makes the template private, you may no longer be able to create sandboxes from it. Access to a public template does not include permission to modify or delete it.

## Job Status, Cancellation, and Troubleshooting

### Job Status

| Status | Meaning | Next step |
| - | - | - |
| `migrating` | The migration is in progress | Keep polling |
| `reverting` | Rolling back and cleaning up | Wait for a final state |
| `completed` | The job finished | Check each item, then verify the resources in the target region |
| `failed` | The job failed | Check each item and keep the job ID for troubleshooting |
| `cancelled` | Cancellation finished | Check the source resources before doing anything else |

The job response reports a status per item but not the full internal failure reason. When you contact support, include the job ID, the Sandbox ID or Template ID, the source region, the target domain, the time of the failure, and the error message.

### Cancel a Job

```js JavaScript & TypeScript icon="js" theme={"system"}
import { CancelTooLateError } from 'novita-sandbox'

try {
  const result = await target.job.cancel(jobId)
  console.log('Status after cancel:', result.status)
} catch (err) {
  if (err instanceof CancelTooLateError) {
    console.log('The job can no longer be cancelled, keep polling:', jobId)
  } else {
    throw err
  }
}
```

```python Python icon="python" theme={"system"}
from novita_sandbox.core import CancelTooLateError

try:
    result = target.job.cancel(job_id)
    print("Status after cancel:", result.status)
except CancelTooLateError:
    print("The job can no longer be cancelled, keep polling:", job_id)
```

A `reverting` status means the cancellation was accepted and cleanup is still running. Poll with `job.get` until the job reaches a final state. A job in its last phase may not be cancellable, so go by what the cancel call returns.

A cancelled or failed job does not restore the source sandbox automatically. Check the rollback result and the source sandbox state before you reconnect to it or migrate again.

### Common Issues

| Symptom | What to do |
| - | - |
| You have a job ID but cannot connect to the target sandbox yet | The migration is still running. Keep polling the job |
| `wait` times out | Poll the same job ID, or call `wait` again |
| The request timed out before returning a job ID | Look for an existing job with `job.list` filtered by the Sandbox ID before you submit again |
| The error says the resource is already migrating | Wait for the existing job to finish instead of submitting another |
| `TemplateAliasConflictError` (409) | Change the template alias and submit again. No job was created |
| `InvalidArgumentError` / `InvalidArgumentException` when distributing several templates | A single alias string was passed for a batch. Pass a function that returns a distinct alias for each Template ID. No request was sent |
| The error says the source sandbox is not paused | `pause` returns before pausing finishes. Poll `getInfo` / `get_info` until the state is `paused`, then submit |
| The error says migration is not supported | Check the target domain, your account permissions, and whether migration is enabled for this environment |
| The job failed | Check each item's status and contact support to confirm the source and target resources before retrying |
| Processes are gone after migration | Running processes are not kept. The template start command runs again; start anything else yourself |
| Files are missing, or paths resolve under `/root` | Commands run as `root` by default after migration. Pass `user` and `cwd` to run as the original user |
| The old domain cannot connect to the migrated sandbox | Use the target domain with the same Sandbox ID |

Never include your API key in error logs, support tickets, or code samples.

## FAQ

### What do I need to do before using a Volume in a migrated sandbox?

The migrated sandbox needs the NFS client dependencies before it can mount a Volume. If `nfs-common` is not installed, install it inside the sandbox first, then mount the Volume. For a sandbox that uses `apt-get`, run the following after connecting to the migrated sandbox:

```python Python icon="python" theme={"system"}
sandbox.commands.run(
    "sudo -n apt-get update && sudo -n apt-get install -y nfs-common",
    user="user",
    timeout=300,
)
```

This example requires the `user` account to have passwordless `sudo` access.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.