# InstaVM Python SDK

Official Python client for InstaVM code execution, VM lifecycle, snapshots, networking controls, browser automation, and platform APIs.

## Installation

```bash
pip install instavm
```

## Quick Start

```python
from instavm import InstaVM

client = InstaVM(api_key="your_api_key")

try:
    result = client.execute("print('hello from instavm')")
    print(result.get("stdout", ""))

    usage = client.get_usage()
    print(usage)
finally:
    client.close_session()
```

## Table of Contents

- [Core Workflows](#core-workflows)
- [Infrastructure & Platform APIs](#infrastructure-platform-apis)
- [Browser & Computer Use](#browser-computer-use)
- [Error Handling](#error-handling)
- [Development & Testing](#development-testing)
- [Docs Map (Further Reading)](#docs-map-further-reading)
- [Version / Changelog](#version-changelog)

<a id="core-workflows"></a>
## Core Workflows

### Code Execution + Session Basics

```python
from instavm import InstaVM

client = InstaVM(
    api_key="your_api_key",
    cpu_count=2,
    memory_mb=1024,
    env={"APP_ENV": "dev"},
    metadata={"team": "platform"},
)

result = client.execute("print('session id:', 'ok')")
print(result)
print(client.session_id)
```

### File Operations

```python
from instavm import InstaVM

client = InstaVM(api_key="your_api_key")

client.upload_file("local_script.py", "/app/local_script.py")
client.execute("python /app/local_script.py", language="bash")
client.download_file("output.json", local_path="./output.json")
```

### Async Execution

```python
from instavm import InstaVM

client = InstaVM(api_key="your_api_key")

task = client.execute_async("sleep 5 && echo 'done'", language="bash")
result = client.get_task_result(task["task_id"], poll_interval=2, timeout=60)
print(result)
```

### VM Management + Snapshots

```python
from instavm import InstaVM

client = InstaVM(api_key="your_api_key")

# VM lifecycle
vm = client.vms.create(wait=True, metadata={"purpose": "dev"})
vms = client.vms.list()  # GET /v1/vms
all_records = client.vms.list_all_records()  # GET /v1/vms/

# Snapshot from running VM
snap_from_vm = client.vms.snapshot(vm_id=vm["vm_id"], wait=True, name="dev-base")

# Snapshot from OCI image (with env vars + Git clone at build time)
snap_from_oci = client.snapshots.create(
    oci_image="docker.io/library/python:3.11-slim",
    name="python-3-11-dev",
    vcpu_count=2,
    memory_mb=1024,
    snapshot_type="user",
    build_args={
        "git_clone_url": "https://github.com/example/repo.git",
        "git_clone_branch": "main",
        "envs": {"PIP_INDEX_URL": "https://pypi.org/simple"},
    },
)

user_snaps = client.snapshots.list(snapshot_type="user")
print(len(user_snaps))
```

### Networking (Egress, Shares, SSH)

```python
from instavm import InstaVM

client = InstaVM(api_key="your_api_key")

policy = client.set_session_egress(
    allow_package_managers=True,
    allow_http=False,
    allow_https=True,
    allowed_domains=["pypi.org", "files.pythonhosted.org"],
)
print(policy)

share = client.shares.create(port=3000, is_public=False)
client.shares.update(share_id=share["share_id"], is_public=True)

key = client.add_ssh_key("ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAA... user@host")
print(key)
```

<a id="infrastructure-platform-apis"></a>
## Infrastructure & Platform APIs

### Platform APIs (API Keys, Audit, Webhooks)

```python
from instavm import InstaVM

client = InstaVM(api_key="your_api_key")

api_key = client.api_keys.create(description="ci key")
audit_page = client.audit.events(limit=25, status="success")

endpoint = client.webhooks.create_endpoint(
    url="https://example.com/instavm/webhook",
    event_patterns=["vm.*", "snapshot.*"],
)

deliveries = client.webhooks.list_deliveries(limit=10)
print(api_key, audit_page, deliveries, endpoint)
```

<a id="browser-computer-use"></a>
## Browser & Computer Use

### Browser Automation

```python
from instavm import InstaVM

client = InstaVM(api_key="your_api_key")

session = client.browser.create_session(viewport_width=1366, viewport_height=768)
session.navigate("https://example.com")
links = session.extract_elements("a", ["text", "href"])
shot_b64 = session.screenshot(full_page=True)
print(len(links), len(shot_b64))
session.close()
```

### LLM-Friendly Content Extraction (concise pattern only)

```python
from instavm import InstaVM

client = InstaVM(api_key="your_api_key")

content = client.browser.extract_content(
    url="https://example.com/docs",
    include_interactive=True,
    include_anchors=True,
    max_anchors=30,
)

print(content["readable_content"].get("title"))
for anchor in (content.get("content_anchors") or [])[:5]:
    print(anchor.get("text"), anchor.get("selector"))
```

### Computer Use

```python
from instavm import InstaVM

client = InstaVM(api_key="your_api_key")

# Any active execution session id works
session_id = client.session_id
viewer = client.computer_use.viewer_url(session_id)
state = client.computer_use.get(session_id, "/state")

print(viewer)
print(state)
```

<a id="error-handling"></a>
## Error Handling

```python
from instavm import (
    InstaVM,
    AuthenticationError,
    ExecutionError,
    NetworkError,
    RateLimitError,
    SessionError,
)

client = InstaVM(api_key="your_api_key")

try:
    client.execute("raise Exception('boom')")
except AuthenticationError:
    print("Invalid API key")
except RateLimitError:
    print("Rate limited")
except SessionError as exc:
    print(f"Session issue: {exc}")
except ExecutionError as exc:
    print(f"Execution failed: {exc}")
except NetworkError as exc:
    print(f"Network issue: {exc}")
```

<a id="development-testing"></a>
## Development & Testing

```bash
# Install local package for development
pip install -e .

# Run focused unit tests
python3 -m unittest tests/test_api_client.py
```

<a id="docs-map-further-reading"></a>
## Docs Map (Further Reading)

- [Python SDK Overview](https://instavm.io/docs/sdks/python/overview)
- [VM Management](https://instavm.io/docs/sdks/python/vm-management)
- [Snapshots](https://instavm.io/docs/sdks/python/snapshots)
- [Egress and Networking](https://instavm.io/docs/sdks/python/egress-and-networking)
- [Platform APIs](https://instavm.io/docs/sdks/python/platform-apis)
- [Browser Automation](https://instavm.io/docs/sdks/python/browser-automation)
- [Error Handling](https://instavm.io/docs/sdks/python/error-handling)

<a id="version-changelog"></a>
## Version / Changelog

Current package version: `0.11.0`.

Highlights in this line:
- Manager-based APIs across VMs, snapshots, shares, custom domains, computer use, API keys, audit, and webhooks
- Snapshot build args support for env vars and Git clone inputs
- Distinct VM list helpers for `/v1/vms` and `/v1/vms/`

For detailed history, see repository tags and PR history.
