# Connect to Running Sandbox
<subtitle>Re-establish connection to running or paused sandboxes through sandbox ID.</subtitle>

## Environment Setup

Before using the SDK, please ensure that the `AGENTBOX_API_KEY` environment variable is configured.

>
> You can obtain your API key from the [Console API Keys page](https://console.ucloud.cn/modelverse/experience/api-keys).

```bash
export AGENTBOX_API_KEY=your_api_key
```

In some scenarios, you may need to reuse existing sandbox instances across processes and sessions. Through the `Sandbox.connect()` method, you can regain control of the target environment using the sandbox ID.

## Connection Process

### 1. Get Target Sandbox ID

You usually read previously saved IDs from a database, or dynamically retrieve them through `Sandbox.list()`.

```python
from ucloud_sandbox import Sandbox

# Retrieve first running sandbox
paginator = Sandbox.list()
running_sandboxes = paginator.next_items()

if not running_sandboxes:
    print("No active sandboxes found.")
else:
    target_id = running_sandboxes[0].sandbox_id
    print(f"Preparing to connect to: {target_id}")
```

### 2. Establish Connection

Use the `connect` method. If the target sandbox is in `PAUSED` state, this operation will automatically wake the sandbox into `RUNNING` state.

```python
from ucloud_sandbox import Sandbox

# Establish connection
# Note: connect also resets the sandbox's inactive timeout
sandbox = Sandbox.connect("your-sandbox-id")

# Can directly execute commands after connection
result = sandbox.commands.run("whoami")
print(result.stdout)
```

## Notes

>
> **Timeout Reset**: Connecting to a sandbox will automatically reset the inactive timeout of that instance to the default value (5 minutes) or the `timeout` parameter value you explicitly specify.

>
> **Invalid ID**: If the target sandbox has been destroyed (Killed) or the ID is incorrect, this method will throw a `NotFoundException` exception. It is recommended to wrap it with `try-except` in production environments.