Metadata-Version: 2.5
Name: pandastack
Version: 0.10.0
Summary: Python SDK for PandaStack — open-source Firecracker microVM sandboxes
Project-URL: Homepage, https://pandastack.ai
Project-URL: Repository, https://github.com/pandastack-io/pandastack
Project-URL: Documentation, https://docs.pandastack.ai
Project-URL: Issues, https://github.com/pandastack-io/pandastack-ai/issues
Author: PandaStack
License-Expression: Apache-2.0
License-File: LICENSE
Keywords: ai-agents,code-interpreter,firecracker,microvm,pandastack,sandbox
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: System :: Distributed Computing
Classifier: Topic :: System :: Emulators
Requires-Python: >=3.9
Requires-Dist: requests>=2.31
Provides-Extra: dev
Requires-Dist: pytest>=7; extra == 'dev'
Requires-Dist: responses>=0.24; extra == 'dev'
Description-Content-Type: text/markdown

# PandaStack Python SDK

Python SDK for PandaStack, open-source Firecracker microVM sandboxes for AI agents and code execution.

## Install

```bash
pip install pandastack
```

## Auth

Create a token in the PandaStack dashboard, then export it:

```bash
export PANDASTACK_API_KEY=pds_...
# Optional for self-hosted/dev:
export PANDASTACK_API=http://localhost:8080
```

`Client()` also reads `~/.config/pandastack/config.json` when environment variables are unset.

## Quickstart

```python
from pandastack import Sandbox

with Sandbox.create(template="code-interpreter") as sb:
    result = sb.run_code("print(2 + 2)")
    print(result.stdout.strip())
```

## Explicit client

```python
from pandastack import Client

client = Client(api_key="pds_xxx", api_url="https://api.pandastack.ai")
sb = client.sandboxes.create(template="code-interpreter")
try:
    print(sb.exec("ls -la").stdout)
finally:
    sb.kill()
```

## Capacity retries

When the platform is briefly out of room, the SDK retries `sandboxes.create`, `Sandbox.create`, `fork` and `fork_tree` for you. It resends a create only after a refusal that the platform sends before any sandbox exists:

| Response | Retried? |
|---|---|
| `503 no compute capacity available` with `Retry-After: 5` (the scheduler found no host) | Yes |
| `503 sandbox host unavailable` with `Retry-After: 15` (a fork whose parent's host is down) | Yes |
| `507 insufficient host memory/storage for sandbox` (the host's admission gate) | Yes |
| `429` with `Retry-After` (the per-workspace rate limiter, `Retry-After: 1`) | Yes |
| `429` without `Retry-After` (quotas such as `max sandboxes reached`) | No, raised at once |
| `503` without `Retry-After` or without a JSON `error` body, such as the load balancer's own `503` when an API edge drops a connection | No |
| `500`, `502`, any other status, a dropped connection, a timeout | No |

The responses that are not retried can follow a create that went through, so resending them could make a second sandbox.

**Schedule.** Each wait is the server's `Retry-After` plus a random jitter whose cap doubles per retry: 1 s, 2 s, 4 s, 8 s, then 15 s. A scheduler refusal (`Retry-After: 5`) therefore waits 5–6 s, then 5–7 s, 5–9 s, 5–13 s, then 5–20 s, which is about 5 to 9 retries (usually 6 to 8) in the default 60-second budget. A `507` carries no `Retry-After`, so it waits 0.5 s plus the jitter (0.5–1.5 s, then 0.5–2.5 s, … up to 15.5 s). A `Retry-After` that does not fit in the budget left ends the retry at once. A wait that would overrun the budget is shortened to end at it, but never below `Retry-After` or 1 s. When the budget runs out, the last refusal is raised unchanged (same exception type and message: `ServerError` for 503/507).

```python
import logging
from pandastack import Client

logging.basicConfig()
logging.getLogger("pandastack").setLevel(logging.INFO)  # one log line per retry

client = Client(
    max_create_retry_seconds=120,  # 0 disables; env: PANDASTACK_MAX_CREATE_RETRY_SECONDS
    on_create_retry=lambda e: print(f"retry {e.attempt}: HTTP {e.status_code} {e.error}, waiting {e.delay_seconds:.1f}s"),
)
```

If `on_create_retry` raises, the exception propagates and retrying stops. It is not called for a refusal that arrives after you set `cancel`.

**Blocking and cancellation.** The budget limits when the last attempt can *start*. An attempt already running keeps its full `timeout`, so a create can block for up to about `max_create_retry_seconds + timeout`. If you run creates under your own deadline, set the budget below it. If you may abandon the call (a futures timeout, `asyncio.wait_for` around `run_in_executor`), also pass a `cancel` event and set it when you give up. No attempt is sent after that, a pending wait ends at once, and the call raises `CreateCancelled`:

```python
import threading
from concurrent.futures import ThreadPoolExecutor, TimeoutError

pool = ThreadPoolExecutor()
cancel = threading.Event()
future = pool.submit(client.sandboxes.create, template="agent", cancel=cancel)
try:
    sb = future.result(timeout=20)
except TimeoutError:
    cancel.set()  # the worker stops retrying now instead of 60 s later
```

`cancel` takes a `threading.Event` or a `multiprocessing.Event` (anything with `is_set()` and a blocking `wait(timeout)`). An `asyncio.Event` raises `TypeError` before anything is sent: the create blocks its thread, so run it with `asyncio.to_thread` or `run_in_executor` and pass a `threading.Event`.

An attempt already in flight cannot be interrupted. If it succeeds after you set `cancel`, the call still returns that sandbox, so delete it from the future if you no longer want it.

**What this does not cover.** The retry relies on how the platform answers today, not on an idempotency key. If a create's response is lost (a timeout, a dropped connection, a `502`), the SDK raises and the sandbox may still exist. Tag creates with `metadata` you can recognise, then list and reconcile before creating again.

## Filesystem

```python
sb.filesystem.write("/home/panda/hello.txt", "hello")
print(sb.filesystem.read("/home/panda/hello.txt"))
sb.filesystem.upload("local.csv", "/home/panda/local.csv")
sb.filesystem.download("/home/panda/out.png", "out.png")
```

## Commands and logs

```python
result = sb.commands.run("python3 --version", timeout=10)
for line in sb.logs(stream="both", follow=False):
    print(line)
```

## Lifecycle

```python
sb.set_ttl(600)
sb.set_persistent(True)
print(sb.lifecycle())
sb.pause()
sb.resume()
snapshot_id = sb.snapshot()
```

## Templates

```python
from pandastack import templates

print(templates.list())
build = templates.build("my-template", rootfs_tar="rootfs.tar", size_mb=2048)
print(build.status)
templates.delete("my-template")
```

## Tokens

```python
from pandastack import tokens

new_token = tokens.create("ci")
print(new_token.token)
for token in tokens.list():
    print(token.prefix, token.name)
tokens.revoke(new_token.prefix)
```

The old `pandastack` import remains as a deprecated compatibility alias. Use `pandastack` for new code.
