diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..cde2dcc --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,24 @@ +name: Publish to PyPI + +on: + push: + branches: + - main + +jobs: + pypi-publish: + name: Upload release to PyPI + runs-on: ubuntu-latest + environment: pypi + permissions: + id-token: write + steps: + - uses: actions/checkout@v4 + + - uses: astral-sh/setup-uv@v6 + + - name: Build package + run: uv build + + - name: Publish package distributions to PyPI + uses: pypa/gh-action-pypi-publish@release/v1 diff --git a/.gitignore b/.gitignore index 36b13f1..23b2ad4 100644 --- a/.gitignore +++ b/.gitignore @@ -174,3 +174,4 @@ cython_debug/ # PyPI configuration file .pypirc +CODE_EXECUTION.md diff --git a/.woodpecker/check.yml b/.woodpecker/check.yml new file mode 100644 index 0000000..23d9bba --- /dev/null +++ b/.woodpecker/check.yml @@ -0,0 +1,21 @@ +when: + event: push + branch: + - main + - dev + +steps: + unit-tests: + image: ghcr.io/astral-sh/uv:python3.13-bookworm + commands: + - uv sync --dev + - uv run pytest -m "not integration" -v + + integration-tests: + image: ghcr.io/astral-sh/uv:python3.13-bookworm + environment: + WRENN_API_KEY: + from_secret: WRENN_API_KEY + commands: + - uv sync --dev + - uv run pytest -m integration -v diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..cc00331 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,132 @@ +## Design Context + +### Users +Developers across the full spectrum — solo engineers building side projects, startup teams integrating sandboxed execution into products, and platform/infra engineers at larger organizations running production workloads on Firecracker microVMs. They arrive with context: they know what a process is, what a rootfs is, what a TTY means. The interface must feel at home for all three: approachable enough not to intimidate a hacker, precise enough to earn the trust of a production ops team. Never condescend, never oversimplify. Trust the user to understand what they're looking at. + +**Primary job to be done:** Understand what's running, act on it confidently, and get back to code. + +### Brand Personality +**Precise. Warm. Uncompromising.** + +Wrenn is an engineer's favorite tool — built with visible care, not assembled from defaults. It runs real infrastructure (Firecracker microVMs), so the UI should reflect that seriousness without becoming cold or corporate. The warmth comes from the typography and color palette; the precision comes from hierarchy, density, and data fidelity. + +Emotional goal: **in control.** Users leave a session with full confidence in what's running, what happened, and what comes next. Nothing is hidden, nothing is ambiguous. + +### Aesthetic Direction +**Dark-only (permanently), industrial-warm, data-forward.** + +No light mode planned. All design decisions should optimize for dark. The near-black-green background palette (`#0a0c0b` through `#2a302d`) reads as "black with intention" — not pitch black (cold) and not charcoal (dated). The sage green accent (`#5e8c58`) is muted and organic, a meaningful departure from the startup-green neon that saturates the developer tool space. + +**Anti-references:** +- **Supabase**: avoid the friendly, approachable startup-green energy — too generic, too eager to please +- **AWS / GCP consoles**: avoid utility-first density without craft — functional but joyless, visually dated + +**References that capture the right spirit:** +- The precision of a well-calibrated instrument +- Editorial typography from technical publications +- The quiet confidence of tools that don't need to explain themselves + +### Type System +Four fonts with strict roles — this is the design system's strongest personality trait and must be respected: + +| Font | CSS Class | Role | When to use | +|------|-----------|------|-------------| +| **Manrope** (variable, sans) | `font-sans` | UI workhorse | All body copy, nav, labels, buttons, form text | +| **Instrument Serif** | `font-serif` | Display / editorial | Page titles (h1), dialog headings, metric values, hero moments | +| **JetBrains Mono** (variable) | `font-mono` | Data / code | IDs, timestamps, key prefixes, file paths, terminal output, metrics | +| **Alice** | brand wordmark only | Brand wordmark | "Wrenn" in sidebar and login only — nowhere else | + +Instrument Serif at scale creates the signature editorial moments. Mono provides the precision signal for technical data. Never swap these roles. + +**Tracking overrides (app.css):** +- `.font-serif` — `letter-spacing: 0.015em` (positive tracking; Instrument Serif reads less condensed at display sizes) +- `.font-mono` — `font-variant-numeric: tabular-nums` (numbers align in tables and metric displays) + +**Type scale (root: 87.5% = 14px base):** +| Token | Value | Use | +|---|---|---| +| `--text-display` | 2.571rem (~36px) | Auth section headings | +| `--text-page` | 2rem (~28px) | Page h1 titles | +| `--text-heading` | 1.429rem (~20px) | Dialog headings, empty states | +| `--text-body` | 1rem (~14px) | Primary body, buttons, inputs | +| `--text-ui` | 0.929rem (~13px) | Nav labels, table cells | +| `--text-meta` | 0.857rem (~12px) | Key prefixes, minor info | +| `--text-label` | 0.786rem (~11px) | Uppercase section labels | +| `--text-badge` | 0.714rem (~10px) | Live badges, tiny indicators | + +### Color System + +All values are CSS custom properties in `frontend/src/app.css`. + +**Backgrounds (6-step near-black-green scale):** +| Token | Value | Use | +|---|---|---| +| `--color-bg-0` | `#0a0c0b` | Page base, sidebar deepest layer | +| `--color-bg-1` | `#0f1211` | Sidebar surface | +| `--color-bg-2` | `#141817` | Card backgrounds | +| `--color-bg-3` | `#1a1e1c` | Table headers, elevated surfaces | +| `--color-bg-4` | `#212624` | Hover states, inputs | +| `--color-bg-5` | `#2a302d` | Highlighted items, selected rows | + +**Text (5-level hierarchy):** +| Token | Value | Use | +|---|---|---| +| `--color-text-bright` | `#eae7e2` | H1s, dialog headings | +| `--color-text-primary` | `#d0cdc6` | Body copy, primary labels | +| `--color-text-secondary` | `#9b9790` | Secondary labels, descriptions | +| `--color-text-tertiary` | `#6b6862` | Hints, placeholders | +| `--color-text-muted` | `#454340` | Dividers as text, ultra-subtle | + +**Accent (sage green — use sparingly, must feel earned):** +| Token | Value | Use | +|---|---|---| +| `--color-accent` | `#5e8c58` | Primary CTA, live indicators, focus rings, active nav | +| `--color-accent-mid` | `#89a785` | Hover accent text | +| `--color-accent-bright` | `#a4c89f` | Accent on dark backgrounds | +| `--color-accent-glow` | `rgba(94,140,88,0.07)` | Subtle tinted backgrounds | +| `--color-accent-glow-mid` | `rgba(94,140,88,0.14)` | Hover tint on accent items | + +**Status semantics:** +| Token | Value | Use | +|---|---|---| +| `--color-amber` | `#d4a73c` | Warning, paused state | +| `--color-red` | `#cf8172` | Error, destructive actions | +| `--color-blue` | `#5a9fd4` | Info, neutral system states | + +**Borders:** `--color-border` (`#1f2321`) default; `--color-border-mid` (`#2a2f2c`) for inputs/hover. + +### Component Patterns + +**Buttons:** +- Primary: solid sage green (`--color-accent`), hover brightness boost + micro-lift (`-translate-y-px`) +- Secondary: bordered (`--color-border-mid`), text transitions to accent on hover +- Danger: red text + subtle red background on hover +- All: `transition-all duration-150` + +**Inputs:** +- Border `--color-border`, background `--color-bg-2`; focus transitions border and icon to accent +- Group focus pattern: `group` wrapper + `group-focus-within:text-[var(--color-accent)]` on icon + +**Tables / data lists:** +- Grid layout; header `bg-3` + uppercase `--text-label`; row hover `hover:bg-[var(--color-bg-3)]` +- Status stripe: left border color matches sandbox state + +**Status indicators:** Running = animated ping + sage green dot; Paused = amber dot; Stopped = muted gray. Color is never the sole differentiator. + +**Modals & dialogs:** Border + shadow only — no accent gradient bars/strips. `fadeUp` 0.35s entrance. + +**Empty states:** Large icon with glow, Instrument Serif heading, secondary body text, CTA below, `iconFloat` 4s animation. + +**Animations (always respect `prefers-reduced-motion`):** `fadeUp` (entrance), `status-ping` (live indicator), `iconFloat` (empty states), `spin-once` (refresh), staggered `animation-delay` on lists. + +### Design Principles + +1. **Precision over friendliness.** Every element earns its place. Wrenn doesn't need to tell you it's developer-friendly — that should be self-evident from the quality of the information architecture. + +2. **Density with breathing room.** Data-forward doesn't mean cramped. Strategic whitespace creates calm hierarchy within dense contexts. Sections breathe; rows don't waste space. + +3. **Industrial warmth.** The serif + mono + warm-black combination prevents sterility. This is a forge, not a gallery. The warmth is in the details, not the primary colors. + +4. **Legible at speed.** Users scan dashboards in seconds. Strong typographic contrast (serif h1, mono IDs, sans body), consistent patterns, and predictable placement let users orientate instantly without reading everything. + +5. **Craft signals trust.** For infrastructure that runs production code, the quality of the UI is a proxy for the quality of the product. Pixel-level decisions matter. Polish is not decoration — it's a trust signal. \ No newline at end of file diff --git a/LICENSE b/LICENSE index 583698c..6c40f1d 100644 --- a/LICENSE +++ b/LICENSE @@ -1,18 +1,18 @@ MIT License -Copyright (c) 2026 wrenn +Copyright (c) 2026 M/S Omukk, Bangladesh -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and -associated documentation files (the "Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and +associated documentation files (the "Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: -The above copyright notice and this permission notice shall be included in all copies or substantial +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT -LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO -EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER -IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT +LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO +EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/Makefile b/Makefile index 6d10f3c..7b1b356 100644 --- a/Makefile +++ b/Makefile @@ -1,8 +1,8 @@ # Makefile -.PHONY: generate +.PHONY: generate lint test check test-integration # Variables -SPEC_URL = "https://git.omukk.dev/wrenn/sandbox/raw/branch/main/internal/api/openapi.yaml" +SPEC_URL = "https://raw.githubusercontent.com/wrennhq/wrenn/refs/heads/main/internal/api/openapi.yaml" SPEC_PATH = "api/openapi.yaml" generate: @@ -21,4 +21,18 @@ generate: --use-schema-description \ --target-python-version 3.13 \ --use-annotated \ - --openapi-scopes schemas + --openapi-scopes schemas \ + --formatters ruff-format ruff-check \ + --input-file-type openapi + +lint: + uv run ruff check src/ + uv run ruff format --check src/ + +test: + uv run pytest tests/test_client.py -v + +test-integration: + uv run pytest tests/ -v -m "integration or not integration" + +check: lint test diff --git a/README.md b/README.md index 2c39d93..787a4b9 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,623 @@ -# python-sdk +# Wrenn Python SDK -Python SDK for wrenn \ No newline at end of file +Python client for the [Wrenn](https://wrenn.dev) microVM platform. Create isolated capsules, execute commands, manage files, run interactive terminals, and execute persistent code -- all from Python. + +Designed as a drop-in replacement for [e2b](https://e2b.dev). If you're migrating, just swap your imports. + +## Installation + +```bash +pip install wrenn +``` + +Requires Python 3.13+. + +## Authentication + +Set the `WRENN_API_KEY` environment variable: + +```bash +export WRENN_API_KEY="wrn_your_api_key_here" +``` + +Optionally override the API base URL: + +```bash +export WRENN_BASE_URL="https://app.wrenn.dev/api" # default +``` + +You can also pass credentials directly: + +```python +from wrenn import Capsule + +capsule = Capsule(api_key="wrn_...", base_url="https://...") +``` + +--- + +## Wrenn Capsules + +### Quick Start + +```python +from wrenn import Capsule + +# Create a capsule (reads WRENN_API_KEY from env) +with Capsule(template="minimal") as capsule: + result = capsule.commands.run("echo hello") + print(result.stdout) # "hello\n" +``` + +### Creating Capsules + +```python +from wrenn import Capsule + +# Direct construction (creates immediately) +capsule = Capsule() +capsule = Capsule(template="base-python", vcpus=2, memory_mb=1024, timeout=300) + +# With auto-wait (blocks until capsule is running) +capsule = Capsule(template="minimal", wait=True) + +# Via factory classmethod +capsule = Capsule.create(template="minimal", wait=True) +``` + +### Context Manager + +Use capsules as context managers for automatic cleanup (destroys capsule on exit): + +```python +with Capsule(template="minimal", wait=True) as capsule: + capsule.commands.run("echo hello") +# capsule is automatically destroyed +``` + +### Connecting to Existing Capsules + +Attach to a running capsule by ID. If it's paused, it will be resumed automatically: + +```python +capsule = Capsule.connect("cl-abc123") +result = capsule.commands.run("echo still running") +``` + +For code interpreter capsules: + +```python +from wrenn.code_interpreter import Capsule as CodeCapsule + +capsule = CodeCapsule.connect("cl-abc123") +result = capsule.run_code("print('reconnected')") +``` + +### Lifecycle Management + +```python +# Instance methods +capsule.pause() +capsule.resume() +capsule.destroy() +capsule.ping() # reset inactivity timer +capsule.wait_ready() # block until running + +info = capsule.get_info() +print(info.status) # "running" +print(capsule.is_running()) # True + +# Static methods (no instance needed) +Capsule.destroy("cl-abc123", api_key="wrn_...") +Capsule.pause("cl-abc123") +Capsule.resume("cl-abc123") +info = Capsule.get_info("cl-abc123") + +# List all capsules +capsules = Capsule.list() +``` + +### Command Execution + +Commands are accessed via `capsule.commands`: + +```python +# Foreground (blocks until complete) +result = capsule.commands.run("python -c 'print(42)'") +print(result.stdout) # "42\n" +print(result.stderr) # "" +print(result.exit_code) # 0 +print(result.duration_ms) # 35 + +# With options +result = capsule.commands.run( + "python train.py", + timeout=120, + envs={"CUDA_VISIBLE_DEVICES": "0"}, + cwd="/app", +) + +# Background process +handle = capsule.commands.run("python server.py", background=True) +print(handle.pid) # 1234 +print(handle.tag) # "exec-abc123" +``` + +#### Streaming Output + +```python +import sys + +# Stream a new command +for event in capsule.commands.stream("python", args=["-u", "train.py"]): + match event.type: + case "stdout": + print(event.data, end="") + case "stderr": + print(event.data, end="", file=sys.stderr) + case "exit": + print(f"\nExited with code {event.exit_code}") + +# Connect to a running background process +for event in capsule.commands.connect(handle.pid): + if event.type == "stdout": + print(event.data, end="") +``` + +#### Process Management + +```python +# List running processes +for proc in capsule.commands.list(): + print(proc.pid, proc.cmd, proc.tag) + +# Kill a process +capsule.commands.kill(pid=1234) +``` + +### Filesystem + +Files are accessed via `capsule.files`: + +```python +# Write and read files +capsule.files.write("/app/main.py", "print('hello')") +content = capsule.files.read("/app/main.py") # str +raw = capsule.files.read_bytes("/app/main.py") # bytes + +# Check existence +capsule.files.exists("/app/main.py") # True + +# List directory +entries = capsule.files.list("/home/user", depth=1) +for entry in entries: + print(entry.name, entry.type, entry.size) + +# Create directory +capsule.files.make_dir("/app/data") + +# Remove file or directory +capsule.files.remove("/app/old_data") +``` + +#### Streaming (Large Files) + +```python +# Streaming upload +def chunks(): + yield b"chunk1" + yield b"chunk2" + +capsule.files.upload_stream("/data/large.bin", chunks()) + +# Streaming download +for chunk in capsule.files.download_stream("/data/large.bin"): + process(chunk) +``` + +### Git + +Git operations are accessed via `capsule.git`. All commands execute the real `git` binary inside the capsule: + +```python +# Initialize a repo +capsule.git.init("/app", initial_branch="main") + +# Configure user +capsule.git.configure_user("Alice", "alice@example.com", cwd="/app") + +# Stage and commit +capsule.git.add(all=True, cwd="/app") +capsule.git.commit("initial commit", cwd="/app") + +# Check status +status = capsule.git.status(cwd="/app") +print(status.branch) # "main" +print(status.is_clean) # True +for f in status.files: + print(f.path, f.index_status, f.work_tree_status) + +# Branches +branches = capsule.git.branches(cwd="/app") +capsule.git.create_branch("feature", cwd="/app") +capsule.git.checkout_branch("main", cwd="/app") +capsule.git.delete_branch("feature", cwd="/app") +``` + +#### Clone with Authentication + +```python +# Clone a private repo (credentials are stripped from remote URL after clone) +capsule.git.clone( + "https://github.com/org/repo.git", + username="user", + password="ghp_token", + cwd="/app", +) + +# Push/pull with inline credentials (temporarily embedded, then restored) +capsule.git.push("origin", "main", username="user", password="ghp_token", cwd="/app") +capsule.git.pull("origin", "main", username="user", password="ghp_token", cwd="/app") +``` + +#### Configuration and Remotes + +```python +capsule.git.set_config("core.autocrlf", "false", cwd="/app") +value = capsule.git.get_config("user.name", cwd="/app") # str | None + +capsule.git.remote_add("upstream", "https://github.com/org/repo.git", cwd="/app") +url = capsule.git.remote_get("origin", cwd="/app") # str | None +``` + +Git errors raise `GitCommandError` (or `GitAuthError` for authentication failures), both inheriting from `GitError`: + +```python +from wrenn import GitCommandError, GitAuthError + +try: + capsule.git.push("origin", "main", username="user", password="bad", cwd="/app") +except GitAuthError as e: + print(e.stderr) + print(e.exit_code) +``` + +### Interactive Terminal (PTY) + +```python +import sys + +with capsule.pty(cmd="/bin/bash", cols=120, rows=40, cwd="/home/user") as term: + term.write(b"ls -la\n") + for event in term: + if event.type == "output": + sys.stdout.buffer.write(event.data) + elif event.type == "exit": + break + +# Reconnect to an existing session +with capsule.pty_connect(term.tag) as term: + term.write(b"echo reconnected\n") +``` + +**PtySession methods:** + +| Method | Description | +|--------|-------------| +| `write(data: bytes)` | Send raw bytes to stdin | +| `resize(cols, rows)` | Resize the terminal | +| `kill()` | Send SIGKILL to the process | +| `tag` | Session tag (after `started` event) | +| `pid` | Process PID (after `started` event) | + +### Proxy URL + +Access services running inside a capsule: + +```python +url = capsule.get_url(8080) +# "wss://8080-cl-abc123.app.wrenn.dev" +``` + +### Snapshots + +Create reusable templates from running capsules: + +```python +template = capsule.create_snapshot(name="my-template", overwrite=True) +``` + +--- + +## Code Interpreter + +The `wrenn.code_interpreter` module provides a specialized capsule for stateful code execution via a persistent Jupyter kernel. + +### Quick Start + +```python +from wrenn.code_interpreter import Capsule + +with Capsule(wait=True) as capsule: + result = capsule.run_code("print('hello')") + print("".join(result.logs.stdout)) # "hello\n" +``` + +### Stateful Execution + +Variables, imports, and function definitions persist across `run_code` calls: + +```python +from wrenn.code_interpreter import Capsule + +with Capsule(wait=True) as capsule: + capsule.run_code("x = 42") + result = capsule.run_code("x * 2") + print(result.text) # "84" + + capsule.run_code("import math") + result = capsule.run_code("math.pi") + print(result.text) # "3.141592653589793" + + capsule.run_code("def greet(name): return f'hello {name}'") + result = capsule.run_code("greet('world')") + print(result.text) # "hello world" +``` + +The `text` property returns the `text/plain` value of the main `execute_result` (the last expression in the cell). Printed output goes to `result.logs.stdout` instead. + +### Error Handling in Code + +```python +result = capsule.run_code("1 / 0") +print(result.error.name) # "ZeroDivisionError" +print(result.error.value) # "division by zero" +print(result.error.traceback) # full traceback string +``` + +### Rich Output + +Each call to `display()`, `plt.show()`, or similar produces a `Result` in `execution.results`. Known MIME types are unpacked into named fields: + +```python +result = capsule.run_code(""" +import matplotlib.pyplot as plt +plt.plot([1, 2, 3]) +plt.show() +""") +for r in result.results: + if r.png: + print(f"Got PNG image ({len(r.png)} bytes base64)") + print(r.formats()) # e.g. ["text", "png"] +``` + +### Streaming Callbacks + +```python +capsule.run_code( + code, + on_result=lambda r: print("result:", r.formats()), + on_stdout=lambda text: print("stdout:", text), + on_stderr=lambda text: print("stderr:", text), + on_error=lambda err: print(f"error: {err.name}: {err.value}"), +) +``` + +### Custom Templates + +By default, `code-runner-beta` template is used. You can specify a custom template: + +```python +capsule = Capsule(template="my-custom-jupyter-template", wait=True) +result = capsule.run_code("print('running on custom template')") +``` + +### Execution Model + +`run_code()` returns an `Execution` object: + +| Field | Type | Description | +|-------|------|-------------| +| `results` | `list[Result]` | All rich outputs (charts, images, expression values) | +| `logs` | `Logs` | `.stdout: list[str]` and `.stderr: list[str]` chunks | +| `error` | `ExecutionError \| None` | `.name`, `.value`, `.traceback` | +| `execution_count` | `int \| None` | Jupyter cell execution counter | +| `text` | `str \| None` | (property) `text/plain` of the main `execute_result` | + +Each `Result` has typed MIME fields: `text`, `html`, `markdown`, `svg`, `png`, `jpeg`, `pdf`, `latex`, `json`, `javascript`, plus `extra` for unknown types. String expression results have quotes stripped automatically. + +### Code Interpreter + Commands/Files + +The code interpreter capsule inherits all standard capsule features: + +```python +from wrenn.code_interpreter import Capsule + +with Capsule(wait=True) as capsule: + # Use run_code for Jupyter execution + capsule.run_code("import pandas as pd; df = pd.DataFrame({'a': [1,2,3]})") + capsule.run_code("df.to_csv('/tmp/data.csv', index=False)") + + # Use standard file operations + content = capsule.files.read("/tmp/data.csv") + print(content) + + # Use standard command execution + result = capsule.commands.run("wc -l /tmp/data.csv") + print(result.stdout) +``` + +--- + +## Async Support + +All operations have async variants via `AsyncCapsule`: + +### Async Capsule + +```python +from wrenn import AsyncCapsule + +async with await AsyncCapsule.create(template="minimal", wait=True) as capsule: + result = await capsule.commands.run("echo hello") + print(result.stdout) + + await capsule.files.write("/app/file.txt", "data") + entries = await capsule.files.list("/app") + + await capsule.pause() + await capsule.resume() +``` + +### Async Code Interpreter + +```python +from wrenn.code_interpreter import AsyncCapsule + +async with await AsyncCapsule.create(wait=True) as capsule: + result = await capsule.run_code("2 + 2") + print(result.text) # "4" +``` + +### Async PTY + +```python +async with capsule.pty(cmd="/bin/bash") as term: + await term.write(b"ls -la\n") + async for event in term: + if event.type == "output": + sys.stdout.buffer.write(event.data) +``` + +--- + +## Error Handling + +The SDK maps server error codes to typed exceptions: + +```python +from wrenn import ( + WrennError, + WrennValidationError, # 400 + WrennAuthenticationError, # 401 + WrennForbiddenError, # 403 + WrennNotFoundError, # 404 + WrennConflictError, # 409 + WrennHostHasCapsulesError, # 409 (host has running capsules) + WrennAgentError, # 502 + WrennInternalError, # 500 + WrennHostUnavailableError, # 503 +) + +try: + Capsule.get_info("nonexistent") +except WrennNotFoundError as e: + print(e.code) # "not_found" + print(e.message) # "capsule not found" + print(e.status_code) # 404 +``` + +All exceptions inherit from `WrennError` and expose `.code`, `.message`, and `.status_code`. + +--- + +## Migrating from e2b + +Replace your imports: + +```python +# Before +from e2b import Sandbox +sandbox = Sandbox() + +# After +from wrenn import Capsule +capsule = Capsule() +``` + +For code interpreter: + +```python +# Before +from e2b_code_interpreter import Sandbox +sandbox = Sandbox() +result = sandbox.run_code("print('hello')") + +# After +from wrenn.code_interpreter import Capsule +capsule = Capsule() +result = capsule.run_code("print('hello')") +``` + +The `Sandbox` name is available as a deprecated alias in both modules: + +```python +from wrenn import Sandbox # works, emits FutureWarning +from wrenn.code_interpreter import Sandbox # works, emits FutureWarning +``` + +--- + +## Low-Level Client + +For direct API access, use `WrennClient` / `AsyncWrennClient`: + +```python +from wrenn import WrennClient + +with WrennClient(api_key="wrn_...") as client: + capsule = client.capsules.create(template="minimal") + client.capsules.pause(capsule.id) + client.capsules.resume(capsule.id) + client.capsules.ping(capsule.id) + client.capsules.destroy(capsule.id) + + # Snapshots + template = client.snapshots.create(capsule_id="cl-abc", name="my-snap") + templates = client.snapshots.list() + client.snapshots.delete("my-snap") +``` + +--- + +## Development + +This project uses [uv](https://docs.astral.sh/uv/) for dependency management. + +```bash +# Install dependencies +uv sync + +# Run linting +make lint + +# Run unit tests +make test + +# Run all tests (including integration) +make test-integration +``` + +### Running Integration Tests + +Integration tests require a live Wrenn server. Set credentials via environment or a `.env` file at the project root: + +```bash +# Option 1: environment variable +export WRENN_API_KEY="wrn_..." + +# Option 2: .env file +echo 'WRENN_API_KEY=wrn_...' > .env +``` + +Then run: + +```bash +make test-integration +``` + +Tests are automatically skipped when `WRENN_API_KEY` is not available. + +## License + +MIT diff --git a/api/openapi.yaml b/api/openapi.yaml index f4c8f66..8d3861c 100644 --- a/api/openapi.yaml +++ b/api/openapi.yaml @@ -1,8 +1,8 @@ openapi: "3.1.0" info: - title: Wrenn Sandbox API + title: Wrenn API description: MicroVM-based code execution platform API. - version: "0.1.0" + version: "0.1.3" servers: - url: http://localhost:8080 @@ -16,6 +16,10 @@ paths: summary: Create a new account operationId: signup tags: [auth] + description: | + Creates an inactive user account and sends an activation email. + The user must activate their account within 30 minutes. + Does not return a JWT — the user must activate first, then sign in. requestBody: required: true content: @@ -24,11 +28,11 @@ paths: $ref: "#/components/schemas/SignupRequest" responses: "201": - description: Account created + description: Account created, activation email sent content: application/json: schema: - $ref: "#/components/schemas/AuthResponse" + $ref: "#/components/schemas/SignupResponse" "400": description: Invalid request (bad email, short password) content: @@ -36,7 +40,80 @@ paths: schema: $ref: "#/components/schemas/Error" "409": - description: Email already registered + description: Email already registered or signup cooldown active + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + + /v1/auth/activate: + post: + summary: Activate account via email token + operationId: activate + tags: [auth] + description: | + Consumes the activation token sent via email and activates the user account. + Creates a default team and returns a JWT to log the user in. + requestBody: + required: true + content: + application/json: + schema: + type: object + required: [token] + properties: + token: + type: string + responses: + "200": + description: Account activated, JWT issued + content: + application/json: + schema: + $ref: "#/components/schemas/AuthResponse" + "400": + description: Invalid or expired token + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + + /v1/auth/switch-team: + post: + summary: Switch active team + operationId: switchTeam + tags: [auth] + security: + - bearerAuth: [] + description: | + Re-issues a JWT scoped to a different team. The user must be a member of + the target team (verified from DB). Use the returned token for subsequent + requests to that team's resources. + requestBody: + required: true + content: + application/json: + schema: + type: object + required: [team_id] + properties: + team_id: + type: string + responses: + "200": + description: New JWT issued for the target team + content: + application/json: + schema: + $ref: "#/components/schemas/AuthResponse" + "403": + description: Not a member of this team + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + "404": + description: Team not found content: application/json: schema: @@ -134,6 +211,252 @@ paths: "302": description: Redirect to frontend with token or error + /v1/me: + get: + summary: Get current user profile + operationId: getMe + tags: [account] + security: + - bearerAuth: [] + responses: + "200": + description: User profile + content: + application/json: + schema: + $ref: "#/components/schemas/MeResponse" + + patch: + summary: Update display name + operationId: updateName + tags: [account] + security: + - bearerAuth: [] + requestBody: + required: true + content: + application/json: + schema: + type: object + required: [name] + properties: + name: + type: string + minLength: 1 + maxLength: 100 + responses: + "200": + description: Name updated, new JWT issued + content: + application/json: + schema: + $ref: "#/components/schemas/AuthResponse" + "400": + description: Invalid name + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + + delete: + summary: Delete current account + operationId: deleteAccount + tags: [account] + security: + - bearerAuth: [] + description: | + Soft-deletes the account (sets status=deleted, deleted_at=now). + The account is permanently removed after 15 days. Blocked if the user + owns any team that has other members. + requestBody: + required: true + content: + application/json: + schema: + type: object + required: [confirmation] + properties: + confirmation: + type: string + description: Must match the user's email address (case-insensitive) + responses: + "204": + description: Account scheduled for deletion + "400": + description: Confirmation does not match email + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + "409": + description: User owns teams with other members + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + + /v1/me/password: + post: + summary: Change or add password + operationId: changePassword + tags: [account] + security: + - bearerAuth: [] + description: | + For users with an existing password: requires `current_password` and `new_password`. + For OAuth-only users adding a password: requires `new_password` and `confirm_password`. + requestBody: + required: true + content: + application/json: + schema: + $ref: "#/components/schemas/ChangePasswordRequest" + responses: + "204": + description: Password updated + "400": + description: Invalid request (short password, mismatch, etc.) + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + "401": + description: Current password is incorrect + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + + /v1/me/password/reset: + post: + summary: Request a password reset email + operationId: requestPasswordReset + tags: [account] + description: | + Sends a password reset link to the given email. Always returns 200 + regardless of whether the email exists, to prevent account enumeration. + The reset token expires in 15 minutes. + requestBody: + required: true + content: + application/json: + schema: + type: object + required: [email] + properties: + email: + type: string + format: email + responses: + "204": + description: Request accepted (email sent if account exists) + + /v1/me/password/reset/confirm: + post: + summary: Confirm password reset + operationId: confirmPasswordReset + tags: [account] + description: | + Consumes a password reset token and sets a new password. The token is + single-use and expires after 15 minutes. + requestBody: + required: true + content: + application/json: + schema: + type: object + required: [token, new_password] + properties: + token: + type: string + description: Raw reset token from the email link + new_password: + type: string + minLength: 8 + responses: + "204": + description: Password reset successful + "400": + description: Invalid or expired token, or password too short + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + + /v1/me/providers/{provider}/connect: + parameters: + - name: provider + in: path + required: true + schema: + type: string + enum: [github] + description: OAuth provider name + + get: + summary: Initiate OAuth provider link + operationId: connectProvider + tags: [account] + security: + - bearerAuth: [] + description: | + Sets OAuth state and link cookies, then returns the provider's + authorization URL. The frontend navigates to this URL to start the + OAuth flow. On callback, the provider is linked to the current account + (not a new registration). + responses: + "200": + description: Authorization URL + content: + application/json: + schema: + type: object + properties: + auth_url: + type: string + format: uri + "404": + description: Provider not found or not configured + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + + /v1/me/providers/{provider}: + parameters: + - name: provider + in: path + required: true + schema: + type: string + enum: [github] + description: OAuth provider name + + delete: + summary: Disconnect an OAuth provider + operationId: disconnectProvider + tags: [account] + security: + - bearerAuth: [] + description: | + Unlinks the OAuth provider from the current account. Blocked if this + is the user's only login method (no password and no other providers). + responses: + "204": + description: Provider disconnected + "400": + description: Cannot disconnect last login method + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + "404": + description: Provider not connected + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + /v1/api-keys: post: summary: Create an API key @@ -195,50 +518,175 @@ paths: "204": description: API key deleted - /v1/sandboxes: - post: - summary: Create a sandbox - operationId: createSandbox - tags: [sandboxes] - security: - - apiKeyAuth: [] - requestBody: - required: true - content: - application/json: - schema: - $ref: "#/components/schemas/CreateSandboxRequest" - responses: - "201": - description: Sandbox created - content: - application/json: - schema: - $ref: "#/components/schemas/Sandbox" - "502": - description: Host agent error - content: - application/json: - schema: - $ref: "#/components/schemas/Error" - + /v1/users/search: get: - summary: List sandboxes for your team - operationId: listSandboxes - tags: [sandboxes] + summary: Search users by email prefix + operationId: searchUsers + tags: [users] security: - - apiKeyAuth: [] + - bearerAuth: [] + description: | + Returns up to 10 users whose email starts with the given prefix. + The prefix must contain "@". Intended for the add-member UI autocomplete. + parameters: + - name: email + in: query + required: true + schema: + type: string + description: Email prefix (must contain "@", e.g. "alice@") responses: "200": - description: List of sandboxes + description: Matching users content: application/json: schema: type: array items: - $ref: "#/components/schemas/Sandbox" + $ref: "#/components/schemas/UserSearchResult" + "400": + description: Prefix does not contain "@" + content: + application/json: + schema: + $ref: "#/components/schemas/Error" - /v1/sandboxes/{id}: + /v1/teams: + get: + summary: List teams for the authenticated user + operationId: listTeams + tags: [teams] + security: + - bearerAuth: [] + responses: + "200": + description: Teams the user belongs to, each with their role + content: + application/json: + schema: + type: array + items: + $ref: "#/components/schemas/TeamWithRole" + + post: + summary: Create a new team + operationId: createTeam + tags: [teams] + security: + - bearerAuth: [] + requestBody: + required: true + content: + application/json: + schema: + type: object + required: [name] + properties: + name: + type: string + description: 1-128 chars; A-Z a-z 0-9 space _ + responses: + "201": + description: Team created (caller is owner) + content: + application/json: + schema: + $ref: "#/components/schemas/TeamWithRole" + "400": + description: Invalid team name + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + + /v1/teams/{id}: + parameters: + - name: id + in: path + required: true + schema: + type: string + description: Team ID (must match the JWT's team_id) + + get: + summary: Get team info and member list + operationId: getTeam + tags: [teams] + security: + - bearerAuth: [] + responses: + "200": + description: Team details with members + content: + application/json: + schema: + $ref: "#/components/schemas/TeamDetail" + "403": + description: JWT team does not match requested team + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + "404": + description: Team not found + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + + patch: + summary: Rename the team + operationId: renameTeam + tags: [teams] + security: + - bearerAuth: [] + description: Admin or owner role required (verified from DB). + requestBody: + required: true + content: + application/json: + schema: + type: object + required: [name] + properties: + name: + type: string + responses: + "204": + description: Renamed + "400": + description: Invalid team name + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + "403": + description: Insufficient role + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + + delete: + summary: Delete the team + operationId: deleteTeam + tags: [teams] + security: + - bearerAuth: [] + description: | + Owner only. Soft-deletes the team and destroys all running/paused/starting + capsulees. All DB records are preserved. The team slug is permanently reserved. + responses: + "204": + description: Team deleted + "403": + description: Caller is not the owner + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + + /v1/teams/{id}/members: parameters: - name: id in: path @@ -247,36 +695,303 @@ paths: type: string get: - summary: Get sandbox details - operationId: getSandbox - tags: [sandboxes] + summary: List team members + operationId: listTeamMembers + tags: [teams] security: - - apiKeyAuth: [] + - bearerAuth: [] responses: "200": - description: Sandbox details + description: Members with roles content: application/json: schema: - $ref: "#/components/schemas/Sandbox" + type: array + items: + $ref: "#/components/schemas/TeamMember" + + post: + summary: Add a member by email + operationId: addTeamMember + tags: [teams] + security: + - bearerAuth: [] + description: Admin or owner role required. User is added instantly as a member. + requestBody: + required: true + content: + application/json: + schema: + type: object + required: [email] + properties: + email: + type: string + format: email + responses: + "201": + description: Member added + content: + application/json: + schema: + $ref: "#/components/schemas/TeamMember" + "403": + description: Insufficient role + content: + application/json: + schema: + $ref: "#/components/schemas/Error" "404": - description: Sandbox not found + description: No account with that email + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + "400": + description: User is already a member + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + + /v1/teams/{id}/members/{uid}: + parameters: + - name: id + in: path + required: true + schema: + type: string + - name: uid + in: path + required: true + schema: + type: string + description: Target user ID + + patch: + summary: Update member role + operationId: updateMemberRole + tags: [teams] + security: + - bearerAuth: [] + description: | + Admin or owner required. Valid target roles: admin, member. + The owner's role cannot be changed. + requestBody: + required: true + content: + application/json: + schema: + type: object + required: [role] + properties: + role: + type: string + enum: [admin, member] + responses: + "204": + description: Role updated + "403": + description: Insufficient role or attempt to modify owner + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + "404": + description: User is not a member content: application/json: schema: $ref: "#/components/schemas/Error" delete: - summary: Destroy a sandbox - operationId: destroySandbox - tags: [sandboxes] + summary: Remove a member + operationId: removeTeamMember + tags: [teams] + security: + - bearerAuth: [] + description: Admin or owner required. Owner cannot be removed. + responses: + "204": + description: Member removed + "403": + description: Insufficient role or attempt to remove owner + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + "404": + description: User is not a member + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + + /v1/teams/{id}/leave: + parameters: + - name: id + in: path + required: true + schema: + type: string + + post: + summary: Leave the team + operationId: leaveTeam + tags: [teams] + security: + - bearerAuth: [] + description: The owner cannot leave; they must delete the team instead. + responses: + "204": + description: Left the team + "403": + description: Owner cannot leave + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + + /v1/capsules: + post: + summary: Create a capsule + operationId: createCapsule + tags: [capsules] + security: + - apiKeyAuth: [] + requestBody: + required: true + content: + application/json: + schema: + $ref: "#/components/schemas/CreateCapsuleRequest" + responses: + "201": + description: Capsule created + content: + application/json: + schema: + $ref: "#/components/schemas/Capsule" + "502": + description: Host agent error + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + + get: + summary: List capsulees for your team + operationId: listCapsules + tags: [capsules] + security: + - apiKeyAuth: [] + responses: + "200": + description: List of capsulees + content: + application/json: + schema: + type: array + items: + $ref: "#/components/schemas/Capsule" + + /v1/capsules/stats: + get: + summary: Get capsule usage stats for your team + operationId: getCapsuleStats + tags: [capsules] + security: + - apiKeyAuth: [] + parameters: + - name: range + in: query + required: false + schema: + type: string + enum: [5m, 1h, 6h, 24h, 30d] + default: 1h + description: Time window for the time-series data. + responses: + "200": + description: Capsule stats for the team + content: + application/json: + schema: + $ref: "#/components/schemas/CapsuleStats" + "400": + $ref: "#/components/responses/BadRequest" + + /v1/capsules/usage: + get: + summary: Get daily CPU and RAM usage for your team + operationId: getCapsuleUsage + tags: [capsules] + security: + - apiKeyAuth: [] + parameters: + - name: from + in: query + required: false + schema: + type: string + format: date + description: Start date (YYYY-MM-DD). Defaults to 30 days ago. + - name: to + in: query + required: false + schema: + type: string + format: date + description: End date (YYYY-MM-DD). Defaults to today. + responses: + "200": + description: Daily usage data for the team + content: + application/json: + schema: + $ref: "#/components/schemas/UsageResponse" + "400": + $ref: "#/components/responses/BadRequest" + + /v1/capsules/{id}: + parameters: + - name: id + in: path + required: true + schema: + type: string + + get: + summary: Get capsule details + operationId: getCapsule + tags: [capsules] + security: + - apiKeyAuth: [] + responses: + "200": + description: Capsule details + content: + application/json: + schema: + $ref: "#/components/schemas/Capsule" + "404": + description: Capsule not found + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + + delete: + summary: Destroy a capsule + operationId: destroyCapsule + tags: [capsules] security: - apiKeyAuth: [] responses: "204": - description: Sandbox destroyed + description: Capsule destroyed - /v1/sandboxes/{id}/exec: + /v1/capsules/{id}/exec: parameters: - name: id in: path @@ -287,7 +1002,7 @@ paths: post: summary: Execute a command operationId: execCommand - tags: [sandboxes] + tags: [capsules] security: - apiKeyAuth: [] requestBody: @@ -298,25 +1013,147 @@ paths: $ref: "#/components/schemas/ExecRequest" responses: "200": - description: Command output + description: Command output (foreground exec) content: application/json: schema: $ref: "#/components/schemas/ExecResponse" + "202": + description: Background process started + content: + application/json: + schema: + $ref: "#/components/schemas/BackgroundExecResponse" "404": - description: Sandbox not found + description: Capsule not found content: application/json: schema: $ref: "#/components/schemas/Error" "409": - description: Sandbox not running + description: Capsule not running content: application/json: schema: $ref: "#/components/schemas/Error" - /v1/sandboxes/{id}/ping: + /v1/capsules/{id}/processes: + parameters: + - name: id + in: path + required: true + schema: + type: string + + get: + summary: List running processes + operationId: listProcesses + tags: [capsules] + security: + - apiKeyAuth: [] + description: | + Returns all running processes inside the capsule, including background + processes and any processes started by templates or init scripts. + responses: + "200": + description: Process list + content: + application/json: + schema: + $ref: "#/components/schemas/ProcessListResponse" + "404": + description: Capsule not found + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + "409": + description: Capsule not running + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + + /v1/capsules/{id}/processes/{selector}: + parameters: + - name: id + in: path + required: true + schema: + type: string + - name: selector + in: path + required: true + description: Process PID (numeric) or tag (string) + schema: + type: string + + delete: + summary: Kill a process + operationId: killProcess + tags: [capsules] + security: + - apiKeyAuth: [] + parameters: + - name: signal + in: query + required: false + description: Signal to send (SIGKILL or SIGTERM, default SIGKILL) + schema: + type: string + enum: [SIGKILL, SIGTERM] + default: SIGKILL + responses: + "204": + description: Process killed + "404": + description: Capsule or process not found + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + "409": + description: Capsule not running + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + + /v1/capsules/{id}/processes/{selector}/stream: + parameters: + - name: id + in: path + required: true + schema: + type: string + - name: selector + in: path + required: true + description: Process PID (numeric) or tag (string) + schema: + type: string + + get: + summary: Stream process output via WebSocket + operationId: connectProcess + tags: [capsules] + security: + - apiKeyAuth: [] + description: | + Opens a WebSocket connection to stream stdout/stderr from a running + background process. The selector can be a numeric PID or a string tag. + + Server sends JSON messages: + - `{"type": "start", "pid": 42}` — connected to process + - `{"type": "stdout", "data": "..."}` — stdout output + - `{"type": "stderr", "data": "..."}` — stderr output + - `{"type": "exit", "exit_code": 0}` — process exited + - `{"type": "error", "data": "..."}` — error message + responses: + "101": + description: WebSocket upgrade + + /v1/capsules/{id}/ping: parameters: - name: id in: path @@ -325,32 +1162,86 @@ paths: type: string post: - summary: Reset sandbox inactivity timer - operationId: pingSandbox - tags: [sandboxes] + summary: Reset capsule inactivity timer + operationId: pingCapsule + tags: [capsules] security: - apiKeyAuth: [] description: | - Resets the last_active_at timestamp for a running sandbox, preventing - the auto-pause TTL from expiring. Use this as a keepalive for sandboxes + Resets the last_active_at timestamp for a running capsule, preventing + the auto-pause TTL from expiring. Use this as a keepalive for capsulees that are idle but should remain running. responses: "204": description: Ping acknowledged, inactivity timer reset "404": - description: Sandbox not found + description: Capsule not found content: application/json: schema: $ref: "#/components/schemas/Error" "409": - description: Sandbox not running + description: Capsule not running content: application/json: schema: $ref: "#/components/schemas/Error" - /v1/sandboxes/{id}/pause: + /v1/capsules/{id}/metrics: + parameters: + - name: id + in: path + required: true + schema: + type: string + + get: + summary: Get per-capsule resource metrics + operationId: getCapsuleMetrics + tags: [capsules] + security: + - apiKeyAuth: [] + - bearerAuth: [] + description: | + Returns time-series CPU, memory, and disk metrics for a capsule. + Three tiers are available with different granularity and retention: + - `10m`: 500ms samples, last 10 minutes + - `2h`: 30-second averages, last 2 hours + - `24h`: 5-minute averages, last 24 hours + + For running capsulees, data comes from the host agent's in-memory + ring buffer. For paused capsulees, data is read from persisted + snapshots in the database. Stopped/destroyed capsulees return 404. + parameters: + - name: range + in: query + required: false + schema: + type: string + enum: ["5m", "10m", "1h", "2h", "6h", "12h", "24h"] + default: "10m" + description: Time range filter to query + responses: + "200": + description: Metrics retrieved + content: + application/json: + schema: + $ref: "#/components/schemas/CapsuleMetrics" + "400": + description: Invalid range parameter + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + "404": + description: Capsule not found or metrics not available + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + + /v1/capsules/{id}/pause: parameters: - name: id in: path @@ -359,30 +1250,30 @@ paths: type: string post: - summary: Pause a running sandbox - operationId: pauseSandbox - tags: [sandboxes] + summary: Pause a running capsule + operationId: pauseCapsule + tags: [capsules] security: - apiKeyAuth: [] description: | - Takes a snapshot of the sandbox (VM state + memory + rootfs), then - destroys all running resources. The sandbox exists only as files on + Takes a snapshot of the capsule (VM state + memory + rootfs), then + destroys all running resources. The capsule exists only as files on disk and can be resumed later. responses: "200": - description: Sandbox paused (snapshot taken, resources released) + description: Capsule paused (snapshot taken, resources released) content: application/json: schema: - $ref: "#/components/schemas/Sandbox" + $ref: "#/components/schemas/Capsule" "409": - description: Sandbox not running + description: Capsule not running content: application/json: schema: $ref: "#/components/schemas/Error" - /v1/sandboxes/{id}/resume: + /v1/capsules/{id}/resume: parameters: - name: id in: path @@ -391,24 +1282,24 @@ paths: type: string post: - summary: Resume a paused sandbox - operationId: resumeSandbox - tags: [sandboxes] + summary: Resume a paused capsule + operationId: resumeCapsule + tags: [capsules] security: - apiKeyAuth: [] description: | - Restores a paused sandbox from its snapshot using UFFD for lazy + Restores a paused capsule from its snapshot using UFFD for lazy memory loading. Boots a fresh Firecracker process, sets up a new network slot, and waits for envd to become ready. responses: "200": - description: Sandbox resumed (new VM booted from snapshot) + description: Capsule resumed (new VM booted from snapshot) content: application/json: schema: - $ref: "#/components/schemas/Sandbox" + $ref: "#/components/schemas/Capsule" "409": - description: Sandbox not paused + description: Capsule not paused content: application/json: schema: @@ -422,9 +1313,9 @@ paths: security: - apiKeyAuth: [] description: | - Pauses a running sandbox, takes a full snapshot, copies the snapshot + Pauses a running capsule, takes a full snapshot, copies the snapshot files to the images directory as a reusable template, then destroys - the sandbox. The template can be used to create new sandboxes. + the capsule. The template can be used to create new capsulees. parameters: - name: overwrite in: query @@ -447,7 +1338,7 @@ paths: schema: $ref: "#/components/schemas/Template" "409": - description: Name already exists or sandbox not running + description: Name already exists or capsule not running content: application/json: schema: @@ -502,7 +1393,7 @@ paths: schema: $ref: "#/components/schemas/Error" - /v1/sandboxes/{id}/files/write: + /v1/capsules/{id}/files/write: parameters: - name: id in: path @@ -513,7 +1404,7 @@ paths: post: summary: Upload a file operationId: uploadFile - tags: [sandboxes] + tags: [capsules] security: - apiKeyAuth: [] requestBody: @@ -526,7 +1417,7 @@ paths: properties: path: type: string - description: Absolute destination path inside the sandbox + description: Absolute destination path inside the capsule file: type: string format: binary @@ -535,7 +1426,7 @@ paths: "204": description: File uploaded "409": - description: Sandbox not running + description: Capsule not running content: application/json: schema: @@ -547,7 +1438,7 @@ paths: schema: $ref: "#/components/schemas/Error" - /v1/sandboxes/{id}/files/read: + /v1/capsules/{id}/files/read: parameters: - name: id in: path @@ -558,7 +1449,7 @@ paths: post: summary: Download a file operationId: downloadFile - tags: [sandboxes] + tags: [capsules] security: - apiKeyAuth: [] requestBody: @@ -576,13 +1467,129 @@ paths: type: string format: binary "404": - description: Sandbox or file not found + description: Capsule or file not found content: application/json: schema: $ref: "#/components/schemas/Error" - /v1/sandboxes/{id}/exec/stream: + /v1/capsules/{id}/files/list: + parameters: + - name: id + in: path + required: true + schema: + type: string + + post: + summary: List directory contents + operationId: listDir + tags: [capsules] + security: + - apiKeyAuth: [] + requestBody: + required: true + content: + application/json: + schema: + $ref: "#/components/schemas/ListDirRequest" + responses: + "200": + description: Directory listing + content: + application/json: + schema: + $ref: "#/components/schemas/ListDirResponse" + "404": + description: Capsule not found + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + "409": + description: Capsule not running + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + + /v1/capsules/{id}/files/mkdir: + parameters: + - name: id + in: path + required: true + schema: + type: string + + post: + summary: Create a directory + operationId: makeDir + tags: [capsules] + security: + - apiKeyAuth: [] + requestBody: + required: true + content: + application/json: + schema: + $ref: "#/components/schemas/MakeDirRequest" + responses: + "200": + description: Directory created + content: + application/json: + schema: + $ref: "#/components/schemas/MakeDirResponse" + "404": + description: Capsule not found + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + "409": + description: Capsule not running + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + + /v1/capsules/{id}/files/remove: + parameters: + - name: id + in: path + required: true + schema: + type: string + + post: + summary: Remove a file or directory + operationId: removePath + tags: [capsules] + security: + - apiKeyAuth: [] + requestBody: + required: true + content: + application/json: + schema: + $ref: "#/components/schemas/RemoveRequest" + responses: + "204": + description: File or directory removed + "404": + description: Capsule not found + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + "409": + description: Capsule not running + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + + /v1/capsules/{id}/exec/stream: parameters: - name: id in: path @@ -593,7 +1600,7 @@ paths: get: summary: Stream command execution via WebSocket operationId: execStream - tags: [sandboxes] + tags: [capsules] security: - apiKeyAuth: [] description: | @@ -623,19 +1630,96 @@ paths: "101": description: WebSocket upgrade "404": - description: Sandbox not found + description: Capsule not found content: application/json: schema: $ref: "#/components/schemas/Error" "409": - description: Sandbox not running + description: Capsule not running content: application/json: schema: $ref: "#/components/schemas/Error" - /v1/sandboxes/{id}/files/stream/write: + /v1/capsules/{id}/pty: + parameters: + - name: id + in: path + required: true + schema: + type: string + + get: + summary: Interactive PTY session via WebSocket + operationId: ptySession + tags: [capsules] + security: + - apiKeyAuth: [] + description: | + Opens a WebSocket connection for an interactive PTY (terminal) session. + Supports creating new sessions, sending input, resizing, killing, and + reconnecting to existing sessions. + + **Client sends** (first message — start a new PTY): + ```json + { + "type": "start", + "cmd": "/bin/bash", + "args": [], + "cols": 80, + "rows": 24, + "envs": {"TERM": "xterm-256color"}, + "cwd": "/home/user", + "user": "user" + } + ``` + All fields except `type` are optional. Defaults: cmd="/bin/bash", cols=80, rows=24. + + **Client sends** (first message — reconnect to existing PTY): + ```json + {"type": "connect", "tag": "pty-abc123de"} + ``` + + **Client sends** (after session is established): + ```json + {"type": "input", "data": ""} + {"type": "resize", "cols": 120, "rows": 40} + {"type": "kill"} + ``` + + **Server sends**: + ```json + {"type": "started", "tag": "pty-abc123de", "pid": 42} + {"type": "output", "data": ""} + {"type": "exit", "exit_code": 0} + {"type": "error", "data": "description", "fatal": true} + {"type": "ping"} + ``` + + PTY data (input and output) is base64-encoded because it contains raw + terminal bytes (escape sequences, control codes) that are not valid UTF-8. + + Sessions persist across WebSocket disconnections — the process keeps + running in the capsule. Use the `tag` from the "started" response to + reconnect later. + responses: + "101": + description: WebSocket upgrade + "404": + description: Capsule not found + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + "409": + description: Capsule not running + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + + /v1/capsules/{id}/files/stream/write: parameters: - name: id in: path @@ -646,11 +1730,11 @@ paths: post: summary: Upload a file (streaming) operationId: streamUploadFile - tags: [sandboxes] + tags: [capsules] security: - apiKeyAuth: [] description: | - Streams file content to the sandbox without buffering in memory. + Streams file content to the capsule without buffering in memory. Suitable for large files. Uses the same multipart/form-data format as the non-streaming upload endpoint. requestBody: @@ -663,7 +1747,7 @@ paths: properties: path: type: string - description: Absolute destination path inside the sandbox + description: Absolute destination path inside the capsule file: type: string format: binary @@ -672,19 +1756,19 @@ paths: "204": description: File uploaded "404": - description: Sandbox not found + description: Capsule not found content: application/json: schema: $ref: "#/components/schemas/Error" "409": - description: Sandbox not running + description: Capsule not running content: application/json: schema: $ref: "#/components/schemas/Error" - /v1/sandboxes/{id}/files/stream/read: + /v1/capsules/{id}/files/stream/read: parameters: - name: id in: path @@ -695,11 +1779,11 @@ paths: post: summary: Download a file (streaming) operationId: streamDownloadFile - tags: [sandboxes] + tags: [capsules] security: - apiKeyAuth: [] description: | - Streams file content from the sandbox without buffering in memory. + Streams file content from the capsule without buffering in memory. Suitable for large files. Returns raw bytes with chunked transfer encoding. requestBody: required: true @@ -716,13 +1800,13 @@ paths: type: string format: binary "404": - description: Sandbox or file not found + description: Capsule or file not found content: application/json: schema: $ref: "#/components/schemas/Error" "409": - description: Sandbox not running + description: Capsule not running content: application/json: schema: @@ -818,8 +1902,16 @@ paths: security: - bearerAuth: [] description: | - Admins can delete any host. Team owners can delete BYOC hosts - belonging to their team. + Admins can delete any host. Team owners and admins can delete BYOC hosts + belonging to their team. Without `?force=true`, returns 409 if the host + has active capsulees. With `?force=true`, destroys all capsulees first. + parameters: + - name: force + in: query + required: false + schema: + type: boolean + description: If true, destroy all capsulees on the host before deleting. responses: "204": description: Host deleted @@ -829,6 +1921,12 @@ paths: application/json: schema: $ref: "#/components/schemas/Error" + "409": + description: Host has active capsulees (only when force is not set) + content: + application/json: + schema: + $ref: "#/components/schemas/HostHasCapsulesError" /v1/hosts/{id}/token: parameters: @@ -937,6 +2035,72 @@ paths: schema: $ref: "#/components/schemas/Error" + /v1/hosts/auth/refresh: + post: + summary: Refresh host JWT + operationId: refreshHostToken + tags: [hosts] + description: | + Exchanges a refresh token for a new JWT and rotated refresh token. + The old refresh token is immediately revoked. No authentication required — + the refresh token itself is the credential. + requestBody: + required: true + content: + application/json: + schema: + $ref: "#/components/schemas/RefreshHostTokenRequest" + responses: + "200": + description: New JWT and rotated refresh token + content: + application/json: + schema: + $ref: "#/components/schemas/RefreshHostTokenResponse" + "401": + description: Invalid, expired, or revoked refresh token + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + + /v1/hosts/{id}/delete-preview: + parameters: + - name: id + in: path + required: true + schema: + type: string + + get: + summary: Preview host deletion + operationId: getHostDeletePreview + tags: [hosts] + security: + - bearerAuth: [] + description: | + Returns the list of capsule IDs that would be destroyed if the host + were deleted with `?force=true`. No state is modified. + responses: + "200": + description: Deletion preview + content: + application/json: + schema: + $ref: "#/components/schemas/HostDeletePreview" + "403": + description: Insufficient permissions + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + "404": + description: Host not found + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + /v1/hosts/{id}/tags: parameters: - name: id @@ -1012,13 +2176,183 @@ paths: schema: $ref: "#/components/schemas/Error" + /v1/channels: + post: + summary: Create a notification channel + operationId: createChannel + tags: [channels] + security: + - bearerAuth: [] + requestBody: + required: true + content: + application/json: + schema: + $ref: "#/components/schemas/CreateChannelRequest" + responses: + "201": + description: Channel created + content: + application/json: + schema: + $ref: "#/components/schemas/ChannelResponse" + "400": + $ref: "#/components/responses/BadRequest" + get: + summary: List notification channels + operationId: listChannels + tags: [channels] + security: + - bearerAuth: [] + responses: + "200": + description: Channels list + content: + application/json: + schema: + type: array + items: + $ref: "#/components/schemas/ChannelResponse" + + /v1/channels/test: + post: + summary: Test a channel configuration + description: > + Sends a test notification using the provided provider and config without + saving anything. Use this to verify credentials before creating a channel. + operationId: testChannel + tags: [channels] + security: + - bearerAuth: [] + requestBody: + required: true + content: + application/json: + schema: + $ref: "#/components/schemas/TestChannelRequest" + responses: + "200": + description: Test notification sent successfully + content: + application/json: + schema: + type: object + properties: + status: + type: string + example: ok + "400": + $ref: "#/components/responses/BadRequest" + + /v1/channels/{id}: + parameters: + - name: id + in: path + required: true + schema: + type: string + get: + summary: Get a notification channel + operationId: getChannel + tags: [channels] + security: + - bearerAuth: [] + responses: + "200": + description: Channel details + content: + application/json: + schema: + $ref: "#/components/schemas/ChannelResponse" + "404": + description: Channel not found + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + patch: + summary: Update a notification channel + operationId: updateChannel + tags: [channels] + security: + - bearerAuth: [] + requestBody: + required: true + content: + application/json: + schema: + $ref: "#/components/schemas/UpdateChannelRequest" + responses: + "200": + description: Channel updated + content: + application/json: + schema: + $ref: "#/components/schemas/ChannelResponse" + "400": + $ref: "#/components/responses/BadRequest" + "404": + description: Channel not found + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + delete: + summary: Delete a notification channel + operationId: deleteChannel + tags: [channels] + security: + - bearerAuth: [] + responses: + "204": + description: Channel deleted + + /v1/channels/{id}/config: + parameters: + - name: id + in: path + required: true + schema: + type: string + put: + summary: Rotate channel secrets + description: > + Replaces the channel's provider configuration entirely with new secrets. + The previous config is discarded. Config fields must match the provider's + required fields. + operationId: rotateChannelConfig + tags: [channels] + security: + - bearerAuth: [] + requestBody: + required: true + content: + application/json: + schema: + $ref: "#/components/schemas/RotateConfigRequest" + responses: + "200": + description: Config rotated + content: + application/json: + schema: + $ref: "#/components/schemas/ChannelResponse" + "400": + $ref: "#/components/responses/BadRequest" + "404": + description: Channel not found + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + components: securitySchemes: apiKeyAuth: type: apiKey in: header name: X-API-Key - description: API key for sandbox lifecycle operations. Create via POST /v1/api-keys. + description: API key for capsule lifecycle operations. Create via POST /v1/api-keys. bearerAuth: type: http @@ -1030,12 +2364,12 @@ components: type: apiKey in: header name: X-Host-Token - description: Long-lived host JWT returned from POST /v1/hosts/register. Valid for 1 year. + description: Host JWT returned from POST /v1/hosts/register or POST /v1/hosts/auth/refresh. Valid for 7 days. schemas: SignupRequest: type: object - required: [email, password] + required: [email, password, name] properties: email: type: string @@ -1043,6 +2377,9 @@ components: password: type: string minLength: 8 + name: + type: string + maxLength: 100 LoginRequest: type: object @@ -1054,6 +2391,13 @@ components: password: type: string + SignupResponse: + type: object + properties: + message: + type: string + description: Confirmation message instructing user to check email + AuthResponse: type: object properties: @@ -1066,6 +2410,8 @@ components: type: string email: type: string + name: + type: string CreateAPIKeyRequest: type: object @@ -1098,7 +2444,7 @@ components: description: Full plaintext key. Only returned on creation, never again. nullable: true - CreateSandboxRequest: + CreateCapsuleRequest: type: object properties: template: @@ -1114,18 +2460,91 @@ components: type: integer default: 0 description: > - Auto-pause TTL in seconds. The sandbox is automatically paused + Auto-pause TTL in seconds. The capsule is automatically paused after this duration of inactivity (no exec or ping). 0 means no auto-pause. - Sandbox: + UsageResponse: + type: object + properties: + from: + type: string + format: date + to: + type: string + format: date + points: + type: array + items: + type: object + properties: + date: + type: string + format: date + cpu_minutes: + type: number + ram_mb_minutes: + type: number + + CapsuleStats: + type: object + properties: + range: + type: string + enum: [5m, 1h, 6h, 24h, 30d] + current: + type: object + properties: + running_count: + type: integer + vcpus_reserved: + type: integer + memory_mb_reserved: + type: integer + sampled_at: + type: string + format: date-time + nullable: true + peaks: + type: object + description: Maximum values over the last 30 days. + properties: + running_count: + type: integer + vcpus: + type: integer + memory_mb: + type: integer + series: + type: object + description: Parallel arrays for chart rendering. + properties: + labels: + type: array + items: + type: string + format: date-time + running: + type: array + items: + type: integer + vcpus: + type: array + items: + type: integer + memory_mb: + type: array + items: + type: integer + + Capsule: type: object properties: id: type: string status: type: string - enum: [pending, running, paused, stopped, error] + enum: [pending, starting, running, paused, hibernated, stopped, missing, error] template: type: string vcpus: @@ -1159,7 +2578,7 @@ components: properties: sandbox_id: type: string - description: ID of the running sandbox to snapshot. + description: ID of the running capsule to snapshot. name: type: string description: Name for the snapshot template. Auto-generated if omitted. @@ -1198,6 +2617,56 @@ components: timeout_sec: type: integer default: 30 + description: Timeout in seconds (foreground exec only, default 30) + background: + type: boolean + default: false + description: If true, starts the process in the background and returns immediately with a PID and tag (HTTP 202) + tag: + type: string + description: Optional user-chosen tag for the background process. Auto-generated if omitted. Only used when background is true. + envs: + type: object + additionalProperties: + type: string + description: Environment variables for the process (background exec only) + cwd: + type: string + description: Working directory for the process (background exec only) + + BackgroundExecResponse: + type: object + properties: + sandbox_id: + type: string + cmd: + type: string + pid: + type: integer + tag: + type: string + + ProcessEntry: + type: object + properties: + pid: + type: integer + tag: + type: string + cmd: + type: string + args: + type: array + items: + type: string + + ProcessListResponse: + type: object + properties: + processes: + type: array + items: + $ref: "#/components/schemas/ProcessEntry" ExecResponse: type: object @@ -1225,7 +2694,79 @@ components: properties: path: type: string - description: Absolute file path inside the sandbox + description: Absolute file path inside the capsule + + ListDirRequest: + type: object + required: [path] + properties: + path: + type: string + description: Directory path inside the capsule + depth: + type: integer + default: 1 + description: Recursion depth (0 = non-recursive, 1 = immediate children) + + ListDirResponse: + type: object + properties: + entries: + type: array + items: + $ref: "#/components/schemas/FileEntry" + + FileEntry: + type: object + properties: + name: + type: string + path: + type: string + type: + type: string + enum: [file, directory, symlink] + size: + type: integer + format: int64 + mode: + type: integer + permissions: + type: string + description: Human-readable permissions (e.g. "-rwxr-xr-x") + owner: + type: string + group: + type: string + modified_at: + type: integer + format: int64 + description: Unix timestamp (seconds) + symlink_target: + type: string + nullable: true + + MakeDirRequest: + type: object + required: [path] + properties: + path: + type: string + description: Directory path to create inside the capsule + + MakeDirResponse: + type: object + properties: + entry: + $ref: "#/components/schemas/FileEntry" + + RemoveRequest: + type: object + required: [path] + properties: + path: + type: string + description: Path to remove inside the capsule CreateHostRequest: type: object @@ -1281,7 +2822,10 @@ components: $ref: "#/components/schemas/Host" token: type: string - description: Long-lived host JWT for X-Host-Token header. Valid for 1 year. + description: Host JWT for X-Host-Token header. Valid for 7 days. + refresh_token: + type: string + description: Refresh token for obtaining new JWTs. Valid for 60 days; rotated on each use. Host: type: object @@ -1317,7 +2861,7 @@ components: nullable: true status: type: string - enum: [pending, online, offline, draining] + enum: [pending, online, offline, draining, unreachable] last_heartbeat_at: type: string format: date-time @@ -1331,6 +2875,54 @@ components: type: string format: date-time + RefreshHostTokenRequest: + type: object + required: [refresh_token] + properties: + refresh_token: + type: string + description: Refresh token obtained from registration or a previous refresh. + + RefreshHostTokenResponse: + type: object + properties: + host: + $ref: "#/components/schemas/Host" + token: + type: string + description: New host JWT. Valid for 7 days. + refresh_token: + type: string + description: New refresh token. Valid for 60 days; old token is revoked. + + HostDeletePreview: + type: object + properties: + host: + $ref: "#/components/schemas/Host" + sandbox_ids: + type: array + items: + type: string + description: IDs of capsulees that would be destroyed on force-delete. + + HostHasCapsulesError: + type: object + properties: + error: + type: object + properties: + code: + type: string + example: host_has_sandboxes + message: + type: string + sandbox_ids: + type: array + items: + type: string + description: IDs of active capsulees blocking deletion. + AddTagRequest: type: object required: [tag] @@ -1338,6 +2930,230 @@ components: tag: type: string + UserSearchResult: + type: object + properties: + user_id: + type: string + email: + type: string + + Team: + type: object + properties: + id: + type: string + name: + type: string + slug: + type: string + description: Immutable 12-char hex slug (e.g. a1b2c3-d1e2f3) + created_at: + type: string + format: date-time + + TeamWithRole: + allOf: + - $ref: "#/components/schemas/Team" + - type: object + properties: + role: + type: string + enum: [owner, admin, member] + + TeamMember: + type: object + properties: + user_id: + type: string + email: + type: string + role: + type: string + enum: [owner, admin, member] + joined_at: + type: string + format: date-time + + TeamDetail: + type: object + properties: + team: + $ref: "#/components/schemas/Team" + members: + type: array + items: + $ref: "#/components/schemas/TeamMember" + + CapsuleMetrics: + type: object + properties: + sandbox_id: + type: string + range: + type: string + enum: ["5m", "10m", "1h", "2h", "6h", "12h", "24h"] + points: + type: array + items: + $ref: "#/components/schemas/MetricPoint" + + MetricPoint: + type: object + properties: + timestamp_unix: + type: integer + format: int64 + cpu_pct: + type: number + format: double + description: "CPU utilization percentage (0-100), normalized to vCPU count" + mem_bytes: + type: integer + format: int64 + description: "Resident memory in bytes (VmRSS of Firecracker process)" + disk_bytes: + type: integer + format: int64 + description: "Allocated disk bytes for the CoW sparse file" + + CreateChannelRequest: + type: object + required: [name, provider, config, events] + properties: + name: + type: string + description: Unique channel name within the team. + provider: + type: string + enum: [discord, slack, teams, googlechat, telegram, matrix, webhook] + config: + type: object + additionalProperties: + type: string + description: > + Provider-specific configuration fields. + Discord/Slack/Teams/Google Chat: {"webhook_url": "..."}. + Telegram: {"bot_token": "...", "chat_id": "..."}. + Matrix: {"homeserver_url": "...", "access_token": "...", "room_id": "..."}. + Webhook: {"url": "...", "secret": "..."} (secret is auto-generated if omitted). + events: + type: array + items: + type: string + enum: + - capsule.created + - capsule.running + - capsule.paused + - capsule.destroyed + - template.snapshot.created + - template.snapshot.deleted + - host.up + - host.down + + TestChannelRequest: + type: object + required: [provider, config] + properties: + provider: + type: string + enum: [discord, slack, teams, googlechat, telegram, matrix, webhook] + config: + type: object + additionalProperties: + type: string + description: Provider-specific configuration fields (same as CreateChannelRequest.config). + + RotateConfigRequest: + type: object + required: [config] + properties: + config: + type: object + additionalProperties: + type: string + description: > + New provider configuration fields. Must include all required fields + for the channel's provider. Replaces the existing config entirely. + + UpdateChannelRequest: + type: object + required: [name, events] + properties: + name: + type: string + events: + type: array + items: + type: string + enum: + - capsule.created + - capsule.running + - capsule.paused + - capsule.destroyed + - template.snapshot.created + - template.snapshot.deleted + - host.up + - host.down + + ChannelResponse: + type: object + properties: + id: + type: string + team_id: + type: string + name: + type: string + provider: + type: string + enum: [discord, slack, teams, googlechat, telegram, matrix, webhook] + events: + type: array + items: + type: string + created_at: + type: string + format: date-time + updated_at: + type: string + format: date-time + secret: + type: string + nullable: true + description: Webhook secret. Only returned on creation, never again. + + MeResponse: + type: object + properties: + name: + type: string + email: + type: string + format: email + has_password: + type: boolean + description: Whether the user has a password set (false for OAuth-only accounts) + providers: + type: array + items: + type: string + description: List of linked OAuth provider names (e.g. ["github"]) + + ChangePasswordRequest: + type: object + required: [new_password] + properties: + current_password: + type: string + description: Required when changing an existing password + new_password: + type: string + minLength: 8 + confirm_password: + type: string + description: Required when adding a password to an OAuth-only account (must match new_password) + Error: type: object properties: diff --git a/pyproject.toml b/pyproject.toml index 0149f62..98570b7 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,14 +1,30 @@ [project] name = "wrenn" version = "0.1.0" -description = "Add your description here" +description = "Python SDK for Wrenn" readme = "README.md" +license = "MIT" +license-files = ["LICENSE"] authors = [ - { name = "Tasnim Kabir Sadik", email = "tksadik92@gmail.com" } + { name = "Rafeed M. Bhuiyan", email = "rafeed@omukk.dev" }, + { name = "Tasnim Kabir Sadik", email = "tksadik@omukk.dev" }, ] requires-python = ">=3.13" +keywords = ["wrenn"] +classifiers = [ + "Development Status :: 3 - Alpha", + "Intended Audience :: Developers", + "License :: OSI Approved :: MIT License", + "Operating System :: OS Independent", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.13", + "Topic :: Software Development :: Libraries :: Python Modules", + "Typing :: Typed", +] dependencies = [ + "email-validator>=2.3.0", "httpx>=0.28.1", + "httpx-ws>=0.9.0", "pydantic>=2.12.5", ] @@ -18,9 +34,19 @@ build-backend = "hatchling.build" [dependency-groups] dev = [ - "datamodel-code-generator>=0.56.0", + "datamodel-code-generator[ruff]>=0.56.0", "mypy>=1.20.0", "pytest>=9.0.3", "pytest-asyncio>=1.3.0", + "respx>=0.23.1", "ruff>=0.15.10", ] + +[project.urls] +Homepage = "https://wrenn.dev" +Repository = "https://github.com/wrennhq/python-sdk" + +[tool.pytest.ini_options] +markers = [ + "integration: integration tests (require live server)", +] diff --git a/src/wrenn/__init__.py b/src/wrenn/__init__.py index cc0f99e..1ae84ae 100644 --- a/src/wrenn/__init__.py +++ b/src/wrenn/__init__.py @@ -1,2 +1,107 @@ -def hello() -> str: - return "Hello from wrenn!" +from wrenn._git import ( + AsyncGit, + FileStatus, + Git, + GitAuthError, + GitBranch, + GitCommandError, + GitError, + GitStatus, +) +from wrenn.async_capsule import AsyncCapsule +from wrenn.capsule import Capsule +from wrenn.client import AsyncWrennClient, WrennClient +from wrenn.commands import ( + CommandHandle, + CommandResult, + ProcessInfo, + StreamErrorEvent, + StreamEvent, + StreamExitEvent, + StreamStartEvent, + StreamStderrEvent, + StreamStdoutEvent, +) +from wrenn.exceptions import ( + WrennAgentError, + WrennAuthenticationError, + WrennConflictError, + WrennError, + WrennForbiddenError, + WrennHostHasCapsulesError, + WrennHostUnavailableError, + WrennInternalError, + WrennNotFoundError, + WrennValidationError, +) +from wrenn.models import FileEntry +from wrenn.pty import AsyncPtySession, PtyEvent, PtyEventType, PtySession + +__version__ = "0.1.0" + +__all__ = [ + "__version__", + "AsyncCapsule", + "AsyncGit", + "AsyncPtySession", + "AsyncWrennClient", + "Capsule", + "CommandHandle", + "CommandResult", + "FileEntry", + "FileStatus", + "Git", + "GitAuthError", + "GitBranch", + "GitCommandError", + "GitError", + "GitStatus", + "ProcessInfo", + "PtyEvent", + "PtyEventType", + "PtySession", + "Sandbox", + "StreamErrorEvent", + "StreamEvent", + "StreamExitEvent", + "StreamStartEvent", + "StreamStderrEvent", + "StreamStdoutEvent", + "WrennAgentError", + "WrennAuthenticationError", + "WrennClient", + "WrennConflictError", + "WrennError", + "WrennForbiddenError", + "WrennHostHasCapsulesError", + "WrennHostHasSandboxesError", + "WrennHostUnavailableError", + "WrennInternalError", + "WrennNotFoundError", + "WrennValidationError", +] + + +def __getattr__(name: str) -> type: + import sys + import warnings + + _module = sys.modules[__name__] + + if name == "Sandbox": + warnings.warn( + "'Sandbox' is deprecated, use 'Capsule' instead", + FutureWarning, + stacklevel=2, + ) + setattr(_module, name, Capsule) + return Capsule + if name == "WrennHostHasSandboxesError": + warnings.warn( + "'WrennHostHasSandboxesError' is deprecated, use 'WrennHostHasCapsulesError' instead", + FutureWarning, + stacklevel=2, + ) + setattr(_module, name, WrennHostHasCapsulesError) + return WrennHostHasCapsulesError + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") diff --git a/src/wrenn/_config.py b/src/wrenn/_config.py new file mode 100644 index 0000000..a9b57ad --- /dev/null +++ b/src/wrenn/_config.py @@ -0,0 +1,33 @@ +from __future__ import annotations + +import os +from dataclasses import dataclass + +DEFAULT_BASE_URL = "https://app.wrenn.dev/api" +ENV_API_KEY = "WRENN_API_KEY" +ENV_BASE_URL = "WRENN_BASE_URL" + + +@dataclass(frozen=True) +class ConnectionConfig: + """Resolved credentials and base URL for Wrenn API calls.""" + + api_key: str + base_url: str + + @classmethod + def from_env( + cls, + api_key: str | None = None, + base_url: str | None = None, + ) -> ConnectionConfig: + resolved_key = api_key or os.environ.get(ENV_API_KEY) + if not resolved_key: + raise ValueError( + f"No API key provided. Pass api_key= or set the {ENV_API_KEY} environment variable." + ) + resolved_url = base_url or os.environ.get(ENV_BASE_URL, DEFAULT_BASE_URL) + return cls(api_key=resolved_key, base_url=resolved_url) + + def auth_headers(self) -> dict[str, str]: + return {"X-API-Key": self.api_key} diff --git a/src/wrenn/_git/__init__.py b/src/wrenn/_git/__init__.py new file mode 100644 index 0000000..fa59564 --- /dev/null +++ b/src/wrenn/_git/__init__.py @@ -0,0 +1,1435 @@ +"""Git operations inside a Wrenn capsule. + +Provides :class:`Git` (sync) and :class:`AsyncGit` (async) interfaces +accessed via ``capsule.git``. All operations execute the real ``git`` +binary inside the capsule through :class:`~wrenn.commands.Commands`. +""" + +from __future__ import annotations + +import posixpath +import shlex +from collections.abc import Awaitable, Callable +from urllib.parse import urlparse + +import httpx + +from wrenn._git._auth import ( + build_credential_approve_cmd, + embed_credentials, + is_auth_error, + strip_credentials, +) +from wrenn._git._cmd import ( + FileStatus, + GitBranch, + GitStatus, + build_add, + build_branches, + build_checkout, + build_clone, + build_commit, + build_config_get, + build_config_set, + build_create_branch, + build_delete_branch, + build_init, + build_pull, + build_push, + build_remote_add, + build_remote_get_url, + build_remote_set_url, + build_reset, + build_restore, + build_status, + parse_branches, + parse_status, +) +from wrenn._git.exceptions import GitAuthError, GitCommandError, GitError +from wrenn.commands import AsyncCommands, CommandResult, Commands + +__all__ = [ + "AsyncGit", + "FileStatus", + "Git", + "GitAuthError", + "GitBranch", + "GitCommandError", + "GitError", + "GitStatus", +] + +_DEFAULT_GIT_ENV: dict[str, str] = {"GIT_TERMINAL_PROMPT": "0"} + + +def _check_result(result: CommandResult, *, op: str) -> None: + """Raise a :class:`GitError` subclass if the command failed. + + Args: + result: Result from ``commands.run()``. + op: Short operation name for error messages (e.g. ``"clone"``). + + Raises: + GitAuthError: If stderr contains authentication failure signals. + GitCommandError: For all other non-zero exit codes. + """ + if result.exit_code == 0: + return + if is_auth_error(result.stderr): + raise GitAuthError( + f"git {op}: authentication failed", + stderr=result.stderr, + exit_code=result.exit_code, + ) + msg = result.stderr.strip() or result.stdout.strip() + raise GitCommandError( + msg or f"git {op} failed (exit {result.exit_code})", + stderr=result.stderr, + exit_code=result.exit_code, + ) + + +def _merge_envs(envs: dict[str, str] | None) -> dict[str, str]: + """Merge caller-provided envs with default git environment.""" + return {**_DEFAULT_GIT_ENV, **(envs or {})} + + +def _derive_repo_dir(url: str) -> str | None: + """Derive the default repo directory name from a git URL.""" + parsed = urlparse(url) + if parsed.scheme not in ("http", "https"): + return None + trimmed = parsed.path.rstrip("/") + if not trimmed: + return None + last = trimmed.split("/")[-1] + if not last: + return None + return last[:-4] if last.endswith(".git") else last + + +class Git: + """Sync git interface. Accessed via ``capsule.git``. + + Executes the real ``git`` binary inside the capsule through + :meth:`Commands.run`. Methods raise :class:`GitCommandError` (or + :class:`GitAuthError`) on non-zero exit codes. + """ + + def __init__(self, capsule_id: str, http: httpx.Client) -> None: + self._capsule_id = capsule_id + self._http = http + self._commands = Commands(capsule_id, http) + + def _run( + self, + argv: list[str], + *, + cwd: str | None = None, + envs: dict[str, str] | None = None, + timeout: int | None = 30, + ) -> CommandResult: + """Build a shell command from *argv* and execute it.""" + return self._commands.run( + shlex.join(argv), + cwd=cwd, + envs=_merge_envs(envs), + timeout=timeout, + ) + + def _run_shell( + self, + cmd: str, + *, + cwd: str | None = None, + envs: dict[str, str] | None = None, + timeout: int | None = 30, + ) -> CommandResult: + """Execute a raw shell command string.""" + return self._commands.run( + cmd, + cwd=cwd, + envs=_merge_envs(envs), + timeout=timeout, + ) + + # ── Repository setup ─────────────────────────────────────── + + def clone( + self, + url: str, + dest: str | None = None, + *, + branch: str | None = None, + depth: int | None = None, + username: str | None = None, + password: str | None = None, + dangerously_store_credentials: bool = False, + cwd: str | None = None, + envs: dict[str, str] | None = None, + timeout: int | None = 300, + ) -> CommandResult: + """Clone a remote repository into the capsule. + + Args: + url: Remote repository URL. + dest: Destination path. Defaults to the repository name + derived from the URL. + branch: Branch or tag to check out. + depth: Create a shallow clone with this many commits. + username: Username for HTTP(S) authentication. + password: Password or token for HTTP(S) authentication. + dangerously_store_credentials: If ``True``, leave credentials + embedded in the remote URL after cloning. + cwd: Working directory for the command. + envs: Extra environment variables. + timeout: Command timeout in seconds. Defaults to ``300``. + + Returns: + Command result with stdout, stderr, exit_code, and duration. + + Raises: + GitAuthError: If the remote rejected authentication. + GitCommandError: If clone failed for another reason. + ValueError: If *password* is provided without *username*. + """ + if password and not username: + raise ValueError( + "Username is required when using a password for git clone." + ) + + clone_url = url + if username and password: + clone_url = embed_credentials(url, username, password) + + argv = build_clone(clone_url, dest, branch=branch, depth=depth) + result = self._run(argv, cwd=cwd, envs=envs, timeout=timeout) + _check_result(result, op="clone") + + if username and password and not dangerously_store_credentials: + sanitized = strip_credentials(clone_url) + if sanitized != clone_url: + repo_dir = dest or _derive_repo_dir(url) + if repo_dir: + repo_cwd = posixpath.join(cwd, repo_dir) if cwd else repo_dir + strip_result = self._run( + build_remote_set_url("origin", sanitized), + cwd=repo_cwd, + envs=envs, + ) + _check_result(strip_result, op="clone (strip credentials)") + + return result + + def init( + self, + path: str = ".", + *, + bare: bool = False, + initial_branch: str | None = None, + cwd: str | None = None, + envs: dict[str, str] | None = None, + timeout: int | None = 30, + ) -> CommandResult: + """Initialize a new git repository. + + Args: + path: Destination path for the repository. + bare: Create a bare repository. + initial_branch: Name for the initial branch (e.g. ``"main"``). + cwd: Working directory for the command. + envs: Extra environment variables. + timeout: Command timeout in seconds. + + Returns: + Command result. + + Raises: + GitCommandError: If init failed. + """ + argv = build_init(path, bare=bare, initial_branch=initial_branch) + result = self._run(argv, cwd=cwd, envs=envs, timeout=timeout) + _check_result(result, op="init") + return result + + # ── Staging and committing ───────────────────────────────── + + def add( + self, + paths: list[str] | None = None, + *, + all: bool = False, + cwd: str | None = None, + envs: dict[str, str] | None = None, + timeout: int | None = 30, + ) -> CommandResult: + """Stage files for commit. + + Args: + paths: Specific files to stage. If ``None``, stages the + current directory (or all with ``all=True``). + all: Stage all changes including untracked files. + cwd: Working directory (repository root). + envs: Extra environment variables. + timeout: Command timeout in seconds. + + Returns: + Command result. + + Raises: + GitCommandError: If add failed. + """ + argv = build_add(paths, all=all) + result = self._run(argv, cwd=cwd, envs=envs, timeout=timeout) + _check_result(result, op="add") + return result + + def commit( + self, + message: str, + *, + allow_empty: bool = False, + author_name: str | None = None, + author_email: str | None = None, + cwd: str | None = None, + envs: dict[str, str] | None = None, + timeout: int | None = 30, + ) -> CommandResult: + """Create a commit. + + Args: + message: Commit message. + allow_empty: Allow creating a commit with no changes. + author_name: Override the commit author name. + author_email: Override the commit author email. + cwd: Working directory (repository root). + envs: Extra environment variables. + timeout: Command timeout in seconds. + + Returns: + Command result. + + Raises: + GitCommandError: If commit failed. + """ + argv = build_commit( + message, + allow_empty=allow_empty, + author_name=author_name, + author_email=author_email, + ) + result = self._run(argv, cwd=cwd, envs=envs, timeout=timeout) + _check_result(result, op="commit") + return result + + # ── Remote sync ──────────────────────────────────────────── + + def push( + self, + remote: str = "origin", + branch: str | None = None, + *, + force: bool = False, + set_upstream: bool = False, + username: str | None = None, + password: str | None = None, + cwd: str | None = None, + envs: dict[str, str] | None = None, + timeout: int | None = 60, + ) -> CommandResult: + """Push commits to a remote. + + Args: + remote: Remote name. Defaults to ``"origin"``. + branch: Branch to push. Defaults to the current branch. + force: Force-push. + set_upstream: Set upstream tracking reference. + username: Username for HTTP(S) authentication. + password: Password or token for HTTP(S) authentication. + cwd: Working directory (repository root). + envs: Extra environment variables. + timeout: Command timeout in seconds. + + Returns: + Command result. + + Raises: + GitAuthError: If authentication failed. + GitCommandError: If push failed. + """ + if username and password: + return self._with_remote_credentials( + remote=remote, + username=username, + password=password, + operation=lambda: self._run( + build_push(remote, branch, force=force, set_upstream=set_upstream), + cwd=cwd, + envs=envs, + timeout=timeout, + ), + cwd=cwd, + envs=envs, + timeout=timeout, + op="push", + ) + + argv = build_push(remote, branch, force=force, set_upstream=set_upstream) + result = self._run(argv, cwd=cwd, envs=envs, timeout=timeout) + _check_result(result, op="push") + return result + + def pull( + self, + remote: str = "origin", + branch: str | None = None, + *, + rebase: bool = False, + ff_only: bool = False, + username: str | None = None, + password: str | None = None, + cwd: str | None = None, + envs: dict[str, str] | None = None, + timeout: int | None = 60, + ) -> CommandResult: + """Pull changes from a remote. + + Args: + remote: Remote name. Defaults to ``"origin"``. + branch: Branch to pull. + rebase: Rebase instead of merge. + ff_only: Only allow fast-forward merges. + username: Username for HTTP(S) authentication. + password: Password or token for HTTP(S) authentication. + cwd: Working directory (repository root). + envs: Extra environment variables. + timeout: Command timeout in seconds. + + Returns: + Command result. + + Raises: + GitAuthError: If authentication failed. + GitCommandError: If pull failed. + """ + if username and password: + return self._with_remote_credentials( + remote=remote, + username=username, + password=password, + operation=lambda: self._run( + build_pull(remote, branch, rebase=rebase, ff_only=ff_only), + cwd=cwd, + envs=envs, + timeout=timeout, + ), + cwd=cwd, + envs=envs, + timeout=timeout, + op="pull", + ) + + argv = build_pull(remote, branch, rebase=rebase, ff_only=ff_only) + result = self._run(argv, cwd=cwd, envs=envs, timeout=timeout) + _check_result(result, op="pull") + return result + + # ── Status and branches ──────────────────────────────────── + + def status( + self, + *, + cwd: str | None = None, + envs: dict[str, str] | None = None, + timeout: int | None = 30, + ) -> GitStatus: + """Get repository status. + + Args: + cwd: Working directory (repository root). + envs: Extra environment variables. + timeout: Command timeout in seconds. + + Returns: + Parsed :class:`GitStatus` with branch info and file changes. + + Raises: + GitCommandError: If the command failed. + """ + result = self._run(build_status(), cwd=cwd, envs=envs, timeout=timeout) + _check_result(result, op="status") + return parse_status(result.stdout) + + def branches( + self, + *, + cwd: str | None = None, + envs: dict[str, str] | None = None, + timeout: int | None = 30, + ) -> list[GitBranch]: + """List local branches. + + Args: + cwd: Working directory (repository root). + envs: Extra environment variables. + timeout: Command timeout in seconds. + + Returns: + List of :class:`GitBranch`. + + Raises: + GitCommandError: If the command failed. + """ + result = self._run(build_branches(), cwd=cwd, envs=envs, timeout=timeout) + _check_result(result, op="branches") + return parse_branches(result.stdout) + + def create_branch( + self, + name: str, + *, + start_point: str | None = None, + cwd: str | None = None, + envs: dict[str, str] | None = None, + timeout: int | None = 30, + ) -> CommandResult: + """Create and check out a new branch. + + Args: + name: Branch name. + start_point: Commit or ref to branch from. + cwd: Working directory (repository root). + envs: Extra environment variables. + timeout: Command timeout in seconds. + + Returns: + Command result. + + Raises: + GitCommandError: If the command failed. + """ + argv = build_create_branch(name, start_point=start_point) + result = self._run(argv, cwd=cwd, envs=envs, timeout=timeout) + _check_result(result, op="create_branch") + return result + + def checkout_branch( + self, + name: str, + *, + cwd: str | None = None, + envs: dict[str, str] | None = None, + timeout: int | None = 30, + ) -> CommandResult: + """Check out an existing branch. + + Args: + name: Branch name. + cwd: Working directory (repository root). + envs: Extra environment variables. + timeout: Command timeout in seconds. + + Returns: + Command result. + + Raises: + GitCommandError: If the command failed. + """ + argv = build_checkout(name) + result = self._run(argv, cwd=cwd, envs=envs, timeout=timeout) + _check_result(result, op="checkout_branch") + return result + + def delete_branch( + self, + name: str, + *, + force: bool = False, + cwd: str | None = None, + envs: dict[str, str] | None = None, + timeout: int | None = 30, + ) -> CommandResult: + """Delete a branch. + + Args: + name: Branch name. + force: Force-delete with ``-D``. + cwd: Working directory (repository root). + envs: Extra environment variables. + timeout: Command timeout in seconds. + + Returns: + Command result. + + Raises: + GitCommandError: If the command failed. + """ + argv = build_delete_branch(name, force=force) + result = self._run(argv, cwd=cwd, envs=envs, timeout=timeout) + _check_result(result, op="delete_branch") + return result + + # ── Remotes ──────────────────────────────────────────────── + + def remote_add( + self, + name: str, + url: str, + *, + fetch: bool = False, + cwd: str | None = None, + envs: dict[str, str] | None = None, + timeout: int | None = 30, + ) -> CommandResult: + """Add a remote. + + Args: + name: Remote name (e.g. ``"origin"``). + url: Remote URL. + fetch: Fetch after adding. + cwd: Working directory (repository root). + envs: Extra environment variables. + timeout: Command timeout in seconds. + + Returns: + Command result. + + Raises: + GitCommandError: If the command failed. + """ + argv = build_remote_add(name, url, fetch=fetch) + result = self._run(argv, cwd=cwd, envs=envs, timeout=timeout) + _check_result(result, op="remote_add") + return result + + def remote_get( + self, + name: str = "origin", + *, + cwd: str | None = None, + envs: dict[str, str] | None = None, + timeout: int | None = 30, + ) -> str | None: + """Get the URL of a remote. + + Returns ``None`` if the remote does not exist rather than raising. + + Args: + name: Remote name. Defaults to ``"origin"``. + cwd: Working directory (repository root). + envs: Extra environment variables. + timeout: Command timeout in seconds. + + Returns: + Remote URL or ``None``. + """ + result = self._run( + build_remote_get_url(name), cwd=cwd, envs=envs, timeout=timeout + ) + if result.exit_code != 0: + return None + url = result.stdout.strip() + return url or None + + # ── Reset and restore ────────────────────────────────────── + + def reset( + self, + *, + mode: str | None = None, + ref: str | None = None, + paths: list[str] | None = None, + cwd: str | None = None, + envs: dict[str, str] | None = None, + timeout: int | None = 30, + ) -> CommandResult: + """Reset the current HEAD. + + Args: + mode: Reset mode (``soft``, ``mixed``, ``hard``, ``merge``, + ``keep``). + ref: Commit, branch, or ref to reset to. + paths: Paths to reset. + cwd: Working directory (repository root). + envs: Extra environment variables. + timeout: Command timeout in seconds. + + Returns: + Command result. + + Raises: + GitCommandError: If the command failed. + """ + argv = build_reset(mode=mode, ref=ref, paths=paths) + result = self._run(argv, cwd=cwd, envs=envs, timeout=timeout) + _check_result(result, op="reset") + return result + + def restore( + self, + paths: list[str], + *, + staged: bool = False, + worktree: bool = False, + source: str | None = None, + cwd: str | None = None, + envs: dict[str, str] | None = None, + timeout: int | None = 30, + ) -> CommandResult: + """Restore working-tree files or unstage changes. + + Args: + paths: Paths to restore. + staged: Restore the index (unstage). + worktree: Restore working-tree files. + source: Commit or ref to restore from. + cwd: Working directory (repository root). + envs: Extra environment variables. + timeout: Command timeout in seconds. + + Returns: + Command result. + + Raises: + GitCommandError: If the command failed. + """ + argv = build_restore(paths, staged=staged, worktree=worktree, source=source) + result = self._run(argv, cwd=cwd, envs=envs, timeout=timeout) + _check_result(result, op="restore") + return result + + # ── Configuration ────────────────────────────────────────── + + def set_config( + self, + key: str, + value: str, + *, + scope: str = "local", + cwd: str | None = None, + envs: dict[str, str] | None = None, + timeout: int | None = 30, + ) -> CommandResult: + """Set a git config value. + + Args: + key: Config key (e.g. ``"user.name"``). + value: Config value. + scope: Config scope: ``"local"``, ``"global"``, or + ``"system"``. + cwd: Working directory (repository root). Required when + scope is ``"local"``. + envs: Extra environment variables. + timeout: Command timeout in seconds. + + Returns: + Command result. + + Raises: + GitCommandError: If the command failed. + """ + argv = build_config_set(key, value, scope=scope, repo_path=cwd) + result = self._run(argv, cwd=cwd, envs=envs, timeout=timeout) + _check_result(result, op="set_config") + return result + + def get_config( + self, + key: str, + *, + scope: str = "local", + cwd: str | None = None, + envs: dict[str, str] | None = None, + timeout: int | None = 30, + ) -> str | None: + """Get a git config value. + + Returns ``None`` if the key is not set rather than raising. + + Args: + key: Config key (e.g. ``"user.name"``). + scope: Config scope: ``"local"``, ``"global"``, or + ``"system"``. + cwd: Working directory (repository root). Required when + scope is ``"local"``. + envs: Extra environment variables. + timeout: Command timeout in seconds. + + Returns: + Config value or ``None``. + """ + argv = build_config_get(key, scope=scope, repo_path=cwd) + result = self._run(argv, cwd=cwd, envs=envs, timeout=timeout) + if result.exit_code != 0: + return None + val = result.stdout.strip() + return val or None + + def configure_user( + self, + name: str, + email: str, + *, + scope: str = "global", + cwd: str | None = None, + envs: dict[str, str] | None = None, + timeout: int | None = 30, + ) -> None: + """Configure git user name and email. + + Args: + name: Git user name. + email: Git user email. + scope: Config scope. Defaults to ``"global"``. + cwd: Working directory (repository root). Required when + scope is ``"local"``. + envs: Extra environment variables. + timeout: Command timeout in seconds. + + Raises: + ValueError: If *name* or *email* is empty. + GitCommandError: If a config command failed. + """ + if not name or not email: + raise ValueError("Both name and email are required.") + self.set_config( + "user.name", name, scope=scope, cwd=cwd, envs=envs, timeout=timeout + ) + self.set_config( + "user.email", email, scope=scope, cwd=cwd, envs=envs, timeout=timeout + ) + + def dangerously_authenticate( + self, + username: str, + password: str, + host: str = "github.com", + protocol: str = "https", + *, + cwd: str | None = None, + envs: dict[str, str] | None = None, + timeout: int | None = 30, + ) -> None: + """Persist git credentials via the credential store. + + .. warning:: + + Credentials are written in plain text to the capsule + filesystem and are accessible to any process running inside + the capsule. Prefer per-operation ``username``/``password`` + parameters on :meth:`clone`, :meth:`push`, and :meth:`pull` + instead. + + Args: + username: Git username. + password: Password or personal access token. + host: Target host. Defaults to ``"github.com"``. + protocol: Protocol. Defaults to ``"https"``. + cwd: Working directory. + envs: Extra environment variables. + timeout: Command timeout in seconds. + + Raises: + ValueError: If *username* or *password* is empty. + GitCommandError: If a command failed. + """ + if not username or not password: + raise ValueError("Both username and password are required.") + self.set_config( + "credential.helper", + "store", + scope="global", + cwd=cwd, + envs=envs, + timeout=timeout, + ) + cmd = build_credential_approve_cmd( + username=username, + password=password, + host=host, + protocol=protocol, + ) + result = self._run_shell(cmd, cwd=cwd, envs=envs, timeout=timeout) + _check_result(result, op="dangerously_authenticate") + + # ── Credential helper for push/pull ──────────────────────── + + def _with_remote_credentials( + self, + *, + remote: str, + username: str, + password: str, + operation: Callable[[], CommandResult], + cwd: str | None, + envs: dict[str, str] | None, + timeout: int | None, + op: str, + ) -> CommandResult: + """Temporarily embed credentials in a remote URL, run an operation, + then restore the original URL. + """ + original_url = self.remote_get(remote, cwd=cwd, envs=envs, timeout=timeout) + if not original_url: + raise GitCommandError( + f"Remote '{remote}' not found.", + stderr="", + exit_code=1, + ) + + credential_url = embed_credentials(original_url, username, password) + self._run( + build_remote_set_url(remote, credential_url), + cwd=cwd, + envs=envs, + timeout=timeout, + ) + + op_error: Exception | None = None + result: CommandResult | None = None + try: + result = operation() + _check_result(result, op=op) + except Exception as err: + op_error = err + + restore_error: Exception | None = None + try: + self._run( + build_remote_set_url(remote, original_url), + cwd=cwd, + envs=envs, + timeout=timeout, + ) + except Exception as err: + restore_error = err + + if op_error: + raise op_error + if restore_error: + raise restore_error + + assert result is not None + return result + + +class AsyncGit: + """Async git interface. Accessed via ``capsule.git``. + + Async mirror of :class:`Git`. See that class for full method + documentation. + """ + + def __init__(self, capsule_id: str, http: httpx.AsyncClient) -> None: + self._capsule_id = capsule_id + self._http = http + self._commands = AsyncCommands(capsule_id, http) + + async def _run( + self, + argv: list[str], + *, + cwd: str | None = None, + envs: dict[str, str] | None = None, + timeout: int | None = 30, + ) -> CommandResult: + """Build a shell command from *argv* and execute it.""" + return await self._commands.run( + shlex.join(argv), + cwd=cwd, + envs=_merge_envs(envs), + timeout=timeout, + ) + + async def _run_shell( + self, + cmd: str, + *, + cwd: str | None = None, + envs: dict[str, str] | None = None, + timeout: int | None = 30, + ) -> CommandResult: + """Execute a raw shell command string.""" + return await self._commands.run( + cmd, + cwd=cwd, + envs=_merge_envs(envs), + timeout=timeout, + ) + + # ── Repository setup ─────────────────────────────────────── + + async def clone( + self, + url: str, + dest: str | None = None, + *, + branch: str | None = None, + depth: int | None = None, + username: str | None = None, + password: str | None = None, + dangerously_store_credentials: bool = False, + cwd: str | None = None, + envs: dict[str, str] | None = None, + timeout: int | None = 300, + ) -> CommandResult: + """Clone a remote repository into the capsule.""" + if password and not username: + raise ValueError( + "Username is required when using a password for git clone." + ) + + clone_url = url + if username and password: + clone_url = embed_credentials(url, username, password) + + argv = build_clone(clone_url, dest, branch=branch, depth=depth) + result = await self._run(argv, cwd=cwd, envs=envs, timeout=timeout) + _check_result(result, op="clone") + + if username and password and not dangerously_store_credentials: + sanitized = strip_credentials(clone_url) + if sanitized != clone_url: + repo_dir = dest or _derive_repo_dir(url) + if repo_dir: + repo_cwd = posixpath.join(cwd, repo_dir) if cwd else repo_dir + strip_result = await self._run( + build_remote_set_url("origin", sanitized), + cwd=repo_cwd, + envs=envs, + ) + _check_result(strip_result, op="clone (strip credentials)") + + return result + + async def init( + self, + path: str = ".", + *, + bare: bool = False, + initial_branch: str | None = None, + cwd: str | None = None, + envs: dict[str, str] | None = None, + timeout: int | None = 30, + ) -> CommandResult: + """Initialize a new git repository.""" + argv = build_init(path, bare=bare, initial_branch=initial_branch) + result = await self._run(argv, cwd=cwd, envs=envs, timeout=timeout) + _check_result(result, op="init") + return result + + # ── Staging and committing ───────────────────────────────── + + async def add( + self, + paths: list[str] | None = None, + *, + all: bool = False, + cwd: str | None = None, + envs: dict[str, str] | None = None, + timeout: int | None = 30, + ) -> CommandResult: + """Stage files for commit.""" + argv = build_add(paths, all=all) + result = await self._run(argv, cwd=cwd, envs=envs, timeout=timeout) + _check_result(result, op="add") + return result + + async def commit( + self, + message: str, + *, + allow_empty: bool = False, + author_name: str | None = None, + author_email: str | None = None, + cwd: str | None = None, + envs: dict[str, str] | None = None, + timeout: int | None = 30, + ) -> CommandResult: + """Create a commit.""" + argv = build_commit( + message, + allow_empty=allow_empty, + author_name=author_name, + author_email=author_email, + ) + result = await self._run(argv, cwd=cwd, envs=envs, timeout=timeout) + _check_result(result, op="commit") + return result + + # ── Remote sync ──────────────────────────────────────────── + + async def push( + self, + remote: str = "origin", + branch: str | None = None, + *, + force: bool = False, + set_upstream: bool = False, + username: str | None = None, + password: str | None = None, + cwd: str | None = None, + envs: dict[str, str] | None = None, + timeout: int | None = 60, + ) -> CommandResult: + """Push commits to a remote.""" + if username and password: + + async def _op() -> CommandResult: + return await self._run( + build_push(remote, branch, force=force, set_upstream=set_upstream), + cwd=cwd, + envs=envs, + timeout=timeout, + ) + + return await self._with_remote_credentials( + remote=remote, + username=username, + password=password, + operation=_op, + cwd=cwd, + envs=envs, + timeout=timeout, + op="push", + ) + + argv = build_push(remote, branch, force=force, set_upstream=set_upstream) + result = await self._run(argv, cwd=cwd, envs=envs, timeout=timeout) + _check_result(result, op="push") + return result + + async def pull( + self, + remote: str = "origin", + branch: str | None = None, + *, + rebase: bool = False, + ff_only: bool = False, + username: str | None = None, + password: str | None = None, + cwd: str | None = None, + envs: dict[str, str] | None = None, + timeout: int | None = 60, + ) -> CommandResult: + """Pull changes from a remote.""" + if username and password: + + async def _op() -> CommandResult: + return await self._run( + build_pull(remote, branch, rebase=rebase, ff_only=ff_only), + cwd=cwd, + envs=envs, + timeout=timeout, + ) + + return await self._with_remote_credentials( + remote=remote, + username=username, + password=password, + operation=_op, + cwd=cwd, + envs=envs, + timeout=timeout, + op="pull", + ) + + argv = build_pull(remote, branch, rebase=rebase, ff_only=ff_only) + result = await self._run(argv, cwd=cwd, envs=envs, timeout=timeout) + _check_result(result, op="pull") + return result + + # ── Status and branches ──────────────────────────────────── + + async def status( + self, + *, + cwd: str | None = None, + envs: dict[str, str] | None = None, + timeout: int | None = 30, + ) -> GitStatus: + """Get repository status.""" + result = await self._run(build_status(), cwd=cwd, envs=envs, timeout=timeout) + _check_result(result, op="status") + return parse_status(result.stdout) + + async def branches( + self, + *, + cwd: str | None = None, + envs: dict[str, str] | None = None, + timeout: int | None = 30, + ) -> list[GitBranch]: + """List local branches.""" + result = await self._run(build_branches(), cwd=cwd, envs=envs, timeout=timeout) + _check_result(result, op="branches") + return parse_branches(result.stdout) + + async def create_branch( + self, + name: str, + *, + start_point: str | None = None, + cwd: str | None = None, + envs: dict[str, str] | None = None, + timeout: int | None = 30, + ) -> CommandResult: + """Create and check out a new branch.""" + argv = build_create_branch(name, start_point=start_point) + result = await self._run(argv, cwd=cwd, envs=envs, timeout=timeout) + _check_result(result, op="create_branch") + return result + + async def checkout_branch( + self, + name: str, + *, + cwd: str | None = None, + envs: dict[str, str] | None = None, + timeout: int | None = 30, + ) -> CommandResult: + """Check out an existing branch.""" + argv = build_checkout(name) + result = await self._run(argv, cwd=cwd, envs=envs, timeout=timeout) + _check_result(result, op="checkout_branch") + return result + + async def delete_branch( + self, + name: str, + *, + force: bool = False, + cwd: str | None = None, + envs: dict[str, str] | None = None, + timeout: int | None = 30, + ) -> CommandResult: + """Delete a branch.""" + argv = build_delete_branch(name, force=force) + result = await self._run(argv, cwd=cwd, envs=envs, timeout=timeout) + _check_result(result, op="delete_branch") + return result + + # ── Remotes ──────────────────────────────────────────────── + + async def remote_add( + self, + name: str, + url: str, + *, + fetch: bool = False, + cwd: str | None = None, + envs: dict[str, str] | None = None, + timeout: int | None = 30, + ) -> CommandResult: + """Add a remote.""" + argv = build_remote_add(name, url, fetch=fetch) + result = await self._run(argv, cwd=cwd, envs=envs, timeout=timeout) + _check_result(result, op="remote_add") + return result + + async def remote_get( + self, + name: str = "origin", + *, + cwd: str | None = None, + envs: dict[str, str] | None = None, + timeout: int | None = 30, + ) -> str | None: + """Get the URL of a remote. Returns ``None`` if not found.""" + result = await self._run( + build_remote_get_url(name), cwd=cwd, envs=envs, timeout=timeout + ) + if result.exit_code != 0: + return None + url = result.stdout.strip() + return url or None + + # ── Reset and restore ────────────────────────────────────── + + async def reset( + self, + *, + mode: str | None = None, + ref: str | None = None, + paths: list[str] | None = None, + cwd: str | None = None, + envs: dict[str, str] | None = None, + timeout: int | None = 30, + ) -> CommandResult: + """Reset the current HEAD.""" + argv = build_reset(mode=mode, ref=ref, paths=paths) + result = await self._run(argv, cwd=cwd, envs=envs, timeout=timeout) + _check_result(result, op="reset") + return result + + async def restore( + self, + paths: list[str], + *, + staged: bool = False, + worktree: bool = False, + source: str | None = None, + cwd: str | None = None, + envs: dict[str, str] | None = None, + timeout: int | None = 30, + ) -> CommandResult: + """Restore working-tree files or unstage changes.""" + argv = build_restore(paths, staged=staged, worktree=worktree, source=source) + result = await self._run(argv, cwd=cwd, envs=envs, timeout=timeout) + _check_result(result, op="restore") + return result + + # ── Configuration ────────────────────────────────────────── + + async def set_config( + self, + key: str, + value: str, + *, + scope: str = "local", + cwd: str | None = None, + envs: dict[str, str] | None = None, + timeout: int | None = 30, + ) -> CommandResult: + """Set a git config value.""" + argv = build_config_set(key, value, scope=scope, repo_path=cwd) + result = await self._run(argv, cwd=cwd, envs=envs, timeout=timeout) + _check_result(result, op="set_config") + return result + + async def get_config( + self, + key: str, + *, + scope: str = "local", + cwd: str | None = None, + envs: dict[str, str] | None = None, + timeout: int | None = 30, + ) -> str | None: + """Get a git config value. Returns ``None`` if not set.""" + argv = build_config_get(key, scope=scope, repo_path=cwd) + result = await self._run(argv, cwd=cwd, envs=envs, timeout=timeout) + if result.exit_code != 0: + return None + val = result.stdout.strip() + return val or None + + async def configure_user( + self, + name: str, + email: str, + *, + scope: str = "global", + cwd: str | None = None, + envs: dict[str, str] | None = None, + timeout: int | None = 30, + ) -> None: + """Configure git user name and email.""" + if not name or not email: + raise ValueError("Both name and email are required.") + await self.set_config( + "user.name", name, scope=scope, cwd=cwd, envs=envs, timeout=timeout + ) + await self.set_config( + "user.email", email, scope=scope, cwd=cwd, envs=envs, timeout=timeout + ) + + async def dangerously_authenticate( + self, + username: str, + password: str, + host: str = "github.com", + protocol: str = "https", + *, + cwd: str | None = None, + envs: dict[str, str] | None = None, + timeout: int | None = 30, + ) -> None: + """Persist git credentials via the credential store. + + .. warning:: + + Credentials are written in plain text to the capsule + filesystem. Prefer per-operation ``username``/``password`` + parameters instead. + """ + if not username or not password: + raise ValueError("Both username and password are required.") + await self.set_config( + "credential.helper", + "store", + scope="global", + cwd=cwd, + envs=envs, + timeout=timeout, + ) + cmd = build_credential_approve_cmd( + username=username, + password=password, + host=host, + protocol=protocol, + ) + result = await self._run_shell(cmd, cwd=cwd, envs=envs, timeout=timeout) + _check_result(result, op="dangerously_authenticate") + + # ── Credential helper for push/pull ──────────────────────── + + async def _with_remote_credentials( + self, + *, + remote: str, + username: str, + password: str, + operation: Callable[[], Awaitable[CommandResult]], + cwd: str | None, + envs: dict[str, str] | None, + timeout: int | None, + op: str, + ) -> CommandResult: + """Temporarily embed credentials in a remote URL, run an operation, + then restore the original URL. + """ + original_url = await self.remote_get( + remote, cwd=cwd, envs=envs, timeout=timeout + ) + if not original_url: + raise GitCommandError( + f"Remote '{remote}' not found.", + stderr="", + exit_code=1, + ) + + credential_url = embed_credentials(original_url, username, password) + await self._run( + build_remote_set_url(remote, credential_url), + cwd=cwd, + envs=envs, + timeout=timeout, + ) + + op_error: Exception | None = None + result: CommandResult | None = None + try: + result = await operation() + _check_result(result, op=op) + except Exception as err: + op_error = err + + restore_error: Exception | None = None + try: + await self._run( + build_remote_set_url(remote, original_url), + cwd=cwd, + envs=envs, + timeout=timeout, + ) + except Exception as err: + restore_error = err + + if op_error: + raise op_error + if restore_error: + raise restore_error + + assert result is not None + return result diff --git a/src/wrenn/_git/_auth.py b/src/wrenn/_git/_auth.py new file mode 100644 index 0000000..af3d267 --- /dev/null +++ b/src/wrenn/_git/_auth.py @@ -0,0 +1,104 @@ +from __future__ import annotations + +import shlex +from urllib.parse import urlparse, urlunparse + + +def embed_credentials(url: str, username: str, password: str) -> str: + """Embed HTTP(S) credentials into a git URL. + + Args: + url: Git repository URL. + username: Username for authentication. + password: Password or personal access token. + + Returns: + URL with ``username:password@`` embedded in the netloc. + + Raises: + ValueError: If the URL scheme is not ``http`` or ``https``. + """ + parsed = urlparse(url) + if parsed.scheme not in ("http", "https"): + raise ValueError("Only http(s) URLs support embedded credentials.") + netloc = f"{username}:{password}@{parsed.hostname}" + if parsed.port: + netloc = f"{netloc}:{parsed.port}" + return urlunparse(parsed._replace(netloc=netloc)) + + +def strip_credentials(url: str) -> str: + """Remove embedded credentials from a git URL. + + Args: + url: Git repository URL, possibly with credentials. + + Returns: + URL with credentials removed. Non-HTTP(S) URLs are returned + unchanged. + """ + parsed = urlparse(url) + if parsed.scheme not in ("http", "https"): + return url + if not parsed.username and not parsed.password: + return url + host = parsed.hostname or "" + if parsed.port: + host = f"{host}:{parsed.port}" + return urlunparse(parsed._replace(netloc=host)) + + +def is_auth_error(stderr: str) -> bool: + """Check whether git stderr indicates an authentication failure. + + Args: + stderr: Combined stderr output from a git command. + + Returns: + ``True`` if any known auth-failure pattern is found. + """ + lower = stderr.lower() + patterns = ( + "authentication failed", + "terminal prompts disabled", + "could not read username", + "invalid username or password", + "access denied", + "permission denied", + "not authorized", + ) + return any(p in lower for p in patterns) + + +def build_credential_approve_cmd( + username: str, + password: str, + host: str = "github.com", + protocol: str = "https", +) -> str: + """Build a shell command that pipes credentials into ``git credential approve``. + + Args: + username: Git username. + password: Password or personal access token. + host: Target host. Defaults to ``"github.com"``. + protocol: Protocol. Defaults to ``"https"``. + + Returns: + A shell command string safe to pass to ``commands.run()``. + """ + if "\n" in username or "\n" in password: + raise ValueError("Credentials must not contain newline characters.") + target_host = host.strip() or "github.com" + target_protocol = protocol.strip() or "https" + credential_input = "\n".join( + [ + f"protocol={target_protocol}", + f"host={target_host}", + f"username={username}", + f"password={password}", + "", + "", + ] + ) + return f"printf %s {shlex.quote(credential_input)} | git credential approve" diff --git a/src/wrenn/_git/_cmd.py b/src/wrenn/_git/_cmd.py new file mode 100644 index 0000000..8e929bf --- /dev/null +++ b/src/wrenn/_git/_cmd.py @@ -0,0 +1,499 @@ +"""Pure functions that build git argument lists and parse git output. + +No I/O, no network, no imports from ``wrenn``. Every ``build_*`` function +returns a ``list[str]`` suitable for ``shlex.join()``. Every ``parse_*`` +function takes raw stdout and returns a typed structure. +""" + +from __future__ import annotations + +import re +from dataclasses import dataclass, field + + +# ── Data types ───────────────────────────────────────────────────── + + +@dataclass +class FileStatus: + """A single entry from ``git status --porcelain=v1``. + + Attributes: + path (str): File path relative to the repository root. + index_status (str): Index (staged) status character. + work_tree_status (str): Working-tree status character. + renamed_from (str | None): Original path when status is a rename. + """ + + path: str + index_status: str + work_tree_status: str + renamed_from: str | None = None + + @property + def staged(self) -> bool: + """Whether the change is staged in the index.""" + return self.index_status not in (" ", "?") + + @property + def status(self) -> str: + """Normalized human-readable status label.""" + return _derive_status(self.index_status, self.work_tree_status) + + +@dataclass +class GitStatus: + """Parsed output of ``git status --porcelain=v1 --branch``. + + Attributes: + branch (str | None): Current branch name, or ``None`` if detached. + upstream (str | None): Upstream tracking branch. + ahead (int): Commits ahead of upstream. + behind (int): Commits behind upstream. + detached (bool): Whether HEAD is detached. + files (list[FileStatus]): Per-file status entries. + """ + + branch: str | None = None + upstream: str | None = None + ahead: int = 0 + behind: int = 0 + detached: bool = False + files: list[FileStatus] = field(default_factory=list) + + @property + def is_clean(self) -> bool: + """``True`` when there are no changed or untracked files.""" + return len(self.files) == 0 + + @property + def has_staged(self) -> bool: + """``True`` when at least one file has staged changes.""" + return any(f.staged for f in self.files) + + @property + def has_untracked(self) -> bool: + """``True`` when at least one file is untracked.""" + return any(f.status == "untracked" for f in self.files) + + @property + def has_conflicts(self) -> bool: + """``True`` when at least one file has merge conflicts.""" + return any(f.status == "conflict" for f in self.files) + + +@dataclass +class GitBranch: + """A single branch entry. + + Attributes: + name (str): Branch name (short ref). + is_current (bool): Whether this is the checked-out branch. + """ + + name: str + is_current: bool = False + + +# ── Argument builders ────────────────────────────────────────────── + + +def build_clone( + url: str, + dest: str | None = None, + *, + branch: str | None = None, + depth: int | None = None, +) -> list[str]: + """Build ``git clone`` arguments.""" + args = ["git", "clone"] + if branch: + args.extend(["--branch", branch, "--single-branch"]) + if depth is not None: + args.extend(["--depth", str(depth)]) + args.append(url) + if dest: + args.append(dest) + return args + + +def build_init( + path: str = ".", + *, + bare: bool = False, + initial_branch: str | None = None, +) -> list[str]: + """Build ``git init`` arguments.""" + args = ["git", "init"] + if initial_branch: + args.extend(["--initial-branch", initial_branch]) + if bare: + args.append("--bare") + args.append(path) + return args + + +def build_add( + paths: list[str] | None = None, + *, + all: bool = False, +) -> list[str]: + """Build ``git add`` arguments.""" + args = ["git", "add"] + if not paths: + args.append("-A" if all else ".") + else: + args.append("--") + args.extend(paths) + return args + + +def build_commit( + message: str, + *, + allow_empty: bool = False, + author_name: str | None = None, + author_email: str | None = None, +) -> list[str]: + """Build ``git commit`` arguments.""" + args = ["git"] + if author_name: + args.extend(["-c", f"user.name={author_name}"]) + if author_email: + args.extend(["-c", f"user.email={author_email}"]) + args.extend(["commit", "-m", message]) + if allow_empty: + args.append("--allow-empty") + return args + + +def build_push( + remote: str = "origin", + branch: str | None = None, + *, + force: bool = False, + set_upstream: bool = False, +) -> list[str]: + """Build ``git push`` arguments.""" + args = ["git", "push"] + if force: + args.append("--force") + if set_upstream: + args.append("--set-upstream") + args.append(remote) + if branch: + args.append(branch) + return args + + +def build_pull( + remote: str = "origin", + branch: str | None = None, + *, + rebase: bool = False, + ff_only: bool = False, +) -> list[str]: + """Build ``git pull`` arguments.""" + args = ["git", "pull"] + if rebase: + args.append("--rebase") + if ff_only: + args.append("--ff-only") + args.append(remote) + if branch: + args.append(branch) + return args + + +def build_status() -> list[str]: + """Build ``git status`` arguments for porcelain parsing.""" + return ["git", "status", "--porcelain=v1", "--branch"] + + +def build_branches() -> list[str]: + """Build ``git branch`` arguments for structured parsing.""" + return ["git", "branch", "--format=%(refname:short)\t%(HEAD)"] + + +def build_create_branch( + name: str, + *, + start_point: str | None = None, +) -> list[str]: + """Build ``git checkout -b`` arguments.""" + args = ["git", "checkout", "-b", name] + if start_point: + args.append(start_point) + return args + + +def build_checkout(name: str) -> list[str]: + """Build ``git checkout`` arguments.""" + return ["git", "checkout", name] + + +def build_delete_branch( + name: str, + *, + force: bool = False, +) -> list[str]: + """Build ``git branch -d/-D`` arguments.""" + return ["git", "branch", "-D" if force else "-d", name] + + +def build_remote_add(name: str, url: str, *, fetch: bool = False) -> list[str]: + """Build ``git remote add`` arguments.""" + args = ["git", "remote", "add"] + if fetch: + args.append("-f") + args.extend([name, url]) + return args + + +def build_remote_get_url(name: str = "origin") -> list[str]: + """Build ``git remote get-url`` arguments.""" + return ["git", "remote", "get-url", name] + + +def build_remote_set_url(name: str, url: str) -> list[str]: + """Build ``git remote set-url`` arguments.""" + return ["git", "remote", "set-url", name, url] + + +def build_reset( + *, + mode: str | None = None, + ref: str | None = None, + paths: list[str] | None = None, +) -> list[str]: + """Build ``git reset`` arguments. + + Args: + mode: Reset mode (``soft``, ``mixed``, ``hard``, ``merge``, ``keep``). + ref: Commit, branch, or ref to reset to. + paths: Paths to reset (mutually exclusive with ``mode``). + """ + _ALLOWED_MODES = {"soft", "mixed", "hard", "merge", "keep"} + if mode and mode not in _ALLOWED_MODES: + raise ValueError( + f"Reset mode must be one of {', '.join(sorted(_ALLOWED_MODES))}." + ) + args = ["git", "reset"] + if mode: + args.append(f"--{mode}") + if ref: + args.append(ref) + if paths: + args.append("--") + args.extend(paths) + return args + + +def build_restore( + paths: list[str], + *, + staged: bool = False, + worktree: bool = False, + source: str | None = None, +) -> list[str]: + """Build ``git restore`` arguments. + + Args: + paths: Paths to restore. + staged: Restore the index (unstage). + worktree: Restore working-tree files. + source: Commit or ref to restore from. + """ + if not paths: + raise ValueError("At least one path is required.") + if not staged and not worktree: + worktree = True + args = ["git", "restore"] + if worktree: + args.append("--worktree") + if staged: + args.append("--staged") + if source: + args.extend(["--source", source]) + args.append("--") + args.extend(paths) + return args + + +def build_config_set( + key: str, + value: str, + *, + scope: str = "local", + repo_path: str | None = None, +) -> list[str]: + """Build ``git config`` set arguments.""" + scope_flag = _resolve_scope_flag(scope) + args = ["git"] + if scope == "local" and repo_path: + args.extend(["-C", repo_path]) + args.extend(["config", scope_flag, key, value]) + return args + + +def build_config_get( + key: str, + *, + scope: str = "local", + repo_path: str | None = None, +) -> list[str]: + """Build ``git config --get`` arguments.""" + scope_flag = _resolve_scope_flag(scope) + args = ["git"] + if scope == "local" and repo_path: + args.extend(["-C", repo_path]) + args.extend(["config", scope_flag, "--get", key]) + return args + + +def build_has_upstream() -> list[str]: + """Build arguments to check if current branch has upstream tracking.""" + return ["git", "rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}"] + + +# ── Parsers ──────────────────────────────────────────────────────── + + +def parse_status(stdout: str) -> GitStatus: + """Parse ``git status --porcelain=v1 --branch`` output. + + Args: + stdout: Raw stdout from the git status command. + + Returns: + Parsed :class:`GitStatus`. + """ + lines = [line for line in stdout.split("\n") if line.rstrip()] + if not lines: + return GitStatus() + + status = GitStatus() + + branch_line = lines[0] + if branch_line.startswith("## "): + _parse_branch_line(branch_line[3:], status) + + for line in lines[1:]: + if line.startswith("?? "): + status.files.append( + FileStatus( + path=line[3:], + index_status="?", + work_tree_status="?", + ) + ) + continue + + if len(line) < 4: + continue + + idx = line[0] + wt = line[1] + path = line[3:] + renamed_from = None + if " -> " in path: + renamed_from, path = path.split(" -> ", 1) + + status.files.append( + FileStatus( + path=path, + index_status=idx, + work_tree_status=wt, + renamed_from=renamed_from, + ) + ) + + return status + + +def parse_branches(stdout: str) -> list[GitBranch]: + """Parse ``git branch --format=%(refname:short)\\t%(HEAD)`` output. + + Args: + stdout: Raw stdout from the git branch command. + + Returns: + List of :class:`GitBranch`. + """ + branches: list[GitBranch] = [] + for line in stdout.split("\n"): + line = line.strip() + if not line: + continue + parts = line.split("\t") + name = parts[0] + is_current = len(parts) > 1 and parts[1] == "*" + branches.append(GitBranch(name=name, is_current=is_current)) + return branches + + +# ── Internal helpers ─────────────────────────────────────────────── + + +def _resolve_scope_flag(scope: str) -> str: + """Convert a scope name to a git config flag.""" + scope = scope.strip().lower() + if scope == "local": + return "--local" + if scope == "global": + return "--global" + if scope == "system": + return "--system" + raise ValueError("Git config scope must be one of: local, global, system.") + + +def _parse_branch_line(info: str, status: GitStatus) -> None: + """Parse the ``## branch...upstream [ahead N, behind M]`` header.""" + ahead_start = info.find(" [") + branch_part = info if ahead_start == -1 else info[:ahead_start] + ahead_part = None if ahead_start == -1 else info[ahead_start + 2 : -1] + + if branch_part.startswith("HEAD (detached at "): + status.detached = True + status.branch = branch_part[18:].rstrip(")") + elif "detached" in branch_part or branch_part.startswith("HEAD"): + status.detached = True + elif "..." in branch_part: + local, remote = branch_part.split("...", 1) + status.branch = local or None + status.upstream = remote or None + else: + name = branch_part.replace("No commits yet on ", "").replace( + "Initial commit on ", "" + ) + status.branch = name or None + + if ahead_part: + m = re.search(r"ahead (\d+)", ahead_part) + if m: + status.ahead = int(m.group(1)) + m = re.search(r"behind (\d+)", ahead_part) + if m: + status.behind = int(m.group(1)) + + +def _derive_status(index_status: str, work_tree_status: str) -> str: + """Derive a normalized status label from porcelain XY characters.""" + chars = {index_status, work_tree_status} + if "U" in chars: + return "conflict" + if "R" in chars: + return "renamed" + if "C" in chars: + return "copied" + if "D" in chars: + return "deleted" + if "A" in chars: + return "added" + if "M" in chars: + return "modified" + if "T" in chars: + return "typechange" + if "?" in chars: + return "untracked" + return "unknown" diff --git a/src/wrenn/_git/exceptions.py b/src/wrenn/_git/exceptions.py new file mode 100644 index 0000000..50d6ec1 --- /dev/null +++ b/src/wrenn/_git/exceptions.py @@ -0,0 +1,28 @@ +from __future__ import annotations + + +class GitError(Exception): + """Base exception for all git operations inside a capsule. + + Not a subclass of :class:`WrennError` because git errors originate + from a process exit code, not an HTTP response. + + Attributes: + message (str): Human-readable error description. + stderr (str): Raw stderr output from the git process. + exit_code (int): Process exit code. + """ + + def __init__(self, message: str, *, stderr: str = "", exit_code: int = -1) -> None: + self.message = message + self.stderr = stderr + self.exit_code = exit_code + super().__init__(message) + + +class GitCommandError(GitError): + """A git command exited with a non-zero exit code.""" + + +class GitAuthError(GitError): + """Authentication failed when communicating with a remote.""" diff --git a/src/wrenn/async_capsule.py b/src/wrenn/async_capsule.py new file mode 100644 index 0000000..3e92de7 --- /dev/null +++ b/src/wrenn/async_capsule.py @@ -0,0 +1,395 @@ +from __future__ import annotations + +import asyncio +import time +from collections.abc import AsyncIterator +from contextlib import asynccontextmanager + +import httpx_ws + +from wrenn._git import AsyncGit +from wrenn.capsule import _DualMethod, _build_proxy_url +from wrenn.client import AsyncWrennClient +from wrenn.commands import AsyncCommands +from wrenn.files import AsyncFiles +from wrenn.models import Capsule as CapsuleModel +from wrenn.models import Status, Template +from wrenn.pty import AsyncPtySession + + +class AsyncCapsule: + """Async Wrenn capsule with e2b-compatible interface. + + Create via classmethod:: + + capsule = await AsyncCapsule.create(template="minimal") + + Use as async context manager:: + + async with await AsyncCapsule.create() as capsule: + await capsule.commands.run("echo hello") + """ + + def __init__( + self, + *, + _capsule_id: str, + _client: AsyncWrennClient, + _info: CapsuleModel | None = None, + ) -> None: + self._id = _capsule_id + self._client = _client + self._info = _info + + self.commands = AsyncCommands(_capsule_id, _client.http) + self.files = AsyncFiles(_capsule_id, _client.http) + self.git = AsyncGit(_capsule_id, _client.http) + + # ── Properties ────────────────────────────────────────────── + + @property + def capsule_id(self) -> str: + """The capsule's unique identifier. + + Returns: + str: Capsule ID assigned by the Wrenn API. + """ + return self._id + + @property + def info(self) -> CapsuleModel | None: + """Cached capsule metadata from the last API call. + + Returns: + CapsuleModel | None: The last-fetched capsule model, or ``None`` + if the capsule was connected without an initial fetch. + """ + return self._info + + # ── Factory classmethods ──────────────────────────────────── + + @classmethod + async def create( + cls, + template: str | None = None, + vcpus: int | None = None, + memory_mb: int | None = None, + timeout: int | None = None, + *, + wait: bool = False, + api_key: str | None = None, + base_url: str | None = None, + ) -> AsyncCapsule: + """Create a new capsule. + + Args: + template (str | None): Template name to boot from. + vcpus (int | None): Number of virtual CPUs. + memory_mb (int | None): Memory in MiB. + timeout (int | None): Inactivity TTL in seconds before auto-pause. + wait (bool): Await until the capsule reaches ``running`` status. + api_key (str | None): Wrenn API key. Falls back to + ``WRENN_API_KEY`` env var. + base_url (str | None): API base URL override. + + Returns: + AsyncCapsule: A new capsule instance. + """ + client = AsyncWrennClient(api_key=api_key, base_url=base_url) + info = await client.capsules.create( + template=template, + vcpus=vcpus, + memory_mb=memory_mb, + timeout_sec=timeout, + ) + capsule = cls( + _capsule_id=info.id, + _client=client, + _info=info, + ) + if wait: + await capsule.wait_ready() + return capsule + + @classmethod + async def connect( + cls, + capsule_id: str, + *, + api_key: str | None = None, + base_url: str | None = None, + ) -> AsyncCapsule: + """Connect to an existing capsule, resuming it if paused. + + Args: + capsule_id (str): ID of the capsule to connect to. + api_key (str | None): Wrenn API key. Falls back to + ``WRENN_API_KEY`` env var. + base_url (str | None): API base URL override. + + Returns: + AsyncCapsule: A capsule instance bound to the existing capsule. + + Raises: + WrennNotFoundError: If no capsule with the given ID exists. + """ + client = AsyncWrennClient(api_key=api_key, base_url=base_url) + info = await client.capsules.get(capsule_id) + + if info.status == Status.paused: + info = await client.capsules.resume(capsule_id) + + return cls( + _capsule_id=capsule_id, + _client=client, + _info=info, + ) + + # ── Dual instance/static lifecycle ────────────────────────── + + destroy = _DualMethod("_instance_destroy", "_static_destroy") + pause = _DualMethod("_instance_pause", "_static_pause") + resume = _DualMethod("_instance_resume", "_static_resume") + get_info = _DualMethod("_instance_get_info", "_static_get_info") + + async def _instance_destroy(self) -> None: + await self._client.capsules.destroy(self._id) + + @classmethod + async def _static_destroy( + cls, + capsule_id: str, + *, + api_key: str | None = None, + base_url: str | None = None, + ) -> None: + async with AsyncWrennClient(api_key=api_key, base_url=base_url) as client: + await client.capsules.destroy(capsule_id) + + async def _instance_pause(self) -> CapsuleModel: + self._info = await self._client.capsules.pause(self._id) + return self._info + + @classmethod + async def _static_pause( + cls, + capsule_id: str, + *, + api_key: str | None = None, + base_url: str | None = None, + ) -> CapsuleModel: + async with AsyncWrennClient(api_key=api_key, base_url=base_url) as client: + return await client.capsules.pause(capsule_id) + + async def _instance_resume(self) -> CapsuleModel: + self._info = await self._client.capsules.resume(self._id) + return self._info + + @classmethod + async def _static_resume( + cls, + capsule_id: str, + *, + api_key: str | None = None, + base_url: str | None = None, + ) -> CapsuleModel: + async with AsyncWrennClient(api_key=api_key, base_url=base_url) as client: + return await client.capsules.resume(capsule_id) + + async def _instance_get_info(self) -> CapsuleModel: + self._info = await self._client.capsules.get(self._id) + return self._info + + @classmethod + async def _static_get_info( + cls, + capsule_id: str, + *, + api_key: str | None = None, + base_url: str | None = None, + ) -> CapsuleModel: + async with AsyncWrennClient(api_key=api_key, base_url=base_url) as client: + return await client.capsules.get(capsule_id) + + # ── Instance-only methods ─────────────────────────────────── + + async def ping(self) -> None: + """Reset the capsule inactivity timer. + + Call this to prevent the capsule from being auto-paused when the + inactivity TTL is set. + """ + await self._client.capsules.ping(self._id) + + async def wait_ready(self, timeout: float = 30, interval: float = 0.5) -> None: + """Await until the capsule status is ``running``. + + Args: + timeout (float): Maximum seconds to wait. Defaults to ``30``. + interval (float): Polling interval in seconds. Defaults to ``0.5``. + + Raises: + TimeoutError: If the capsule does not reach ``running`` state + within ``timeout`` seconds. + RuntimeError: If the capsule enters an error, stopped, or paused + state while waiting. + """ + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + info = await self._client.capsules.get(self._id) + if info.status == Status.running: + self._info = info + return + if info.status in (Status.error, Status.stopped, Status.paused): + raise RuntimeError(f"Capsule entered {info.status} state while waiting") + await asyncio.sleep(interval) + raise TimeoutError(f"Capsule {self._id} did not become ready within {timeout}s") + + async def is_running(self) -> bool: + """Check whether the capsule is currently running. + + Makes a live API call to fetch current status. + + Returns: + bool: ``True`` if the capsule status is ``running``. + """ + info = await self._instance_get_info() + return info.status == Status.running + + # ── Static list ───────────────────────────────────────────── + + @classmethod + async def list( + cls, + *, + api_key: str | None = None, + base_url: str | None = None, + ) -> list[CapsuleModel]: + """List all capsules belonging to the team. + + Args: + api_key (str | None): Wrenn API key. Falls back to + ``WRENN_API_KEY`` env var. + base_url (str | None): API base URL override. + + Returns: + list[CapsuleModel]: All capsules for the authenticated team. + """ + async with AsyncWrennClient(api_key=api_key, base_url=base_url) as client: + return await client.capsules.list() + + # ── PTY ───────────────────────────────────────────────────── + + @asynccontextmanager + async def pty( + self, + cmd: str = "/bin/bash", + args: list[str] | None = None, + cols: int = 80, + rows: int = 24, + envs: dict[str, str] | None = None, + cwd: str | None = None, + ) -> AsyncIterator[AsyncPtySession]: + """Open an async interactive PTY session backed by a WebSocket. + + Use as an async context manager and async iterate over + :class:`PtyEvent` objects:: + + async with capsule.pty() as term: + await term.write(b"echo hello\\n") + async for event in term: + if event.type == "output": + print(event.data.decode()) + + Args: + cmd (str): Command to run inside the PTY. Defaults to + ``"/bin/bash"``. + args (list[str] | None): Additional arguments for ``cmd``. + cols (int): Initial terminal column count. Defaults to ``80``. + rows (int): Initial terminal row count. Defaults to ``24``. + envs (dict[str, str] | None): Additional environment variables + to inject into the process. + cwd (str | None): Working directory for the process. + + Yields: + AsyncPtySession: An interactive async PTY session. + """ + async with httpx_ws.aconnect_ws( + f"/v1/capsules/{self._id}/pty", client=self._client.http + ) as ws: + session = AsyncPtySession(ws, self._id) + await session._send_start( + cmd=cmd, args=args, cols=cols, rows=rows, envs=envs, cwd=cwd + ) + yield session + + @asynccontextmanager + async def pty_connect(self, tag: str) -> AsyncIterator[AsyncPtySession]: + """Reconnect to an existing PTY session by tag. + + Args: + tag (str): Session tag returned in the ``started`` PTY event. + + Yields: + AsyncPtySession: The reconnected async PTY session. + """ + async with httpx_ws.aconnect_ws( + f"/v1/capsules/{self._id}/pty", client=self._client.http + ) as ws: + session = AsyncPtySession(ws, self._id) + await session._send_connect(tag) + yield session + + # ── Proxy helpers ─────────────────────────────────────────── + + def get_url(self, port: int) -> str: + """Get the proxy URL for a port exposed inside this capsule. + + Args: + port (int): Port number to proxy. + + Returns: + str: A ``wss://`` (or ``ws://``) URL that proxies to the given + port inside the capsule. + """ + return _build_proxy_url(self._client._base_url, self._id, port) + + # ── Snapshots ─────────────────────────────────────────────── + + async def create_snapshot( + self, name: str | None = None, overwrite: bool = False + ) -> Template: + """Create a snapshot template from this capsule's current state. + + Args: + name (str | None): Name for the snapshot template. Auto-generated + if not provided. + overwrite (bool): If ``True``, overwrite an existing template with + the same name. Defaults to ``False``. + + Returns: + Template: The created snapshot template. + """ + return await self._client.snapshots.create( + capsule_id=self._id, name=name, overwrite=overwrite + ) + + # ── Context manager ───────────────────────────────────────── + + async def __aenter__(self) -> AsyncCapsule: + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: object, + ) -> None: + try: + await self._instance_destroy() + except Exception: + pass + try: + await self._client.aclose() + except Exception: + pass diff --git a/src/wrenn/capsule.py b/src/wrenn/capsule.py new file mode 100644 index 0000000..400409f --- /dev/null +++ b/src/wrenn/capsule.py @@ -0,0 +1,470 @@ +from __future__ import annotations + +import time +from collections.abc import Iterator +from contextlib import contextmanager +from typing import Any + +import httpx +import httpx_ws + +from wrenn._git import Git +from wrenn.client import WrennClient +from wrenn.commands import Commands +from wrenn.files import Files +from wrenn.models import Capsule as CapsuleModel +from wrenn.models import Status, Template +from wrenn.pty import PtySession + + +def _build_proxy_url(base_url: str, capsule_id: str | None, port: int) -> str: + parsed = httpx.URL(base_url) + host = parsed.host + if parsed.port: + host = f"{host}:{parsed.port}" + scheme = "ws" if parsed.scheme == "http" else "wss" + return f"{scheme}://{port}-{capsule_id}.{host}" + + +class _DualMethod: + """Descriptor that dispatches to instance method or classmethod depending on call site.""" + + def __init__(self, instance_fn_name: str, static_fn_name: str) -> None: + self._ifn = instance_fn_name + self._sfn = static_fn_name + + def __set_name__(self, owner: type, name: str) -> None: + self._name = name + + def __get__(self, obj: Any, cls: type) -> Any: + if obj is None: + return getattr(cls, self._sfn) + return getattr(obj, self._ifn) + + +class Capsule: + """A Wrenn capsule (sandbox) with e2b-compatible interface. + + Create directly:: + + capsule = Capsule(api_key="wrn_...") + capsule = Capsule(template="minimal") # reads WRENN_API_KEY env + + Or via classmethod:: + + capsule = Capsule.create(template="minimal") + + Use as context manager for automatic cleanup:: + + with Capsule() as capsule: + capsule.commands.run("echo hello") + """ + + def __init__( + self, + template: str | None = None, + vcpus: int | None = None, + memory_mb: int | None = None, + timeout: int | None = None, + *, + wait: bool = False, + api_key: str | None = None, + base_url: str | None = None, + # Private: used by classmethods to skip creation + _capsule_id: str | None = None, + _client: WrennClient | None = None, + _info: CapsuleModel | None = None, + ) -> None: + """Create and start a new capsule. + + Args: + template (str | None): Template name to boot from. Defaults to + the server-side default (``"minimal"``). + vcpus (int | None): Number of virtual CPUs. Defaults to the + server-side default. + memory_mb (int | None): Memory in MiB. Defaults to the + server-side default. + timeout (int | None): Inactivity TTL in seconds before the capsule + is auto-paused. ``0`` disables auto-pause. + wait (bool): If ``True``, block until the capsule status is + ``running`` before returning. + api_key (str | None): Wrenn API key (``wrn_...``). Falls back to + the ``WRENN_API_KEY`` environment variable. + base_url (str | None): Wrenn API base URL. Falls back to + ``WRENN_BASE_URL`` or the default production endpoint. + """ + if _capsule_id is not None: + # Internal construction path (from create/connect classmethods) + assert _client is not None + self._id = _capsule_id + self._client = _client + self._info = _info + else: + # Public construction: create a capsule immediately + self._client = WrennClient(api_key=api_key, base_url=base_url) + self._info = self._client.capsules.create( + template=template, + vcpus=vcpus, + memory_mb=memory_mb, + timeout_sec=timeout, + ) + self._id = self._info.id + + self.commands = Commands(self._id, self._client.http) + self.files = Files(self._id, self._client.http) + self.git = Git(self._id, self._client.http) + + if wait: + self.wait_ready() + + # ── Properties ────────────────────────────────────────────── + + @property + def capsule_id(self) -> str: + """The capsule's unique identifier. + + Returns: + str: Capsule ID assigned by the Wrenn API. + """ + return self._id + + @property + def info(self) -> CapsuleModel | None: + """Cached capsule metadata from the last API call. + + Returns: + CapsuleModel | None: The last-fetched capsule model, or ``None`` + if the capsule was connected without an initial fetch. + """ + return self._info + + # ── Factory classmethods ──────────────────────────────────── + + @classmethod + def create( + cls, + template: str | None = None, + vcpus: int | None = None, + memory_mb: int | None = None, + timeout: int | None = None, + *, + wait: bool = False, + api_key: str | None = None, + base_url: str | None = None, + ) -> Capsule: + """Create a new capsule. + + Equivalent to calling ``Capsule(...)`` directly. + + Args: + template (str | None): Template name to boot from. + vcpus (int | None): Number of virtual CPUs. + memory_mb (int | None): Memory in MiB. + timeout (int | None): Inactivity TTL in seconds before auto-pause. + wait (bool): Block until the capsule reaches ``running`` status. + api_key (str | None): Wrenn API key. Falls back to + ``WRENN_API_KEY`` env var. + base_url (str | None): API base URL override. + + Returns: + Capsule: A new capsule instance. + """ + return cls( + template=template, + vcpus=vcpus, + memory_mb=memory_mb, + timeout=timeout, + wait=wait, + api_key=api_key, + base_url=base_url, + ) + + @classmethod + def connect( + cls, + capsule_id: str, + *, + api_key: str | None = None, + base_url: str | None = None, + ) -> Capsule: + """Connect to an existing capsule, resuming it if paused. + + Args: + capsule_id (str): ID of the capsule to connect to. + api_key (str | None): Wrenn API key. Falls back to + ``WRENN_API_KEY`` env var. + base_url (str | None): API base URL override. + + Returns: + Capsule: A capsule instance bound to the existing capsule. + + Raises: + WrennNotFoundError: If no capsule with the given ID exists. + """ + client = WrennClient(api_key=api_key, base_url=base_url) + info = client.capsules.get(capsule_id) + + if info.status == Status.paused: + info = client.capsules.resume(capsule_id) + + return cls( + _capsule_id=capsule_id, + _client=client, + _info=info, + ) + + # ── Dual instance/static lifecycle ────────────────────────── + + destroy = _DualMethod("_instance_destroy", "_static_destroy") + pause = _DualMethod("_instance_pause", "_static_pause") + resume = _DualMethod("_instance_resume", "_static_resume") + get_info = _DualMethod("_instance_get_info", "_static_get_info") + + def _instance_destroy(self) -> None: + """Destroy this capsule.""" + self._client.capsules.destroy(self._id) + + @classmethod + def _static_destroy( + cls, + capsule_id: str, + *, + api_key: str | None = None, + base_url: str | None = None, + ) -> None: + """Destroy a capsule by ID.""" + with WrennClient(api_key=api_key, base_url=base_url) as client: + client.capsules.destroy(capsule_id) + + def _instance_pause(self) -> CapsuleModel: + """Pause this capsule.""" + self._info = self._client.capsules.pause(self._id) + return self._info + + @classmethod + def _static_pause( + cls, + capsule_id: str, + *, + api_key: str | None = None, + base_url: str | None = None, + ) -> CapsuleModel: + """Pause a capsule by ID.""" + with WrennClient(api_key=api_key, base_url=base_url) as client: + return client.capsules.pause(capsule_id) + + def _instance_resume(self) -> CapsuleModel: + """Resume this capsule.""" + self._info = self._client.capsules.resume(self._id) + return self._info + + @classmethod + def _static_resume( + cls, + capsule_id: str, + *, + api_key: str | None = None, + base_url: str | None = None, + ) -> CapsuleModel: + """Resume a capsule by ID.""" + with WrennClient(api_key=api_key, base_url=base_url) as client: + return client.capsules.resume(capsule_id) + + def _instance_get_info(self) -> CapsuleModel: + """Get current info for this capsule.""" + self._info = self._client.capsules.get(self._id) + return self._info + + @classmethod + def _static_get_info( + cls, + capsule_id: str, + *, + api_key: str | None = None, + base_url: str | None = None, + ) -> CapsuleModel: + """Get capsule info by ID.""" + with WrennClient(api_key=api_key, base_url=base_url) as client: + return client.capsules.get(capsule_id) + + # ── Instance-only methods ─────────────────────────────────── + + def ping(self) -> None: + """Reset the capsule inactivity timer. + + Call this to prevent the capsule from being auto-paused when the + inactivity TTL is set. + """ + self._client.capsules.ping(self._id) + + def wait_ready(self, timeout: float = 30, interval: float = 0.5) -> None: + """Block until the capsule status is ``running``. + + Args: + timeout (float): Maximum seconds to wait. Defaults to ``30``. + interval (float): Polling interval in seconds. Defaults to ``0.5``. + + Raises: + TimeoutError: If the capsule does not reach ``running`` state + within ``timeout`` seconds. + RuntimeError: If the capsule enters an error, stopped, or paused + state while waiting. + """ + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + info = self._client.capsules.get(self._id) + if info.status == Status.running: + self._info = info + return + if info.status in (Status.error, Status.stopped, Status.paused): + raise RuntimeError(f"Capsule entered {info.status} state while waiting") + time.sleep(interval) + raise TimeoutError(f"Capsule {self._id} did not become ready within {timeout}s") + + def is_running(self) -> bool: + """Check whether the capsule is currently running. + + Makes a live API call to fetch current status. + + Returns: + bool: ``True`` if the capsule status is ``running``. + """ + info = self._instance_get_info() + return info.status == Status.running + + # ── Static list ───────────────────────────────────────────── + + @classmethod + def list( + cls, + *, + api_key: str | None = None, + base_url: str | None = None, + ) -> list[CapsuleModel]: + """List all capsules belonging to the team. + + Args: + api_key (str | None): Wrenn API key. Falls back to + ``WRENN_API_KEY`` env var. + base_url (str | None): API base URL override. + + Returns: + list[CapsuleModel]: All capsules for the authenticated team. + """ + with WrennClient(api_key=api_key, base_url=base_url) as client: + return client.capsules.list() + + # ── PTY ───────────────────────────────────────────────────── + + @contextmanager + def pty( + self, + cmd: str = "/bin/bash", + args: list[str] | None = None, + cols: int = 80, + rows: int = 24, + envs: dict[str, str] | None = None, + cwd: str | None = None, + ) -> Iterator[PtySession]: + """Open an interactive PTY session backed by a WebSocket. + + Use as a context manager and iterate over :class:`PtyEvent` objects:: + + with capsule.pty() as term: + term.write(b"echo hello\\n") + for event in term: + if event.type == "output": + print(event.data.decode()) + + Args: + cmd (str): Command to run inside the PTY. Defaults to + ``"/bin/bash"``. + args (list[str] | None): Additional arguments for ``cmd``. + cols (int): Initial terminal column count. Defaults to ``80``. + rows (int): Initial terminal row count. Defaults to ``24``. + envs (dict[str, str] | None): Additional environment variables to + inject into the process. + cwd (str | None): Working directory for the process. + + Yields: + PtySession: An interactive PTY session. + """ + with httpx_ws.connect_ws( + f"/v1/capsules/{self._id}/pty", client=self._client.http + ) as ws: + session = PtySession(ws, self._id) + session._send_start( + cmd=cmd, args=args, cols=cols, rows=rows, envs=envs, cwd=cwd + ) + yield session + + @contextmanager + def pty_connect(self, tag: str) -> Iterator[PtySession]: + """Reconnect to an existing PTY session by tag. + + Args: + tag (str): Session tag returned in the ``started`` PTY event. + + Yields: + PtySession: The reconnected PTY session. + """ + with httpx_ws.connect_ws( + f"/v1/capsules/{self._id}/pty", client=self._client.http + ) as ws: + session = PtySession(ws, self._id) + session._send_connect(tag) + yield session + + # ── Proxy helpers ─────────────────────────────────────────── + + def get_url(self, port: int) -> str: + """Get the proxy URL for a port exposed inside this capsule. + + Args: + port (int): Port number to proxy. + + Returns: + str: A ``wss://`` (or ``ws://``) URL that proxies to the given + port inside the capsule. + """ + return _build_proxy_url(self._client._base_url, self._id, port) + + # ── Snapshots ─────────────────────────────────────────────── + + def create_snapshot( + self, name: str | None = None, overwrite: bool = False + ) -> Template: + """Create a snapshot template from this capsule's current state. + + Args: + name (str | None): Name for the snapshot template. Auto-generated + if not provided. + overwrite (bool): If ``True``, overwrite an existing template with + the same name. Defaults to ``False``. + + Returns: + Template: The created snapshot template. + """ + return self._client.snapshots.create( + capsule_id=self._id, name=name, overwrite=overwrite + ) + + # ── Context manager ───────────────────────────────────────── + + def __enter__(self) -> Capsule: + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: object, + ) -> None: + try: + self._instance_destroy() + except Exception: + pass + try: + self._client.close() + except Exception: + pass diff --git a/src/wrenn/client.py b/src/wrenn/client.py new file mode 100644 index 0000000..c927396 --- /dev/null +++ b/src/wrenn/client.py @@ -0,0 +1,471 @@ +from __future__ import annotations + +import os + +import httpx + +from wrenn._config import DEFAULT_BASE_URL, ENV_API_KEY, ENV_BASE_URL +from wrenn.exceptions import handle_response +from wrenn.models import ( + Template, +) +from wrenn.models import ( + Capsule as CapsuleModel, +) + + +def _resolve_api_key(api_key: str | None) -> str: + resolved = api_key or os.environ.get(ENV_API_KEY) + if not resolved: + raise ValueError( + f"No API key provided. Pass api_key= or set the {ENV_API_KEY} environment variable." + ) + return resolved + + +class CapsulesResource: + """Sync capsule control-plane operations.""" + + def __init__(self, http: httpx.Client) -> None: + self._http = http + + def create( + self, + template: str | None = None, + vcpus: int | None = None, + memory_mb: int | None = None, + timeout_sec: int | None = None, + ) -> CapsuleModel: + """Create a new capsule. + + Args: + template (str | None): Template name to boot from. + vcpus (int | None): Number of virtual CPUs. + memory_mb (int | None): Memory in MiB. + timeout_sec (int | None): Inactivity TTL in seconds before + auto-pause. ``0`` disables auto-pause. + + Returns: + CapsuleModel: The newly created capsule. + """ + payload: dict = {} + if template is not None: + payload["template"] = template + if vcpus is not None: + payload["vcpus"] = vcpus + if memory_mb is not None: + payload["memory_mb"] = memory_mb + if timeout_sec is not None: + payload["timeout_sec"] = timeout_sec + resp = self._http.post("/v1/capsules", json=payload) + return CapsuleModel.model_validate(handle_response(resp)) + + def list(self) -> list[CapsuleModel]: + """List all capsules for the authenticated team. + + Returns: + list[CapsuleModel]: All capsules belonging to the team. + """ + resp = self._http.get("/v1/capsules") + return [CapsuleModel.model_validate(item) for item in handle_response(resp)] + + def get(self, id: str) -> CapsuleModel: + """Get a capsule by ID. + + Args: + id (str): Capsule ID. + + Returns: + CapsuleModel: Current state of the capsule. + + Raises: + WrennNotFoundError: If no capsule with the given ID exists. + """ + resp = self._http.get(f"/v1/capsules/{id}") + return CapsuleModel.model_validate(handle_response(resp)) + + def destroy(self, id: str) -> None: + """Destroy a capsule permanently. + + Args: + id (str): Capsule ID. + + Raises: + WrennNotFoundError: If no capsule with the given ID exists. + """ + resp = self._http.delete(f"/v1/capsules/{id}") + handle_response(resp) + + def pause(self, id: str) -> CapsuleModel: + """Pause a running capsule. + + Args: + id (str): Capsule ID. + + Returns: + CapsuleModel: Updated capsule state. + + Raises: + WrennNotFoundError: If no capsule with the given ID exists. + """ + resp = self._http.post(f"/v1/capsules/{id}/pause") + return CapsuleModel.model_validate(handle_response(resp)) + + def resume(self, id: str) -> CapsuleModel: + """Resume a paused capsule. + + Args: + id (str): Capsule ID. + + Returns: + CapsuleModel: Updated capsule state. + + Raises: + WrennNotFoundError: If no capsule with the given ID exists. + """ + resp = self._http.post(f"/v1/capsules/{id}/resume") + return CapsuleModel.model_validate(handle_response(resp)) + + def ping(self, id: str) -> None: + """Reset the inactivity timer for a capsule. + + Args: + id (str): Capsule ID. + + Raises: + WrennNotFoundError: If no capsule with the given ID exists. + """ + resp = self._http.post(f"/v1/capsules/{id}/ping") + handle_response(resp) + + +class AsyncCapsulesResource: + """Async capsule control-plane operations.""" + + def __init__(self, http: httpx.AsyncClient) -> None: + self._http = http + + async def create( + self, + template: str | None = None, + vcpus: int | None = None, + memory_mb: int | None = None, + timeout_sec: int | None = None, + ) -> CapsuleModel: + """Create a new capsule. + + Args: + template (str | None): Template name to boot from. + vcpus (int | None): Number of virtual CPUs. + memory_mb (int | None): Memory in MiB. + timeout_sec (int | None): Inactivity TTL in seconds before + auto-pause. ``0`` disables auto-pause. + + Returns: + CapsuleModel: The newly created capsule. + """ + payload: dict = {} + if template is not None: + payload["template"] = template + if vcpus is not None: + payload["vcpus"] = vcpus + if memory_mb is not None: + payload["memory_mb"] = memory_mb + if timeout_sec is not None: + payload["timeout_sec"] = timeout_sec + resp = await self._http.post("/v1/capsules", json=payload) + return CapsuleModel.model_validate(handle_response(resp)) + + async def list(self) -> list[CapsuleModel]: + """List all capsules for the authenticated team. + + Returns: + list[CapsuleModel]: All capsules belonging to the team. + """ + resp = await self._http.get("/v1/capsules") + return [CapsuleModel.model_validate(item) for item in handle_response(resp)] + + async def get(self, id: str) -> CapsuleModel: + """Get a capsule by ID. + + Args: + id (str): Capsule ID. + + Returns: + CapsuleModel: Current state of the capsule. + + Raises: + WrennNotFoundError: If no capsule with the given ID exists. + """ + resp = await self._http.get(f"/v1/capsules/{id}") + return CapsuleModel.model_validate(handle_response(resp)) + + async def destroy(self, id: str) -> None: + """Destroy a capsule permanently. + + Args: + id (str): Capsule ID. + + Raises: + WrennNotFoundError: If no capsule with the given ID exists. + """ + resp = await self._http.delete(f"/v1/capsules/{id}") + handle_response(resp) + + async def pause(self, id: str) -> CapsuleModel: + """Pause a running capsule. + + Args: + id (str): Capsule ID. + + Returns: + CapsuleModel: Updated capsule state. + + Raises: + WrennNotFoundError: If no capsule with the given ID exists. + """ + resp = await self._http.post(f"/v1/capsules/{id}/pause") + return CapsuleModel.model_validate(handle_response(resp)) + + async def resume(self, id: str) -> CapsuleModel: + """Resume a paused capsule. + + Args: + id (str): Capsule ID. + + Returns: + CapsuleModel: Updated capsule state. + + Raises: + WrennNotFoundError: If no capsule with the given ID exists. + """ + resp = await self._http.post(f"/v1/capsules/{id}/resume") + return CapsuleModel.model_validate(handle_response(resp)) + + async def ping(self, id: str) -> None: + """Reset the inactivity timer for a capsule. + + Args: + id (str): Capsule ID. + + Raises: + WrennNotFoundError: If no capsule with the given ID exists. + """ + resp = await self._http.post(f"/v1/capsules/{id}/ping") + handle_response(resp) + + +class SnapshotsResource: + """Sync snapshot operations.""" + + def __init__(self, http: httpx.Client) -> None: + self._http = http + + def create( + self, + capsule_id: str, + name: str | None = None, + overwrite: bool = False, + ) -> Template: + """Create a snapshot template from a running capsule. + + Args: + capsule_id (str): ID of the capsule to snapshot. + name (str | None): Name for the snapshot template. Auto-generated + if not provided. + overwrite (bool): If ``True``, overwrite an existing template with + the same name. Defaults to ``False``. + + Returns: + Template: The created snapshot template. + """ + payload: dict = {"sandbox_id": capsule_id} + if name is not None: + payload["name"] = name + params: dict = {} + if overwrite: + params["overwrite"] = "true" + resp = self._http.post("/v1/snapshots", json=payload, params=params) + return Template.model_validate(handle_response(resp)) + + def list(self, type: str | None = None) -> list[Template]: + """List snapshot templates. + + Args: + type (str | None): Filter by template type. Returns all templates + if not provided. + + Returns: + list[Template]: Matching snapshot templates. + """ + params: dict = {} + if type is not None: + params["type"] = type + resp = self._http.get("/v1/snapshots", params=params) + return [Template.model_validate(item) for item in handle_response(resp)] + + def delete(self, name: str) -> None: + """Delete a snapshot template by name. + + Args: + name (str): Template name to delete. + + Raises: + WrennNotFoundError: If no template with the given name exists. + """ + resp = self._http.delete(f"/v1/snapshots/{name}") + handle_response(resp) + + +class AsyncSnapshotsResource: + """Async snapshot operations.""" + + def __init__(self, http: httpx.AsyncClient) -> None: + self._http = http + + async def create( + self, + capsule_id: str, + name: str | None = None, + overwrite: bool = False, + ) -> Template: + """Create a snapshot template from a running capsule. + + Args: + capsule_id (str): ID of the capsule to snapshot. + name (str | None): Name for the snapshot template. Auto-generated + if not provided. + overwrite (bool): If ``True``, overwrite an existing template with + the same name. Defaults to ``False``. + + Returns: + Template: The created snapshot template. + """ + payload: dict = {"sandbox_id": capsule_id} + if name is not None: + payload["name"] = name + params: dict = {} + if overwrite: + params["overwrite"] = "true" + resp = await self._http.post("/v1/snapshots", json=payload, params=params) + return Template.model_validate(handle_response(resp)) + + async def list(self, type: str | None = None) -> list[Template]: + """List snapshot templates. + + Args: + type (str | None): Filter by template type. Returns all templates + if not provided. + + Returns: + list[Template]: Matching snapshot templates. + """ + params: dict = {} + if type is not None: + params["type"] = type + resp = await self._http.get("/v1/snapshots", params=params) + return [Template.model_validate(item) for item in handle_response(resp)] + + async def delete(self, name: str) -> None: + """Delete a snapshot template by name. + + Args: + name (str): Template name to delete. + + Raises: + WrennNotFoundError: If no template with the given name exists. + """ + resp = await self._http.delete(f"/v1/snapshots/{name}") + handle_response(resp) + + +class WrennClient: + """Synchronous client for the Wrenn API. + + Authenticates with an API key. + + Args: + api_key: API key (``wrn_...``). Falls back to ``WRENN_API_KEY`` env var. + base_url: Wrenn API base URL. + """ + + def __init__( + self, + api_key: str | None = None, + base_url: str | None = None, + ) -> None: + self._api_key = _resolve_api_key(api_key) + self._base_url = base_url or os.environ.get(ENV_BASE_URL, DEFAULT_BASE_URL) + self._http = httpx.Client( + base_url=self._base_url, + headers={"X-API-Key": self._api_key}, + ) + + self.capsules = CapsulesResource(self._http) + self.snapshots = SnapshotsResource(self._http) + + @property + def http(self) -> httpx.Client: + """The underlying httpx.Client (for sub-objects that need direct access).""" + return self._http + + def close(self) -> None: + """Close the underlying HTTP connection pool.""" + self._http.close() + + def __enter__(self) -> WrennClient: + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: object, + ) -> None: + self.close() + + +class AsyncWrennClient: + """Asynchronous client for the Wrenn API. + + Authenticates with an API key. + + Args: + api_key: API key (``wrn_...``). Falls back to ``WRENN_API_KEY`` env var. + base_url: Wrenn API base URL. Falls back to ``WRENN_BASE_URL`` env var. + """ + + def __init__( + self, + api_key: str | None = None, + base_url: str | None = None, + ) -> None: + self._api_key = _resolve_api_key(api_key) + self._base_url = base_url or os.environ.get(ENV_BASE_URL, DEFAULT_BASE_URL) + self._http = httpx.AsyncClient( + base_url=self._base_url, + headers={"X-API-Key": self._api_key}, + ) + + self.capsules = AsyncCapsulesResource(self._http) + self.snapshots = AsyncSnapshotsResource(self._http) + + @property + def http(self) -> httpx.AsyncClient: + """The underlying httpx.AsyncClient.""" + return self._http + + async def aclose(self) -> None: + """Close the underlying async HTTP connection pool.""" + await self._http.aclose() + + async def __aenter__(self) -> AsyncWrennClient: + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: object, + ) -> None: + await self.aclose() diff --git a/src/wrenn/code_interpreter/__init__.py b/src/wrenn/code_interpreter/__init__.py new file mode 100644 index 0000000..9818204 --- /dev/null +++ b/src/wrenn/code_interpreter/__init__.py @@ -0,0 +1,35 @@ +from wrenn.code_interpreter.async_capsule import AsyncCapsule +from wrenn.code_interpreter.capsule import Capsule +from wrenn.code_interpreter.models import ( + Execution, + ExecutionError, + Logs, + Result, +) + +__all__ = [ + "AsyncCapsule", + "Capsule", + "Execution", + "ExecutionError", + "Logs", + "Result", + "Sandbox", +] + + +def __getattr__(name: str) -> type: + import sys + import warnings + + _module = sys.modules[__name__] + + if name == "Sandbox": + warnings.warn( + "'Sandbox' is deprecated, use 'Capsule' instead", + FutureWarning, + stacklevel=2, + ) + setattr(_module, name, Capsule) + return Capsule + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") diff --git a/src/wrenn/code_interpreter/async_capsule.py b/src/wrenn/code_interpreter/async_capsule.py new file mode 100644 index 0000000..fb99752 --- /dev/null +++ b/src/wrenn/code_interpreter/async_capsule.py @@ -0,0 +1,270 @@ +from __future__ import annotations + +import asyncio +import json +import time +import uuid +from collections.abc import Callable +from typing import Any + +import httpx +import httpx_ws + +from wrenn.async_capsule import AsyncCapsule as BaseAsyncCapsule +from wrenn.capsule import _build_proxy_url +from wrenn.client import AsyncWrennClient +from wrenn.code_interpreter.capsule import DEFAULT_TEMPLATE +from wrenn.code_interpreter.models import ( + Execution, + ExecutionError, + Result, +) + + +class AsyncCapsule(BaseAsyncCapsule): + """Async code interpreter capsule with ``run_code`` support. + + Uses ``code-runner-beta`` template by default:: + + from wrenn.code_interpreter import AsyncCapsule + + capsule = await AsyncCapsule.create() + result = await capsule.run_code("print('hello')") + """ + + _kernel_id: str | None + _proxy_client: httpx.AsyncClient | None + + def __init__(self, **kwargs) -> None: + super().__init__(**kwargs) + self._kernel_id = None + self._proxy_client = None + + @classmethod + async def create( + cls, + template: str | None = None, + vcpus: int | None = None, + memory_mb: int | None = None, + timeout: int | None = None, + *, + wait: bool = False, + api_key: str | None = None, + base_url: str | None = None, + ) -> AsyncCapsule: + """Create a new async code interpreter capsule. + + Args: + template (str | None): Template to boot from. Defaults to + ``"code-runner-beta"``. + vcpus (int | None): Number of virtual CPUs. + memory_mb (int | None): Memory in MiB. + timeout (int | None): Inactivity TTL in seconds before auto-pause. + wait (bool): Await until the capsule reaches ``running`` status. + api_key (str | None): Wrenn API key. Falls back to + ``WRENN_API_KEY`` env var. + base_url (str | None): API base URL override. + + Returns: + AsyncCapsule: A new async code interpreter capsule instance. + """ + client = AsyncWrennClient(api_key=api_key, base_url=base_url) + info = await client.capsules.create( + template=template or DEFAULT_TEMPLATE, + vcpus=vcpus, + memory_mb=memory_mb, + timeout_sec=timeout, + ) + capsule = cls( + _capsule_id=info.id, + _client=client, + _info=info, + ) + if wait: + await capsule.wait_ready() + return capsule + + def _get_proxy_client(self) -> httpx.AsyncClient: + if self._proxy_client is None: + url = ( + _build_proxy_url(self._client._base_url, self._id, 8888) + .replace("ws://", "http://") + .replace("wss://", "https://") + ) + self._proxy_client = httpx.AsyncClient( + base_url=url, + headers={"X-API-Key": self._client._api_key}, + ) + return self._proxy_client + + async def _ensure_kernel(self, jupyter_timeout: float = 30) -> str: + if self._kernel_id is not None: + return self._kernel_id + + client = self._get_proxy_client() + deadline = time.monotonic() + jupyter_timeout + last_exc: Exception | None = None + + while time.monotonic() < deadline: + try: + # Try to reuse an existing kernel + resp = await client.get("/api/kernels") + if resp.status_code < 500: + resp.raise_for_status() + kernels = resp.json() + if kernels: + self._kernel_id = kernels[0]["id"] + return self._kernel_id + # No existing kernels, create a new one + resp = await client.post("/api/kernels") + if resp.status_code < 500: + resp.raise_for_status() + self._kernel_id = resp.json()["id"] + return self._kernel_id + last_exc = httpx.HTTPStatusError( + f"Jupyter returned {resp.status_code}", + request=resp.request, + response=resp, + ) + except httpx.HTTPStatusError: + raise + except Exception as exc: + last_exc = exc + await asyncio.sleep(0.5) + + raise TimeoutError( + f"Jupyter not available within {jupyter_timeout}s: {last_exc}" + ) + + def _jupyter_ws_url(self, kernel_id: str) -> str: + proxy = _build_proxy_url(self._client._base_url, self._id, 8888) + return f"{proxy}/api/kernels/{kernel_id}/channels" + + @staticmethod + def _jupyter_execute_request(code: str) -> dict: + msg_id = str(uuid.uuid4()) + return { + "header": { + "msg_id": msg_id, + "msg_type": "execute_request", + "username": "wrenn-sdk", + "session": str(uuid.uuid4()), + "date": time.strftime("%Y-%m-%dT%H:%M:%S.000Z", time.gmtime()), + "version": "5.3", + }, + "parent_header": {}, + "metadata": {}, + "content": { + "code": code, + "silent": False, + "store_history": True, + "user_expressions": {}, + "allow_stdin": False, + "stop_on_error": True, + }, + "buffers": [], + "channel": "shell", + "msg_id": msg_id, + "msg_type": "execute_request", + } + + async def run_code( + self, + code: str, + language: str = "python", + timeout: float = 30, + jupyter_timeout: float = 30, + on_result: Callable[[Result], Any] | None = None, + on_stdout: Callable[[str], Any] | None = None, + on_stderr: Callable[[str], Any] | None = None, + on_error: Callable[[ExecutionError], Any] | None = None, + ) -> Execution: + """Execute code in a persistent Jupyter kernel (async). + + Args: + code: Code string to execute. + language: Execution backend language. Currently only ``"python"``. + timeout: Maximum seconds to wait for execution to complete. + jupyter_timeout: Maximum seconds to wait for Jupyter to become + available. + on_result: Called for each rich output (charts, images, expression + values). + on_stdout: Called for each stdout chunk. + on_stderr: Called for each stderr chunk. + on_error: Called when the cell raises an exception. + + Returns: + An :class:`Execution` with ``.results``, ``.logs``, ``.error``, + and a convenience ``.text`` property. + """ + kernel_id = await self._ensure_kernel(jupyter_timeout=jupyter_timeout) + ws_url = self._jupyter_ws_url(kernel_id) + + msg = self._jupyter_execute_request(code) + msg_id = msg["msg_id"] + + execution = Execution() + deadline = time.monotonic() + timeout + headers = {"X-API-Key": self._client._api_key} + + async with httpx_ws.aconnect_ws(ws_url, headers=headers) as ws: + await ws.send_text(json.dumps(msg)) + while time.monotonic() < deadline: + time_left = deadline - time.monotonic() + if time_left <= 0: + break + try: + data = await asyncio.wait_for(ws.receive_json(), timeout=time_left) + except (asyncio.TimeoutError, Exception): + break + if not data: + break + parent = data.get("parent_header", {}).get("msg_id") + if parent != msg_id: + continue + msg_type = data.get("msg_type") or data.get("header", {}).get( + "msg_type" + ) + content = data.get("content", {}) + + if msg_type == "stream": + text = content.get("text", "") + name = content.get("name", "stdout") + if name == "stderr": + execution.logs.stderr.append(text) + if on_stderr is not None: + on_stderr(text) + else: + execution.logs.stdout.append(text) + if on_stdout is not None: + on_stdout(text) + elif msg_type in ("execute_result", "display_data"): + bundle = content.get("data", {}) + is_main = msg_type == "execute_result" + result = Result.from_bundle(bundle, is_main_result=is_main) + execution.results.append(result) + if is_main: + execution.execution_count = content.get("execution_count") + if on_result is not None: + on_result(result) + elif msg_type == "error": + err = ExecutionError( + name=content.get("ename", ""), + value=content.get("evalue", ""), + traceback="\n".join(content.get("traceback", [])), + ) + execution.error = err + if on_error is not None: + on_error(err) + elif msg_type == "status" and content.get("execution_state") == "idle": + break + + return execution + + async def __aexit__(self, *args) -> None: + if self._proxy_client is not None: + try: + await self._proxy_client.aclose() + except Exception: + pass + await super().__aexit__(*args) diff --git a/src/wrenn/code_interpreter/capsule.py b/src/wrenn/code_interpreter/capsule.py new file mode 100644 index 0000000..1b1f7ea --- /dev/null +++ b/src/wrenn/code_interpreter/capsule.py @@ -0,0 +1,296 @@ +from __future__ import annotations + +import json +import time +import uuid +from collections.abc import Callable +from typing import Any + +import httpx +import httpx_ws + +from wrenn.capsule import Capsule as BaseCapsule +from wrenn.capsule import _build_proxy_url +from wrenn.code_interpreter.models import ( + Execution, + ExecutionError, + Result, +) + +DEFAULT_TEMPLATE = "code-runner-beta" + + +class Capsule(BaseCapsule): + """Code interpreter capsule with ``run_code`` support. + + Uses ``code-runner-beta`` template by default:: + + from wrenn.code_interpreter import Capsule + + capsule = Capsule() + result = capsule.run_code("print('hello')") + print(result.logs.stdout) # ["hello\\n"] + """ + + _kernel_id: str | None + _proxy_client: httpx.Client | None + + def __init__( + self, + template: str | None = None, + vcpus: int | None = None, + memory_mb: int | None = None, + timeout: int | None = None, + *, + api_key: str | None = None, + base_url: str | None = None, + **kwargs, + ) -> None: + """Create a code interpreter capsule. + + Args: + template (str | None): Template to boot from. Defaults to + ``"code-runner-beta"``. + vcpus (int | None): Number of virtual CPUs. + memory_mb (int | None): Memory in MiB. + timeout (int | None): Inactivity TTL in seconds before auto-pause. + api_key (str | None): Wrenn API key. Falls back to + ``WRENN_API_KEY`` env var. + base_url (str | None): API base URL override. + """ + super().__init__( + template=template or DEFAULT_TEMPLATE, + vcpus=vcpus, + memory_mb=memory_mb, + timeout=timeout, + api_key=api_key, + base_url=base_url, + **kwargs, + ) + self._kernel_id = None + self._proxy_client = None + + @classmethod + def create( + cls, + template: str | None = None, + vcpus: int | None = None, + memory_mb: int | None = None, + timeout: int | None = None, + *, + wait: bool = False, + api_key: str | None = None, + base_url: str | None = None, + ) -> Capsule: + """Create a new code interpreter capsule. + + Args: + template (str | None): Template to boot from. Defaults to + ``"code-runner-beta"``. + vcpus (int | None): Number of virtual CPUs. + memory_mb (int | None): Memory in MiB. + timeout (int | None): Inactivity TTL in seconds before auto-pause. + wait (bool): Block until the capsule reaches ``running`` status. + api_key (str | None): Wrenn API key. Falls back to + ``WRENN_API_KEY`` env var. + base_url (str | None): API base URL override. + + Returns: + Capsule: A new code interpreter capsule instance. + """ + return cls( + template=template or DEFAULT_TEMPLATE, + vcpus=vcpus, + memory_mb=memory_mb, + timeout=timeout, + wait=wait, + api_key=api_key, + base_url=base_url, + ) + + def _get_proxy_client(self) -> httpx.Client: + if self._proxy_client is None: + url = ( + _build_proxy_url(self._client._base_url, self._id, 8888) + .replace("ws://", "http://") + .replace("wss://", "https://") + ) + self._proxy_client = httpx.Client( + base_url=url, + headers={"X-API-Key": self._client._api_key}, + ) + return self._proxy_client + + def _ensure_kernel(self, jupyter_timeout: float = 30) -> str: + if self._kernel_id is not None: + return self._kernel_id + + client = self._get_proxy_client() + deadline = time.monotonic() + jupyter_timeout + last_exc: Exception | None = None + + while time.monotonic() < deadline: + try: + # Try to reuse an existing kernel + resp = client.get("/api/kernels") + if resp.status_code < 500: + resp.raise_for_status() + kernels = resp.json() + if kernels: + self._kernel_id = kernels[0]["id"] + return self._kernel_id + # No existing kernels, create a new one + resp = client.post("/api/kernels") + if resp.status_code < 500: + resp.raise_for_status() + self._kernel_id = resp.json()["id"] + return self._kernel_id + last_exc = httpx.HTTPStatusError( + f"Jupyter returned {resp.status_code}", + request=resp.request, + response=resp, + ) + except httpx.HTTPStatusError: + raise + except Exception as exc: + last_exc = exc + time.sleep(0.5) + + raise TimeoutError( + f"Jupyter not available within {jupyter_timeout}s: {last_exc}" + ) + + def _jupyter_ws_url(self, kernel_id: str) -> str: + proxy = _build_proxy_url(self._client._base_url, self._id, 8888) + return f"{proxy}/api/kernels/{kernel_id}/channels" + + @staticmethod + def _jupyter_execute_request(code: str) -> dict: + msg_id = str(uuid.uuid4()) + return { + "header": { + "msg_id": msg_id, + "msg_type": "execute_request", + "username": "wrenn-sdk", + "session": str(uuid.uuid4()), + "date": time.strftime("%Y-%m-%dT%H:%M:%S.000Z", time.gmtime()), + "version": "5.3", + }, + "parent_header": {}, + "metadata": {}, + "content": { + "code": code, + "silent": False, + "store_history": True, + "user_expressions": {}, + "allow_stdin": False, + "stop_on_error": True, + }, + "buffers": [], + "channel": "shell", + "msg_id": msg_id, + "msg_type": "execute_request", + } + + def run_code( + self, + code: str, + language: str = "python", + timeout: float = 30, + jupyter_timeout: float = 30, + on_result: Callable[[Result], Any] | None = None, + on_stdout: Callable[[str], Any] | None = None, + on_stderr: Callable[[str], Any] | None = None, + on_error: Callable[[ExecutionError], Any] | None = None, + ) -> Execution: + """Execute code in a persistent Jupyter kernel. + + Variables, imports, and function definitions survive across calls. + + Args: + code: Code string to execute. + language: Execution backend language. Currently only ``"python"``. + timeout: Maximum seconds to wait for execution to complete. + jupyter_timeout: Maximum seconds to wait for Jupyter to become + available. + on_result: Called for each rich output (charts, images, expression + values). + on_stdout: Called for each stdout chunk. + on_stderr: Called for each stderr chunk. + on_error: Called when the cell raises an exception. + + Returns: + An :class:`Execution` with ``.results``, ``.logs``, ``.error``, + and a convenience ``.text`` property. + """ + kernel_id = self._ensure_kernel(jupyter_timeout=jupyter_timeout) + ws_url = self._jupyter_ws_url(kernel_id) + + msg = self._jupyter_execute_request(code) + msg_id = msg["msg_id"] + + execution = Execution() + deadline = time.monotonic() + timeout + headers = {"X-API-Key": self._client._api_key} + + with httpx_ws.connect_ws(ws_url, headers=headers) as ws: + ws.send_text(json.dumps(msg)) + while time.monotonic() < deadline: + time_left = deadline - time.monotonic() + if time_left <= 0: + break + try: + data = ws.receive_json(timeout=time_left) + except (TimeoutError, Exception): + break + if not data: + break + parent = data.get("parent_header", {}).get("msg_id") + if parent != msg_id: + continue + msg_type = data.get("msg_type") or data.get("header", {}).get( + "msg_type" + ) + content = data.get("content", {}) + + if msg_type == "stream": + text = content.get("text", "") + name = content.get("name", "stdout") + if name == "stderr": + execution.logs.stderr.append(text) + if on_stderr is not None: + on_stderr(text) + else: + execution.logs.stdout.append(text) + if on_stdout is not None: + on_stdout(text) + elif msg_type in ("execute_result", "display_data"): + bundle = content.get("data", {}) + is_main = msg_type == "execute_result" + result = Result.from_bundle(bundle, is_main_result=is_main) + execution.results.append(result) + if is_main: + execution.execution_count = content.get("execution_count") + if on_result is not None: + on_result(result) + elif msg_type == "error": + err = ExecutionError( + name=content.get("ename", ""), + value=content.get("evalue", ""), + traceback="\n".join(content.get("traceback", [])), + ) + execution.error = err + if on_error is not None: + on_error(err) + elif msg_type == "status" and content.get("execution_state") == "idle": + break + + return execution + + def __exit__(self, *args) -> None: + if self._proxy_client is not None: + try: + self._proxy_client.close() + except Exception: + pass + super().__exit__(*args) diff --git a/src/wrenn/code_interpreter/models.py b/src/wrenn/code_interpreter/models.py new file mode 100644 index 0000000..1449bc4 --- /dev/null +++ b/src/wrenn/code_interpreter/models.py @@ -0,0 +1,156 @@ +from __future__ import annotations + +from dataclasses import dataclass, field + +_MIME_MAP: dict[str, str] = { + "text/plain": "text", + "text/html": "html", + "text/markdown": "markdown", + "image/svg+xml": "svg", + "image/png": "png", + "image/jpeg": "jpeg", + "application/pdf": "pdf", + "text/latex": "latex", + "application/json": "json", + "application/javascript": "javascript", +} + + +@dataclass +class ExecutionError: + """Error raised during code execution. + + Attributes: + name: Exception class name (e.g. ``"NameError"``). + value: Exception message. + traceback: Full traceback string. + """ + + name: str = "" + value: str = "" + traceback: str = "" + + +@dataclass +class Logs: + """Captured stdout/stderr streams. + + Each element in the list is one chunk of text as it arrived from + the kernel. + """ + + stdout: list[str] = field(default_factory=list) + stderr: list[str] = field(default_factory=list) + + +@dataclass +class Result: + """A single rich output from code execution. + + Jupyter cells can produce multiple outputs — one ``execute_result`` + (the expression value) and zero or more ``display_data`` messages + (from ``plt.show()``, ``display()``, etc.). Each becomes a + ``Result``. + + Known MIME types are unpacked into named attributes; anything else + lands in :pyattr:`extra`. + """ + + # --- MIME type fields --- + text: str | None = None + """``text/plain`` representation.""" + html: str | None = None + """``text/html`` representation.""" + markdown: str | None = None + """``text/markdown`` representation.""" + svg: str | None = None + """``image/svg+xml`` representation.""" + png: str | None = None + """``image/png`` — base64-encoded.""" + jpeg: str | None = None + """``image/jpeg`` — base64-encoded.""" + pdf: str | None = None + """``application/pdf`` — base64-encoded.""" + latex: str | None = None + """``text/latex`` representation.""" + json: dict | None = None + """``application/json`` representation.""" + javascript: str | None = None + """``application/javascript`` representation.""" + extra: dict[str, str] | None = None + """MIME types not covered by the named fields above.""" + + is_main_result: bool = False + """``True`` when this came from an ``execute_result`` message + (i.e. the value of the last expression in the cell). ``False`` + for ``display_data`` outputs.""" + + @classmethod + def from_bundle( + cls, bundle: dict[str, str], *, is_main_result: bool = False + ) -> Result: + """Build a ``Result`` from a Jupyter MIME bundle dict.""" + kwargs: dict = {"is_main_result": is_main_result} + extra: dict[str, str] = {} + for mime, value in bundle.items(): + attr = _MIME_MAP.get(mime) + if attr is not None: + kwargs[attr] = value + else: + extra[mime] = value + if extra: + kwargs["extra"] = extra + # Strip surrounding quotes from text/plain (Jupyter repr artefact) + text = kwargs.get("text") + if isinstance(text, str) and len(text) >= 2: + if (text[0] == text[-1]) and text[0] in ("'", '"'): + kwargs["text"] = text[1:-1] + return cls(**kwargs) + + def formats(self) -> list[str]: + """Return names of non-``None`` MIME-type fields.""" + out: list[str] = [] + for attr in ( + "text", + "html", + "markdown", + "svg", + "png", + "jpeg", + "pdf", + "latex", + "json", + "javascript", + ): + if getattr(self, attr) is not None: + out.append(attr) + if self.extra: + out.extend(self.extra) + return out + + +@dataclass +class Execution: + """Complete result of a ``run_code`` call. + + Attributes: + results: All rich outputs produced by the cell — charts, tables, + images, expression values, etc. + logs: Captured stdout/stderr text. + error: Populated when the cell raised an exception. + execution_count: Jupyter execution counter (the ``[N]`` number). + """ + + results: list[Result] = field(default_factory=list) + logs: Logs = field(default_factory=Logs) + error: ExecutionError | None = None + execution_count: int | None = None + + @property + def text(self) -> str | None: + """Convenience — ``text/plain`` of the main ``execute_result``, + or ``None`` if the cell had no expression value.""" + for r in self.results: + if r.is_main_result: + return r.text + return None diff --git a/src/wrenn/commands.py b/src/wrenn/commands.py new file mode 100644 index 0000000..7ca9f44 --- /dev/null +++ b/src/wrenn/commands.py @@ -0,0 +1,480 @@ +from __future__ import annotations + +import base64 +import json +from collections.abc import AsyncIterator, Iterator +from dataclasses import dataclass +from typing import overload, Literal + +import httpx +import httpx_ws + +from wrenn.exceptions import handle_response + + +@dataclass +class CommandResult: + """Result from a foreground command execution.""" + + stdout: str + stderr: str + exit_code: int + duration_ms: int | None = None + + +@dataclass +class CommandHandle: + """Handle for a background process.""" + + pid: int + tag: str + capsule_id: str + + +@dataclass +class ProcessInfo: + """Information about a running process.""" + + pid: int + tag: str | None = None + cmd: str | None = None + args: list[str] | None = None + + +class StreamEvent: + """Base class for streaming exec events.""" + + __slots__ = ("type",) + + def __init__(self, type: str) -> None: + self.type = type + + +class StreamStartEvent(StreamEvent): + __slots__ = ("pid",) + + def __init__(self, pid: int) -> None: + super().__init__("start") + self.pid = pid + + +class StreamStdoutEvent(StreamEvent): + __slots__ = ("data",) + + def __init__(self, data: str) -> None: + super().__init__("stdout") + self.data = data + + +class StreamStderrEvent(StreamEvent): + __slots__ = ("data",) + + def __init__(self, data: str) -> None: + super().__init__("stderr") + self.data = data + + +class StreamExitEvent(StreamEvent): + __slots__ = ("exit_code",) + + def __init__(self, exit_code: int) -> None: + super().__init__("exit") + self.exit_code = exit_code + + +class StreamErrorEvent(StreamEvent): + __slots__ = ("data",) + + def __init__(self, data: str) -> None: + super().__init__("error") + self.data = data + + +def _parse_stream_event(raw: dict) -> StreamEvent: + t = raw.get("type") + if t == "start": + return StreamStartEvent(pid=raw.get("pid", 0)) + if t == "stdout": + return StreamStdoutEvent(data=raw.get("data", "")) + if t == "stderr": + return StreamStderrEvent(data=raw.get("data", "")) + if t == "exit": + return StreamExitEvent(exit_code=raw.get("exit_code", -1)) + if t == "error": + return StreamErrorEvent(data=raw.get("data", "")) + return StreamEvent(type=t or "unknown") + + +def _decode_exec_response(data: dict) -> CommandResult: + stdout = data.get("stdout") or "" + stderr = data.get("stderr") or "" + if data.get("encoding") == "base64": + stdout = base64.b64decode(stdout).decode("utf-8", errors="replace") + if stderr: + stderr = base64.b64decode(stderr).decode("utf-8", errors="replace") + return CommandResult( + stdout=stdout, + stderr=stderr, + exit_code=data.get("exit_code", -1), + duration_ms=data.get("duration_ms"), + ) + + +class Commands: + """Sync command execution interface. Accessed via ``capsule.commands``.""" + + def __init__(self, capsule_id: str, http: httpx.Client) -> None: + self._capsule_id = capsule_id + self._http = http + + @overload + def run( + self, + cmd: str, + *, + background: Literal[False] = ..., + timeout: int | None = 30, + envs: dict[str, str] | None = None, + cwd: str | None = None, + tag: str | None = None, + ) -> CommandResult: ... + + @overload + def run( + self, + cmd: str, + *, + background: Literal[True], + timeout: int | None = 30, + envs: dict[str, str] | None = None, + cwd: str | None = None, + tag: str | None = None, + ) -> CommandHandle: ... + + def run( + self, + cmd: str, + *, + background: bool = False, + timeout: int | None = 30, + envs: dict[str, str] | None = None, + cwd: str | None = None, + tag: str | None = None, + ) -> CommandResult | CommandHandle: + """Execute a shell command inside the capsule. + + Args: + cmd (str): Shell command string to execute. + background (bool): If ``True``, launch the process in the + background and return a :class:`CommandHandle` immediately. + Defaults to ``False``. + timeout (int | None): Seconds before the foreground command times + out. Ignored for background commands. Defaults to ``30``. + envs (dict[str, str] | None): Additional environment variables + to set for the process. + cwd (str | None): Working directory for the process. + tag (str | None): Optional label attached to background processes + for later retrieval via :meth:`connect`. + + Returns: + CommandResult: stdout, stderr, exit code, and duration for + foreground commands (``background=False``). + + CommandHandle: PID and tag for background commands + (``background=True``). + """ + payload: dict = { + "cmd": "/bin/sh", + "args": ["-c", cmd], + "background": background, + } + if timeout is not None and not background: + payload["timeout_sec"] = timeout + if envs is not None: + payload["envs"] = envs + if cwd is not None: + payload["cwd"] = cwd + if tag is not None: + payload["tag"] = tag + + resp = self._http.post(f"/v1/capsules/{self._capsule_id}/exec", json=payload) + data = handle_response(resp) + + if background: + return CommandHandle( + pid=data.get("pid", 0), + tag=data.get("tag", ""), + capsule_id=self._capsule_id, + ) + return _decode_exec_response(data) + + def list(self) -> list[ProcessInfo]: + """List all running background processes in the capsule. + + Returns: + list[ProcessInfo]: Running processes with their PID, tag, and + command information. + """ + resp = self._http.get(f"/v1/capsules/{self._capsule_id}/processes") + data = handle_response(resp) + return [ + ProcessInfo( + pid=p.get("pid", 0), + tag=p.get("tag"), + cmd=p.get("cmd"), + args=p.get("args"), + ) + for p in data.get("processes", []) + ] + + def kill(self, pid: int) -> None: + """Send SIGKILL to a background process. + + Args: + pid (int): PID of the process to kill. + + Raises: + WrennNotFoundError: If no process with the given PID exists. + """ + resp = self._http.delete(f"/v1/capsules/{self._capsule_id}/processes/{pid}") + handle_response(resp) + + def connect(self, pid: int) -> Iterator[StreamEvent]: + """Connect to a running background process and stream its output. + + Args: + pid (int): PID of the background process to attach to. + + Yields: + StreamEvent: Successive output events. Stops on + :class:`StreamExitEvent` or :class:`StreamErrorEvent`. + """ + with httpx_ws.connect_ws( + f"/v1/capsules/{self._capsule_id}/processes/{pid}/stream", + self._http, + ) as ws: + while True: + try: + raw = ws.receive_json() + event = _parse_stream_event(raw) + yield event + if event.type in ("exit", "error"): + break + except httpx_ws.WebSocketDisconnect: + break + + def stream(self, cmd: str, args: list[str] | None = None) -> Iterator[StreamEvent]: + """Execute a command via WebSocket, streaming output as events. + + Args: + cmd (str): Command to execute. + args (list[str] | None): Additional arguments for the command. + When omitted, *cmd* is interpreted as a shell command + string and executed via ``/bin/sh -c``. + + Yields: + StreamEvent: Successive events including :class:`StreamStartEvent`, + :class:`StreamStdoutEvent`, :class:`StreamStderrEvent`, + :class:`StreamExitEvent`, and :class:`StreamErrorEvent`. + """ + with httpx_ws.connect_ws( + f"/v1/capsules/{self._capsule_id}/exec/stream", + self._http, + ) as ws: + if args: + start_msg: dict = {"type": "start", "cmd": cmd, "args": args} + else: + start_msg = {"type": "start", "cmd": "/bin/sh", "args": ["-c", cmd]} + ws.send_text(json.dumps(start_msg)) + while True: + try: + raw = ws.receive_json() + event = _parse_stream_event(raw) + yield event + if event.type in ("exit", "error"): + break + except httpx_ws.WebSocketDisconnect: + break + + +class AsyncCommands: + """Async command execution interface. Accessed via ``capsule.commands``.""" + + def __init__(self, capsule_id: str, http: httpx.AsyncClient) -> None: + self._capsule_id = capsule_id + self._http = http + + @overload + async def run( + self, + cmd: str, + *, + background: Literal[False] = ..., + timeout: int | None = 30, + envs: dict[str, str] | None = None, + cwd: str | None = None, + tag: str | None = None, + ) -> CommandResult: ... + + @overload + async def run( + self, + cmd: str, + *, + background: Literal[True], + timeout: int | None = 30, + envs: dict[str, str] | None = None, + cwd: str | None = None, + tag: str | None = None, + ) -> CommandHandle: ... + + async def run( + self, + cmd: str, + *, + background: bool = False, + timeout: int | None = 30, + envs: dict[str, str] | None = None, + cwd: str | None = None, + tag: str | None = None, + ) -> CommandResult | CommandHandle: + """Execute a shell command inside the capsule. + + Args: + cmd (str): Shell command string to execute. + background (bool): If ``True``, launch the process in the + background and return a :class:`CommandHandle` immediately. + Defaults to ``False``. + timeout (int | None): Seconds before the foreground command times + out. Ignored for background commands. Defaults to ``30``. + envs (dict[str, str] | None): Additional environment variables + to set for the process. + cwd (str | None): Working directory for the process. + tag (str | None): Optional label attached to background processes + for later retrieval via :meth:`connect`. + + Returns: + CommandResult: stdout, stderr, exit code, and duration for + foreground commands (``background=False``). + + CommandHandle: PID and tag for background commands + (``background=True``). + """ + payload: dict = { + "cmd": "/bin/sh", + "args": ["-c", cmd], + "background": background, + } + if timeout is not None and not background: + payload["timeout_sec"] = timeout + if envs is not None: + payload["envs"] = envs + if cwd is not None: + payload["cwd"] = cwd + if tag is not None: + payload["tag"] = tag + + resp = await self._http.post( + f"/v1/capsules/{self._capsule_id}/exec", json=payload + ) + data = handle_response(resp) + + if background: + return CommandHandle( + pid=data.get("pid", 0), + tag=data.get("tag", ""), + capsule_id=self._capsule_id, + ) + return _decode_exec_response(data) + + async def list(self) -> list[ProcessInfo]: + """List all running background processes in the capsule. + + Returns: + list[ProcessInfo]: Running processes with their PID, tag, and + command information. + """ + resp = await self._http.get(f"/v1/capsules/{self._capsule_id}/processes") + data = handle_response(resp) + return [ + ProcessInfo( + pid=p.get("pid", 0), + tag=p.get("tag"), + cmd=p.get("cmd"), + args=p.get("args"), + ) + for p in data.get("processes", []) + ] + + async def kill(self, pid: int) -> None: + """Send SIGKILL to a background process. + + Args: + pid (int): PID of the process to kill. + + Raises: + WrennNotFoundError: If no process with the given PID exists. + """ + resp = await self._http.delete( + f"/v1/capsules/{self._capsule_id}/processes/{pid}" + ) + handle_response(resp) + + async def connect(self, pid: int) -> AsyncIterator[StreamEvent]: + """Connect to a running background process and stream its output. + + Args: + pid (int): PID of the background process to attach to. + + Yields: + StreamEvent: Successive output events. Stops on + :class:`StreamExitEvent` or :class:`StreamErrorEvent`. + """ + async with httpx_ws.aconnect_ws( + f"/v1/capsules/{self._capsule_id}/processes/{pid}/stream", + self._http, + ) as ws: + try: + while True: + raw = await ws.receive_json() + event = _parse_stream_event(raw) + yield event + if event.type in ("exit", "error"): + break + except httpx_ws.WebSocketDisconnect: + pass + + async def stream( + self, cmd: str, args: list[str] | None = None + ) -> AsyncIterator[StreamEvent]: + """Execute a command via WebSocket, streaming output as events. + + Args: + cmd (str): Command to execute. + args (list[str] | None): Additional arguments for the command. + When omitted, *cmd* is interpreted as a shell command + string and executed via ``/bin/sh -c``. + + Yields: + StreamEvent: Successive events including :class:`StreamStartEvent`, + :class:`StreamStdoutEvent`, :class:`StreamStderrEvent`, + :class:`StreamExitEvent`, and :class:`StreamErrorEvent`. + """ + async with httpx_ws.aconnect_ws( + f"/v1/capsules/{self._capsule_id}/exec/stream", + self._http, + ) as ws: + if args: + start_msg: dict = {"type": "start", "cmd": cmd, "args": args} + else: + start_msg = {"type": "start", "cmd": "/bin/sh", "args": ["-c", cmd]} + await ws.send_text(json.dumps(start_msg)) + try: + while True: + raw = await ws.receive_json() + event = _parse_stream_event(raw) + yield event + if event.type in ("exit", "error"): + break + except httpx_ws.WebSocketDisconnect: + pass diff --git a/src/wrenn/exceptions.py b/src/wrenn/exceptions.py new file mode 100644 index 0000000..438cfcb --- /dev/null +++ b/src/wrenn/exceptions.py @@ -0,0 +1,155 @@ +from __future__ import annotations + +import warnings + +import httpx + + +class WrennError(Exception): + """Base exception for all Wrenn SDK errors. + + All SDK exceptions inherit from this class, so you can catch + ``WrennError`` to handle any API error generically. + + Attributes: + code (str): Machine-readable error code from the API + (e.g. ``"not_found"``). + message (str): Human-readable error description. + status_code (int): HTTP status code of the response. + """ + + def __init__(self, code: str, message: str, status_code: int) -> None: + """Initialize a WrennError. + + Args: + code (str): Machine-readable error code. + message (str): Human-readable error description. + status_code (int): HTTP status code of the response. + """ + self.code = code + self.message = message + self.status_code = status_code + super().__init__(message) + + +class WrennValidationError(WrennError): + """400 — Invalid request parameters.""" + + +class WrennAuthenticationError(WrennError): + """401 — Invalid or missing authentication.""" + + +class WrennForbiddenError(WrennError): + """403 — Authenticated but not authorized.""" + + +class WrennNotFoundError(WrennError): + """404 — Resource not found.""" + + +class WrennConflictError(WrennError): + """409 — State conflict (e.g. invalid_state).""" + + +class WrennHostHasCapsulesError(WrennConflictError): + """409 — Host still has running capsules. + + Attributes: + capsule_ids (list[str]): IDs of the capsules still running on the host. + """ + + def __init__( + self, code: str, message: str, status_code: int, capsule_ids: list[str] + ) -> None: + """Initialize a WrennHostHasCapsulesError. + + Args: + code (str): Machine-readable error code. + message (str): Human-readable error description. + status_code (int): HTTP status code of the response. + capsule_ids (list[str]): IDs of capsules still on the host. + """ + self.capsule_ids = capsule_ids + super().__init__(code, message, status_code) + + @property + def sandbox_ids(self) -> list[str]: + warnings.warn( + "'sandbox_ids' is deprecated, use 'capsule_ids' instead", + DeprecationWarning, + stacklevel=2, + ) + return self.capsule_ids + + +class WrennHostUnavailableError(WrennError): + """503 — No suitable host available.""" + + +class WrennAgentError(WrennError): + """502 — Host agent returned an error.""" + + +class WrennInternalError(WrennError): + """500 — Unexpected server error.""" + + +_ERROR_MAP: dict[str, type[WrennError]] = { + "invalid_request": WrennValidationError, + "unauthorized": WrennAuthenticationError, + "forbidden": WrennForbiddenError, + "not_found": WrennNotFoundError, + "invalid_state": WrennConflictError, + "conflict": WrennConflictError, + "host_has_sandboxes": WrennHostHasCapsulesError, + "host_has_capsules": WrennHostHasCapsulesError, + "host_unavailable": WrennHostUnavailableError, + "agent_error": WrennAgentError, + "internal_error": WrennInternalError, +} + + +def handle_response(resp: httpx.Response) -> dict | list: + if resp.status_code >= 400: + try: + body = resp.json() + except Exception: + resp.raise_for_status() + raise + + err = body.get("error", {}) + code = err.get("code", "internal_error") + message = err.get("message", resp.text) + + exc_cls = _ERROR_MAP.get(code, WrennError) + + if exc_cls is WrennHostHasCapsulesError: + raise WrennHostHasCapsulesError( + code=code, + message=message, + status_code=resp.status_code, + capsule_ids=body.get("sandbox_ids", []), + ) + + raise exc_cls( + code=code, + message=message, + status_code=resp.status_code, + ) + + if resp.status_code == 204: + return {} + + return resp.json() + + +def __getattr__(name: str) -> type: + if name == "WrennHostHasSandboxesError": + warnings.warn( + "'WrennHostHasSandboxesError' is deprecated, use 'WrennHostHasCapsulesError' instead", + DeprecationWarning, + stacklevel=2, + ) + return WrennHostHasCapsulesError + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") diff --git a/src/wrenn/files.py b/src/wrenn/files.py new file mode 100644 index 0000000..94a1dcc --- /dev/null +++ b/src/wrenn/files.py @@ -0,0 +1,404 @@ +from __future__ import annotations + +import os +from collections.abc import AsyncIterator, Iterator + +import httpx + +from wrenn.exceptions import WrennNotFoundError, handle_response +from wrenn.models import FileEntry, ListDirResponse, MakeDirResponse + + +class Files: + """Sync filesystem interface. Accessed via ``capsule.files``.""" + + def __init__(self, capsule_id: str, http: httpx.Client) -> None: + self._capsule_id = capsule_id + self._http = http + + def read(self, path: str) -> str: + """Read a file as a UTF-8 string. + + Args: + path (str): Absolute path to the file inside the capsule. + + Returns: + str: File contents decoded as UTF-8. + + Raises: + WrennNotFoundError: If the path does not exist. + """ + return self.read_bytes(path).decode("utf-8", errors="replace") + + def read_bytes(self, path: str) -> bytes: + """Read a file as raw bytes. + + Args: + path (str): Absolute path to the file inside the capsule. + + Returns: + bytes: Raw file contents. + + Raises: + WrennNotFoundError: If the path does not exist. + """ + resp = self._http.post( + f"/v1/capsules/{self._capsule_id}/files/read", + json={"path": path}, + ) + resp.raise_for_status() + return resp.content + + def write(self, path: str, data: str | bytes) -> None: + """Write data to a file inside the capsule. + + Creates parent directories if they do not exist. + + Args: + path (str): Absolute destination path inside the capsule. + data (str | bytes): Content to write. Strings are UTF-8 encoded. + """ + if isinstance(data, str): + data = data.encode("utf-8") + resp = self._http.post( + f"/v1/capsules/{self._capsule_id}/files/write", + files={"file": ("upload", data)}, + data={"path": path}, + ) + resp.raise_for_status() + + def list(self, path: str, depth: int = 1) -> list[FileEntry]: + """List directory contents. + + Args: + path (str): Absolute path to the directory inside the capsule. + depth (int): Recursion depth. ``1`` lists only immediate children. + Defaults to ``1``. + + Returns: + list[FileEntry]: Entries in the directory. + + Raises: + WrennNotFoundError: If the path does not exist. + """ + resp = self._http.post( + f"/v1/capsules/{self._capsule_id}/files/list", + json={"path": path, "depth": depth}, + ) + parsed = ListDirResponse.model_validate(handle_response(resp)) + return parsed.entries or [] + + def exists(self, path: str) -> bool: + """Check whether a path exists inside the capsule. + + Args: + path (str): Absolute path to check. + + Returns: + bool: ``True`` if the path exists. + """ + parent = os.path.dirname(path) + name = os.path.basename(path) + try: + entries = self.list(parent, depth=1) + except WrennNotFoundError: + return False + return any(e.name == name for e in entries) + + def make_dir(self, path: str) -> FileEntry: + """Create a directory (with parents). Idempotent. + + Args: + path (str): Absolute path of the directory to create. + + Returns: + FileEntry: The created (or already-existing) directory entry. + """ + resp = self._http.post( + f"/v1/capsules/{self._capsule_id}/files/mkdir", + json={"path": path}, + ) + if resp.status_code == 409: + try: + body = resp.json() + if body.get("error", {}).get("code") == "conflict": + parent = os.path.dirname(path) + name = os.path.basename(path) + for entry in self.list(parent, depth=1): + if entry.name == name: + return entry + except Exception: + pass + parsed = MakeDirResponse.model_validate(handle_response(resp)) + if parsed.entry is None: + raise RuntimeError("mkdir response missing entry") + return parsed.entry + + def remove(self, path: str) -> None: + """Remove a file or directory recursively. + + Args: + path (str): Absolute path to remove. + + Raises: + WrennNotFoundError: If the path does not exist. + """ + resp = self._http.post( + f"/v1/capsules/{self._capsule_id}/files/remove", + json={"path": path}, + ) + handle_response(resp) + + def upload_stream(self, path: str, stream: Iterator[bytes]) -> None: + """Stream a large file into the capsule. + + Prefer this over :meth:`write` when the file is too large to hold in + memory. + + Args: + path (str): Absolute destination path inside the capsule. + stream (Iterator[bytes]): Iterable of byte chunks to upload. + """ + boundary = os.urandom(16).hex().encode("utf-8") + + def _multipart() -> Iterator[bytes]: + yield b"--" + boundary + b"\r\n" + yield b'Content-Disposition: form-data; name="path"\r\n\r\n' + yield path.encode("utf-8") + b"\r\n" + yield b"--" + boundary + b"\r\n" + yield b'Content-Disposition: form-data; name="file"; filename="upload.bin"\r\n' + yield b"Content-Type: application/octet-stream\r\n\r\n" + for chunk in stream: + yield chunk if isinstance(chunk, bytes) else chunk.encode("utf-8") + yield b"\r\n--" + boundary + b"--\r\n" + + resp = self._http.post( + f"/v1/capsules/{self._capsule_id}/files/stream/write", + content=_multipart(), + headers={ + "Content-Type": f"multipart/form-data; boundary={boundary.decode('utf-8')}" + }, + ) + resp.raise_for_status() + + def download_stream(self, path: str) -> Iterator[bytes]: + """Stream a large file out of the capsule. + + Prefer this over :meth:`read_bytes` when the file is too large to hold + in memory. + + Args: + path (str): Absolute path to the file inside the capsule. + + Yields: + bytes: Successive byte chunks of the file. + + Raises: + WrennNotFoundError: If the path does not exist. + """ + with self._http.stream( + "POST", + f"/v1/capsules/{self._capsule_id}/files/stream/read", + json={"path": path}, + ) as resp: + resp.raise_for_status() + yield from resp.iter_bytes() + + +class AsyncFiles: + """Async filesystem interface. Accessed via ``capsule.files``.""" + + def __init__(self, capsule_id: str, http: httpx.AsyncClient) -> None: + self._capsule_id = capsule_id + self._http = http + + async def read(self, path: str) -> str: + """Read a file as a UTF-8 string. + + Args: + path (str): Absolute path to the file inside the capsule. + + Returns: + str: File contents decoded as UTF-8. + + Raises: + WrennNotFoundError: If the path does not exist. + """ + data = await self.read_bytes(path) + return data.decode("utf-8", errors="replace") + + async def read_bytes(self, path: str) -> bytes: + """Read a file as raw bytes. + + Args: + path (str): Absolute path to the file inside the capsule. + + Returns: + bytes: Raw file contents. + + Raises: + WrennNotFoundError: If the path does not exist. + """ + resp = await self._http.post( + f"/v1/capsules/{self._capsule_id}/files/read", + json={"path": path}, + ) + resp.raise_for_status() + return resp.content + + async def write(self, path: str, data: str | bytes) -> None: + """Write data to a file inside the capsule. + + Creates parent directories if they do not exist. + + Args: + path (str): Absolute destination path inside the capsule. + data (str | bytes): Content to write. Strings are UTF-8 encoded. + """ + if isinstance(data, str): + data = data.encode("utf-8") + resp = await self._http.post( + f"/v1/capsules/{self._capsule_id}/files/write", + files={"file": ("upload", data)}, + data={"path": path}, + ) + resp.raise_for_status() + + async def list(self, path: str, depth: int = 1) -> list[FileEntry]: + """List directory contents. + + Args: + path (str): Absolute path to the directory inside the capsule. + depth (int): Recursion depth. ``1`` lists only immediate children. + Defaults to ``1``. + + Returns: + list[FileEntry]: Entries in the directory. + + Raises: + WrennNotFoundError: If the path does not exist. + """ + resp = await self._http.post( + f"/v1/capsules/{self._capsule_id}/files/list", + json={"path": path, "depth": depth}, + ) + parsed = ListDirResponse.model_validate(handle_response(resp)) + return parsed.entries or [] + + async def exists(self, path: str) -> bool: + """Check whether a path exists inside the capsule. + + Args: + path (str): Absolute path to check. + + Returns: + bool: ``True`` if the path exists. + """ + parent = os.path.dirname(path) + name = os.path.basename(path) + try: + entries = await self.list(parent, depth=1) + except WrennNotFoundError: + return False + return any(e.name == name for e in entries) + + async def make_dir(self, path: str) -> FileEntry: + """Create a directory (with parents). Idempotent. + + Args: + path (str): Absolute path of the directory to create. + + Returns: + FileEntry: The created (or already-existing) directory entry. + """ + resp = await self._http.post( + f"/v1/capsules/{self._capsule_id}/files/mkdir", + json={"path": path}, + ) + if resp.status_code == 409: + try: + body = resp.json() + if body.get("error", {}).get("code") == "conflict": + parent = os.path.dirname(path) + name = os.path.basename(path) + for entry in await self.list(parent, depth=1): + if entry.name == name: + return entry + except Exception: + pass + parsed = MakeDirResponse.model_validate(handle_response(resp)) + if parsed.entry is None: + raise RuntimeError("mkdir response missing entry") + return parsed.entry + + async def remove(self, path: str) -> None: + """Remove a file or directory recursively. + + Args: + path (str): Absolute path to remove. + + Raises: + WrennNotFoundError: If the path does not exist. + """ + resp = await self._http.post( + f"/v1/capsules/{self._capsule_id}/files/remove", + json={"path": path}, + ) + handle_response(resp) + + async def upload_stream(self, path: str, stream: AsyncIterator[bytes]) -> None: + """Stream a large file into the capsule. + + Prefer this over :meth:`write` when the file is too large to hold in + memory. + + Args: + path (str): Absolute destination path inside the capsule. + stream (AsyncIterator[bytes]): Async iterable of byte chunks to + upload. + """ + boundary = os.urandom(16).hex().encode("utf-8") + + async def _multipart() -> AsyncIterator[bytes]: + yield b"--" + boundary + b"\r\n" + yield b'Content-Disposition: form-data; name="path"\r\n\r\n' + yield path.encode("utf-8") + b"\r\n" + yield b"--" + boundary + b"\r\n" + yield b'Content-Disposition: form-data; name="file"; filename="upload.bin"\r\n' + yield b"Content-Type: application/octet-stream\r\n\r\n" + async for chunk in stream: + yield chunk if isinstance(chunk, bytes) else chunk.encode("utf-8") + yield b"\r\n--" + boundary + b"--\r\n" + + resp = await self._http.post( + f"/v1/capsules/{self._capsule_id}/files/stream/write", + content=_multipart(), + headers={ + "Content-Type": f"multipart/form-data; boundary={boundary.decode('utf-8')}" + }, + ) + resp.raise_for_status() + + async def download_stream(self, path: str) -> AsyncIterator[bytes]: + """Stream a large file out of the capsule. + + Prefer this over :meth:`read_bytes` when the file is too large to hold + in memory. + + Args: + path (str): Absolute path to the file inside the capsule. + + Yields: + bytes: Successive byte chunks of the file. + + Raises: + WrennNotFoundError: If the path does not exist. + """ + async with self._http.stream( + "POST", + f"/v1/capsules/{self._capsule_id}/files/stream/read", + json={"path": path}, + ) as resp: + resp.raise_for_status() + async for chunk in resp.aiter_bytes(): + yield chunk diff --git a/src/wrenn/models/__init__.py b/src/wrenn/models/__init__.py new file mode 100644 index 0000000..5628e11 --- /dev/null +++ b/src/wrenn/models/__init__.py @@ -0,0 +1,67 @@ +from wrenn.models._generated import ( + APIKeyResponse, + AuthResponse, + Capsule, + CreateAPIKeyRequest, + CreateCapsuleRequest, + CreateHostRequest, + CreateHostResponse, + CreateSnapshotRequest, + Encoding, + Error, + Error1, + ExecRequest, + ExecResponse, + FileEntry, + Host, + ListDirRequest, + ListDirResponse, + LoginRequest, + MakeDirRequest, + MakeDirResponse, + ReadFileRequest, + RegisterHostRequest, + RegisterHostResponse, + RemoveRequest, + SignupRequest, + Status, + Status1, + Template, + Type, + Type1, + Type2, +) + +__all__ = [ + "APIKeyResponse", + "AuthResponse", + "CreateAPIKeyRequest", + "CreateHostRequest", + "CreateHostResponse", + "CreateCapsuleRequest", + "CreateSnapshotRequest", + "Encoding", + "Error", + "Error1", + "ExecRequest", + "ExecResponse", + "FileEntry", + "Host", + "ListDirRequest", + "ListDirResponse", + "LoginRequest", + "MakeDirRequest", + "MakeDirResponse", + "ReadFileRequest", + "RegisterHostRequest", + "RegisterHostResponse", + "RemoveRequest", + "Capsule", + "SignupRequest", + "Status", + "Status1", + "Template", + "Type", + "Type1", + "Type2", +] diff --git a/src/wrenn/models/_generated.py b/src/wrenn/models/_generated.py new file mode 100644 index 0000000..5542c2f --- /dev/null +++ b/src/wrenn/models/_generated.py @@ -0,0 +1,625 @@ +# generated by datamodel-codegen: +# filename: openapi.yaml +# timestamp: 2026-04-22T20:21:34+00:00 + +from __future__ import annotations +from pydantic import AwareDatetime, BaseModel, EmailStr, Field +from typing import Annotated +from datetime import date as date_aliased +from enum import StrEnum + + +class SignupRequest(BaseModel): + email: EmailStr + password: Annotated[str, Field(min_length=8)] + name: Annotated[str, Field(max_length=100)] + + +class LoginRequest(BaseModel): + email: EmailStr + password: str + + +class SignupResponse(BaseModel): + message: Annotated[ + str | None, + Field(description="Confirmation message instructing user to check email"), + ] = None + + +class AuthResponse(BaseModel): + token: Annotated[str | None, Field(description="JWT token (valid for 6 hours)")] = ( + None + ) + user_id: str | None = None + team_id: str | None = None + email: str | None = None + name: str | None = None + + +class CreateAPIKeyRequest(BaseModel): + name: str | None = "Unnamed API Key" + + +class APIKeyResponse(BaseModel): + id: str | None = None + team_id: str | None = None + name: str | None = None + key_prefix: Annotated[ + str | None, Field(description='Display prefix (e.g. "wrn_ab12cd34...")') + ] = None + created_at: AwareDatetime | None = None + last_used: AwareDatetime | None = None + key: Annotated[ + str | None, + Field( + description="Full plaintext key. Only returned on creation, never again." + ), + ] = None + + +class CreateCapsuleRequest(BaseModel): + template: str | None = "minimal" + vcpus: int | None = 1 + memory_mb: int | None = 512 + timeout_sec: Annotated[ + int | None, + Field( + description="Auto-pause TTL in seconds. The capsule is automatically paused after this duration of inactivity (no exec or ping). 0 means no auto-pause.\n" + ), + ] = 0 + + +class Point(BaseModel): + date: date_aliased | None = None + cpu_minutes: float | None = None + ram_mb_minutes: float | None = None + + +class UsageResponse(BaseModel): + from_: Annotated[date_aliased | None, Field(alias="from")] = None + to: date_aliased | None = None + points: list[Point] | None = None + + +class Range(StrEnum): + field_5m = "5m" + field_1h = "1h" + field_6h = "6h" + field_24h = "24h" + field_30d = "30d" + + +class Current(BaseModel): + running_count: int | None = None + vcpus_reserved: int | None = None + memory_mb_reserved: int | None = None + sampled_at: AwareDatetime | None = None + + +class Peaks(BaseModel): + """ + Maximum values over the last 30 days. + """ + + running_count: int | None = None + vcpus: int | None = None + memory_mb: int | None = None + + +class Series(BaseModel): + """ + Parallel arrays for chart rendering. + """ + + labels: list[AwareDatetime] | None = None + running: list[int] | None = None + vcpus: list[int] | None = None + memory_mb: list[int] | None = None + + +class CapsuleStats(BaseModel): + range: Range | None = None + current: Current | None = None + peaks: Annotated[ + Peaks | None, Field(description="Maximum values over the last 30 days.") + ] = None + series: Annotated[ + Series | None, Field(description="Parallel arrays for chart rendering.") + ] = None + + +class Status(StrEnum): + pending = "pending" + starting = "starting" + running = "running" + paused = "paused" + hibernated = "hibernated" + stopped = "stopped" + missing = "missing" + error = "error" + + +class Capsule(BaseModel): + id: str | None = None + status: Status | None = None + template: str | None = None + vcpus: int | None = None + memory_mb: int | None = None + timeout_sec: int | None = None + guest_ip: str | None = None + host_ip: str | None = None + created_at: AwareDatetime | None = None + started_at: AwareDatetime | None = None + last_active_at: AwareDatetime | None = None + last_updated: AwareDatetime | None = None + + +class CreateSnapshotRequest(BaseModel): + sandbox_id: Annotated[ + str, Field(description="ID of the running capsule to snapshot.") + ] + name: Annotated[ + str | None, + Field(description="Name for the snapshot template. Auto-generated if omitted."), + ] = None + + +class Type(StrEnum): + base = "base" + snapshot = "snapshot" + + +class Template(BaseModel): + name: str | None = None + type: Type | None = None + vcpus: int | None = None + memory_mb: int | None = None + size_bytes: int | None = None + created_at: AwareDatetime | None = None + + +class ExecRequest(BaseModel): + cmd: str + args: list[str] | None = None + timeout_sec: Annotated[ + int | None, + Field(description="Timeout in seconds (foreground exec only, default 30)"), + ] = 30 + background: Annotated[ + bool | None, + Field( + description="If true, starts the process in the background and returns immediately with a PID and tag (HTTP 202)" + ), + ] = False + tag: Annotated[ + str | None, + Field( + description="Optional user-chosen tag for the background process. Auto-generated if omitted. Only used when background is true." + ), + ] = None + envs: Annotated[ + dict[str, str] | None, + Field( + description="Environment variables for the process (background exec only)" + ), + ] = None + cwd: Annotated[ + str | None, + Field(description="Working directory for the process (background exec only)"), + ] = None + + +class BackgroundExecResponse(BaseModel): + sandbox_id: str | None = None + cmd: str | None = None + pid: int | None = None + tag: str | None = None + + +class ProcessEntry(BaseModel): + pid: int | None = None + tag: str | None = None + cmd: str | None = None + args: list[str] | None = None + + +class ProcessListResponse(BaseModel): + processes: list[ProcessEntry] | None = None + + +class Encoding(StrEnum): + """ + Output encoding. "base64" when stdout/stderr contain binary data. + """ + + utf_8 = "utf-8" + base64 = "base64" + + +class ExecResponse(BaseModel): + sandbox_id: str | None = None + cmd: str | None = None + stdout: str | None = None + stderr: str | None = None + exit_code: int | None = None + duration_ms: int | None = None + encoding: Annotated[ + Encoding | None, + Field( + description='Output encoding. "base64" when stdout/stderr contain binary data.' + ), + ] = None + + +class ReadFileRequest(BaseModel): + path: Annotated[str, Field(description="Absolute file path inside the capsule")] + + +class ListDirRequest(BaseModel): + path: Annotated[str, Field(description="Directory path inside the capsule")] + depth: Annotated[ + int | None, + Field( + description="Recursion depth (0 = non-recursive, 1 = immediate children)" + ), + ] = 1 + + +class Type1(StrEnum): + file = "file" + directory = "directory" + symlink = "symlink" + + +class FileEntry(BaseModel): + name: str | None = None + path: str | None = None + type: Type1 | None = None + size: int | None = None + mode: int | None = None + permissions: Annotated[ + str | None, Field(description='Human-readable permissions (e.g. "-rwxr-xr-x")') + ] = None + owner: str | None = None + group: str | None = None + modified_at: Annotated[ + int | None, Field(description="Unix timestamp (seconds)") + ] = None + symlink_target: str | None = None + + +class MakeDirRequest(BaseModel): + path: Annotated[ + str, Field(description="Directory path to create inside the capsule") + ] + + +class MakeDirResponse(BaseModel): + entry: FileEntry | None = None + + +class RemoveRequest(BaseModel): + path: Annotated[str, Field(description="Path to remove inside the capsule")] + + +class Type2(StrEnum): + """ + Host type. Regular hosts are shared; BYOC hosts belong to a team. + """ + + regular = "regular" + byoc = "byoc" + + +class CreateHostRequest(BaseModel): + type: Annotated[ + Type2, + Field( + description="Host type. Regular hosts are shared; BYOC hosts belong to a team." + ), + ] + team_id: Annotated[str | None, Field(description="Required for BYOC hosts.")] = None + provider: Annotated[ + str | None, + Field(description="Cloud provider (e.g. aws, gcp, hetzner, bare-metal)."), + ] = None + availability_zone: Annotated[ + str | None, Field(description="Availability zone (e.g. us-east, eu-west).") + ] = None + + +class RegisterHostRequest(BaseModel): + token: Annotated[ + str, Field(description="One-time registration token from POST /v1/hosts.") + ] + arch: Annotated[ + str | None, Field(description="CPU architecture (e.g. x86_64, aarch64).") + ] = None + cpu_cores: int | None = None + memory_mb: int | None = None + disk_gb: int | None = None + address: Annotated[str, Field(description="Host agent address (ip:port).")] + + +class Type3(StrEnum): + regular = "regular" + byoc = "byoc" + + +class Status1(StrEnum): + pending = "pending" + online = "online" + offline = "offline" + draining = "draining" + unreachable = "unreachable" + + +class Host(BaseModel): + id: str | None = None + type: Type3 | None = None + team_id: str | None = None + provider: str | None = None + availability_zone: str | None = None + arch: str | None = None + cpu_cores: int | None = None + memory_mb: int | None = None + disk_gb: int | None = None + address: str | None = None + status: Status1 | None = None + last_heartbeat_at: AwareDatetime | None = None + created_by: str | None = None + created_at: AwareDatetime | None = None + updated_at: AwareDatetime | None = None + + +class RefreshHostTokenRequest(BaseModel): + refresh_token: Annotated[ + str, + Field( + description="Refresh token obtained from registration or a previous refresh." + ), + ] + + +class RefreshHostTokenResponse(BaseModel): + host: Host | None = None + token: Annotated[ + str | None, Field(description="New host JWT. Valid for 7 days.") + ] = None + refresh_token: Annotated[ + str | None, + Field( + description="New refresh token. Valid for 60 days; old token is revoked." + ), + ] = None + + +class HostDeletePreview(BaseModel): + host: Host | None = None + sandbox_ids: Annotated[ + list[str] | None, + Field(description="IDs of capsulees that would be destroyed on force-delete."), + ] = None + + +class Error(BaseModel): + code: Annotated[str | None, Field(examples=["host_has_sandboxes"])] = None + message: str | None = None + sandbox_ids: Annotated[ + list[str] | None, + Field(description="IDs of active capsulees blocking deletion."), + ] = None + + +class HostHasCapsulesError(BaseModel): + error: Error | None = None + + +class AddTagRequest(BaseModel): + tag: str + + +class UserSearchResult(BaseModel): + user_id: str | None = None + email: str | None = None + + +class Team(BaseModel): + id: str | None = None + name: str | None = None + slug: Annotated[ + str | None, Field(description="Immutable 12-char hex slug (e.g. a1b2c3-d1e2f3)") + ] = None + created_at: AwareDatetime | None = None + + +class Role(StrEnum): + owner = "owner" + admin = "admin" + member = "member" + + +class TeamWithRole(Team): + role: Role | None = None + + +class TeamMember(BaseModel): + user_id: str | None = None + email: str | None = None + role: Role | None = None + joined_at: AwareDatetime | None = None + + +class TeamDetail(BaseModel): + team: Team | None = None + members: list[TeamMember] | None = None + + +class Range1(StrEnum): + field_5m = "5m" + field_10m = "10m" + field_1h = "1h" + field_2h = "2h" + field_6h = "6h" + field_12h = "12h" + field_24h = "24h" + + +class MetricPoint(BaseModel): + timestamp_unix: int | None = None + cpu_pct: Annotated[ + float | None, + Field( + description="CPU utilization percentage (0-100), normalized to vCPU count" + ), + ] = None + mem_bytes: Annotated[ + int | None, + Field(description="Resident memory in bytes (VmRSS of Firecracker process)"), + ] = None + disk_bytes: Annotated[ + int | None, Field(description="Allocated disk bytes for the CoW sparse file") + ] = None + + +class Provider(StrEnum): + discord = "discord" + slack = "slack" + teams = "teams" + googlechat = "googlechat" + telegram = "telegram" + matrix = "matrix" + webhook = "webhook" + + +class Event(StrEnum): + capsule_created = "capsule.created" + capsule_running = "capsule.running" + capsule_paused = "capsule.paused" + capsule_destroyed = "capsule.destroyed" + template_snapshot_created = "template.snapshot.created" + template_snapshot_deleted = "template.snapshot.deleted" + host_up = "host.up" + host_down = "host.down" + + +class CreateChannelRequest(BaseModel): + name: Annotated[str, Field(description="Unique channel name within the team.")] + provider: Provider + config: Annotated[ + dict[str, str], + Field( + description='Provider-specific configuration fields. Discord/Slack/Teams/Google Chat: {"webhook_url": "..."}. Telegram: {"bot_token": "...", "chat_id": "..."}. Matrix: {"homeserver_url": "...", "access_token": "...", "room_id": "..."}. Webhook: {"url": "...", "secret": "..."} (secret is auto-generated if omitted).\n' + ), + ] + events: list[Event] + + +class TestChannelRequest(BaseModel): + provider: Provider + config: Annotated[ + dict[str, str], + Field( + description="Provider-specific configuration fields (same as CreateChannelRequest.config)." + ), + ] + + +class RotateConfigRequest(BaseModel): + config: Annotated[ + dict[str, str], + Field( + description="New provider configuration fields. Must include all required fields for the channel's provider. Replaces the existing config entirely.\n" + ), + ] + + +class UpdateChannelRequest(BaseModel): + name: str + events: list[Event] + + +class ChannelResponse(BaseModel): + id: str | None = None + team_id: str | None = None + name: str | None = None + provider: Provider | None = None + events: list[str] | None = None + created_at: AwareDatetime | None = None + updated_at: AwareDatetime | None = None + secret: Annotated[ + str | None, + Field(description="Webhook secret. Only returned on creation, never again."), + ] = None + + +class MeResponse(BaseModel): + name: str | None = None + email: EmailStr | None = None + has_password: Annotated[ + bool | None, + Field( + description="Whether the user has a password set (false for OAuth-only accounts)" + ), + ] = None + providers: Annotated[ + list[str] | None, + Field(description='List of linked OAuth provider names (e.g. ["github"])'), + ] = None + + +class ChangePasswordRequest(BaseModel): + current_password: Annotated[ + str | None, Field(description="Required when changing an existing password") + ] = None + new_password: Annotated[str, Field(min_length=8)] + confirm_password: Annotated[ + str | None, + Field( + description="Required when adding a password to an OAuth-only account (must match new_password)" + ), + ] = None + + +class Error2(BaseModel): + code: str | None = None + message: str | None = None + + +class Error1(BaseModel): + error: Error2 | None = None + + +class ListDirResponse(BaseModel): + entries: list[FileEntry] | None = None + + +class CreateHostResponse(BaseModel): + host: Host | None = None + registration_token: Annotated[ + str | None, + Field( + description="One-time registration token for the host agent. Expires in 1 hour." + ), + ] = None + + +class RegisterHostResponse(BaseModel): + host: Host | None = None + token: Annotated[ + str | None, + Field(description="Host JWT for X-Host-Token header. Valid for 7 days."), + ] = None + refresh_token: Annotated[ + str | None, + Field( + description="Refresh token for obtaining new JWTs. Valid for 60 days; rotated on each use." + ), + ] = None + + +class CapsuleMetrics(BaseModel): + sandbox_id: str | None = None + range: Range1 | None = None + points: list[MetricPoint] | None = None diff --git a/src/wrenn/pty.py b/src/wrenn/pty.py new file mode 100644 index 0000000..83ee871 --- /dev/null +++ b/src/wrenn/pty.py @@ -0,0 +1,306 @@ +from __future__ import annotations + +import base64 +import json +from collections.abc import AsyncIterator, Iterator +from enum import StrEnum +from typing import Any + +import httpx_ws +from pydantic import BaseModel + + +class PtyEventType(StrEnum): + started = "started" + output = "output" + exit = "exit" + error = "error" + ping = "ping" + + +class PtyEvent(BaseModel): + type: PtyEventType + pid: int | None = None + tag: str | None = None + data: bytes | str | None = None + exit_code: int | None = None + fatal: bool | None = None + + +def _parse_pty_event(raw: dict[str, Any]) -> PtyEvent: + msg_type = raw.get("type", "") + if msg_type == "started": + return PtyEvent( + type=PtyEventType.started, + pid=raw.get("pid"), + tag=raw.get("tag"), + ) + if msg_type == "output": + raw_data = raw.get("data", "") + decoded = base64.b64decode(raw_data) if raw_data else b"" + return PtyEvent(type=PtyEventType.output, data=decoded) + if msg_type == "exit": + return PtyEvent(type=PtyEventType.exit, exit_code=raw.get("exit_code", -1)) + if msg_type == "error": + return PtyEvent( + type=PtyEventType.error, + data=raw.get("data", ""), + fatal=raw.get("fatal", False), + ) + if msg_type == "ping": + return PtyEvent(type=PtyEventType.ping) + return PtyEvent(type=PtyEventType(msg_type) if msg_type else PtyEventType.ping) + + +class PtySession: + """Interactive PTY session backed by a WebSocket. + + Use as a context manager and iterate over events:: + + with sb.pty(cmd="/bin/bash") as term: + term.write(b"ls -la\\n") + for event in term: + if event.type == "output": + sys.stdout.buffer.write(event.data) + elif event.type == "exit": + break + """ + + def __init__(self, ws: httpx_ws.WebSocketSession, capsule_id: str) -> None: + self._ws = ws + self._capsule_id = capsule_id + self._tag: str | None = None + self._pid: int | None = None + self._done = False + + @property + def tag(self) -> str | None: + """Session tag. Available after the ``started`` event.""" + return self._tag + + @property + def pid(self) -> int | None: + """Process PID. Available after the ``started`` event.""" + return self._pid + + def _send_start( + self, + cmd: str = "/bin/bash", + args: list[str] | None = None, + cols: int = 80, + rows: int = 24, + envs: dict[str, str] | None = None, + cwd: str | None = None, + ) -> None: + msg: dict[str, Any] = { + "type": "start", + "cmd": cmd, + "cols": cols or 80, + "rows": rows or 24, + } + if args: + msg["args"] = args + if envs: + msg["envs"] = envs + if cwd: + msg["cwd"] = cwd + self._ws.send_text(json.dumps(msg)) + + def _send_connect(self, tag: str) -> None: + self._ws.send_text(json.dumps({"type": "connect", "tag": tag})) + + def write(self, data: bytes) -> None: + """Send raw bytes to the PTY stdin. + + Args: + data: Raw bytes to send. Base64-encoded internally. + """ + encoded = base64.b64encode(data).decode("ascii") + self._ws.send_text(json.dumps({"type": "input", "data": encoded})) + + def resize(self, cols: int, rows: int) -> None: + """Resize the PTY terminal. + + Args: + cols: New column count. Must be > 0. + rows: New row count. Must be > 0. + + Raises: + ValueError: If cols or rows is 0. + """ + if cols <= 0 or rows <= 0: + raise ValueError("cols and rows must be greater than 0") + self._ws.send_text(json.dumps({"type": "resize", "cols": cols, "rows": rows})) + + def kill(self) -> None: + """Send SIGKILL to the PTY process.""" + self._ws.send_text(json.dumps({"type": "kill"})) + + def __iter__(self) -> Iterator[PtyEvent]: + return self + + def __next__(self) -> PtyEvent: + if self._done: + raise StopIteration + try: + raw = self._ws.receive_text() + except httpx_ws.WebSocketDisconnect: + raise StopIteration + event = _parse_pty_event(json.loads(raw)) + if event.type == PtyEventType.started: + if event.tag is not None: + self._tag = event.tag + if event.pid is not None: + self._pid = event.pid + if event.type == PtyEventType.exit: + raise StopIteration + if event.type == PtyEventType.error and event.fatal: + self._done = True + return event + return event + + def __enter__(self) -> PtySession: + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: object, + ) -> None: + try: + self.kill() + except Exception: + pass + try: + self._ws.close() + except Exception: + pass + + +class AsyncPtySession: + """Async interactive PTY session backed by a WebSocket. + + Use as an async context manager and async iterate over events:: + + async with sb.pty(cmd="/bin/bash") as term: + await term.write(b"ls -la\\n") + async for event in term: + if event.type == "output": + sys.stdout.buffer.write(event.data) + elif event.type == "exit": + break + """ + + def __init__(self, ws: httpx_ws.AsyncWebSocketSession, capsule_id: str) -> None: + self._ws = ws + self._capsule_id = capsule_id + self._tag: str | None = None + self._pid: int | None = None + self._done = False + + @property + def tag(self) -> str | None: + """Session tag. Available after the ``started`` event.""" + return self._tag + + @property + def pid(self) -> int | None: + """Process PID. Available after the ``started`` event.""" + return self._pid + + async def _send_start( + self, + cmd: str = "/bin/bash", + args: list[str] | None = None, + cols: int = 80, + rows: int = 24, + envs: dict[str, str] | None = None, + cwd: str | None = None, + ) -> None: + msg: dict[str, Any] = { + "type": "start", + "cmd": cmd, + "cols": cols or 80, + "rows": rows or 24, + } + if args: + msg["args"] = args + if envs: + msg["envs"] = envs + if cwd: + msg["cwd"] = cwd + await self._ws.send_text(json.dumps(msg)) + + async def _send_connect(self, tag: str) -> None: + await self._ws.send_text(json.dumps({"type": "connect", "tag": tag})) + + async def write(self, data: bytes) -> None: + """Send raw bytes to the PTY stdin. + + Args: + data: Raw bytes to send. Base64-encoded internally. + """ + encoded = base64.b64encode(data).decode("ascii") + await self._ws.send_text(json.dumps({"type": "input", "data": encoded})) + + async def resize(self, cols: int, rows: int) -> None: + """Resize the PTY terminal. + + Args: + cols: New column count. Must be > 0. + rows: New row count. Must be > 0. + + Raises: + ValueError: If cols or rows is 0. + """ + if cols <= 0 or rows <= 0: + raise ValueError("cols and rows must be greater than 0") + await self._ws.send_text( + json.dumps({"type": "resize", "cols": cols, "rows": rows}) + ) + + async def kill(self) -> None: + """Send SIGKILL to the PTY process.""" + await self._ws.send_text(json.dumps({"type": "kill"})) + + def __aiter__(self) -> AsyncIterator[PtyEvent]: + return self + + async def __anext__(self) -> PtyEvent: + if self._done: + raise StopAsyncIteration + try: + raw = await self._ws.receive_text() + except httpx_ws.WebSocketDisconnect: + raise StopAsyncIteration + event = _parse_pty_event(json.loads(raw)) + if event.type == PtyEventType.started: + if event.tag is not None: + self._tag = event.tag + if event.pid is not None: + self._pid = event.pid + if event.type == PtyEventType.exit: + raise StopAsyncIteration + if event.type == PtyEventType.error and event.fatal: + self._done = True + return event + return event + + async def __aenter__(self) -> AsyncPtySession: + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: object, + ) -> None: + try: + await self.kill() + except Exception: + pass + try: + await self._ws.close() + except Exception: + pass diff --git a/src/wrenn/sandbox.py b/src/wrenn/sandbox.py new file mode 100644 index 0000000..1b2499c --- /dev/null +++ b/src/wrenn/sandbox.py @@ -0,0 +1,22 @@ +import warnings as _warnings + +from wrenn.capsule import Capsule # noqa: F401 +from wrenn.commands import ( # noqa: F401 + StreamErrorEvent, + StreamEvent, + StreamExitEvent, + StreamStartEvent, + StreamStderrEvent, + StreamStdoutEvent, +) + + +def __getattr__(name: str) -> type: + if name == "Sandbox": + _warnings.warn( + "'Sandbox' is deprecated, use 'Capsule' instead", + FutureWarning, + stacklevel=2, + ) + return Capsule + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000..e0a7d65 --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,37 @@ +from __future__ import annotations + +import os +from pathlib import Path + +import pytest + +ENV_FILE = Path(__file__).resolve().parent.parent / ".env" + + +def _read_env_file() -> dict[str, str]: + result: dict[str, str] = {} + if not ENV_FILE.exists(): + return result + for line in ENV_FILE.read_text().splitlines(): + line = line.strip() + if not line or line.startswith("#") or "=" not in line: + continue + key, _, value = line.partition("=") + key = key.strip() + value = value.strip().strip("\"'") + if key: + result[key] = value + return result + + +def pytest_collection_modifyitems( + config: pytest.Config, items: list[pytest.Item] +) -> None: + env_vars = _read_env_file() + has_key = bool(os.environ.get("WRENN_API_KEY") or env_vars.get("WRENN_API_KEY")) + if has_key: + return + skip = pytest.mark.skip(reason="WRENN_API_KEY not set") + for item in items: + if "integration" in item.keywords: + item.add_marker(skip) diff --git a/tests/test_capsule_features.py b/tests/test_capsule_features.py new file mode 100644 index 0000000..5c630da --- /dev/null +++ b/tests/test_capsule_features.py @@ -0,0 +1,197 @@ +from __future__ import annotations + +import respx + +from wrenn.capsule import Capsule, _build_proxy_url +from wrenn.code_interpreter.models import Execution, ExecutionError, Logs, Result + +BASE = "https://app.wrenn.dev/api" + + +class TestBuildProxyUrl: + def test_https_production(self): + url = _build_proxy_url("https://app.wrenn.dev/api", "cl-abc123", 8888) + assert url == "wss://8888-cl-abc123.app.wrenn.dev" + + def test_http_localhost(self): + url = _build_proxy_url("http://localhost:8080", "cl-abc123", 3000) + assert url == "ws://3000-cl-abc123.localhost:8080" + + def test_https_custom_port(self): + url = _build_proxy_url("https://api.example.com:9443", "sb-1", 8080) + assert url == "wss://8080-sb-1.api.example.com:9443" + + def test_http_no_port(self): + url = _build_proxy_url("http://192.168.1.1", "sb-2", 5000) + assert url == "ws://5000-sb-2.192.168.1.1" + + +class TestCapsuleCreate: + @respx.mock + def test_capsule_constructor_creates(self): + respx.post(f"{BASE}/v1/capsules").respond( + 201, json={"id": "cl-1", "status": "pending", "template": "minimal"} + ) + cap = Capsule(template="minimal", api_key="wrn_test1234567890abcdef12345678") + assert cap.capsule_id == "cl-1" + assert hasattr(cap, "commands") + assert hasattr(cap, "files") + + @respx.mock + def test_capsule_create_classmethod(self): + respx.post(f"{BASE}/v1/capsules").respond( + 201, json={"id": "cl-2", "status": "pending"} + ) + cap = Capsule.create(api_key="wrn_test1234567890abcdef12345678") + assert cap.capsule_id == "cl-2" + + @respx.mock + def test_capsule_context_manager_kills(self): + respx.post(f"{BASE}/v1/capsules").respond( + 201, json={"id": "cl-1", "status": "pending"} + ) + kill_route = respx.delete(f"{BASE}/v1/capsules/cl-1").respond(204) + with Capsule(api_key="wrn_test1234567890abcdef12345678") as cap: + assert cap.capsule_id == "cl-1" + assert kill_route.called + + @respx.mock + def test_capsule_env_var(self, monkeypatch): + monkeypatch.setenv("WRENN_API_KEY", "wrn_from_env_key") + respx.post(f"{BASE}/v1/capsules").respond( + 201, json={"id": "cl-3", "status": "pending"} + ) + cap = Capsule() + assert cap.capsule_id == "cl-3" + + +class TestCapsuleStaticMethods: + @respx.mock + def test_static_destroy(self): + route = respx.delete(f"{BASE}/v1/capsules/cl-1").respond(204) + Capsule._static_destroy("cl-1", api_key="wrn_test1234567890abcdef12345678") + assert route.called + + @respx.mock + def test_static_pause(self): + respx.post(f"{BASE}/v1/capsules/cl-1/pause").respond( + 200, json={"id": "cl-1", "status": "paused"} + ) + info = Capsule._static_pause("cl-1", api_key="wrn_test1234567890abcdef12345678") + assert info.status.value == "paused" + + @respx.mock + def test_static_list(self): + respx.get(f"{BASE}/v1/capsules").respond( + 200, json=[{"id": "cl-1", "status": "running"}] + ) + items = Capsule.list(api_key="wrn_test1234567890abcdef12345678") + assert len(items) == 1 + assert items[0].id == "cl-1" + + @respx.mock + def test_static_get_info(self): + respx.get(f"{BASE}/v1/capsules/cl-1").respond( + 200, json={"id": "cl-1", "status": "running"} + ) + info = Capsule._static_get_info( + "cl-1", api_key="wrn_test1234567890abcdef12345678" + ) + assert info.id == "cl-1" + + +class TestCapsuleConnect: + @respx.mock + def test_connect_running(self): + respx.get(f"{BASE}/v1/capsules/cl-1").respond( + 200, json={"id": "cl-1", "status": "running"} + ) + cap = Capsule.connect("cl-1", api_key="wrn_test1234567890abcdef12345678") + assert cap.capsule_id == "cl-1" + + @respx.mock + def test_connect_paused_resumes(self): + respx.get(f"{BASE}/v1/capsules/cl-1").respond( + 200, json={"id": "cl-1", "status": "paused"} + ) + respx.post(f"{BASE}/v1/capsules/cl-1/resume").respond( + 200, json={"id": "cl-1", "status": "running"} + ) + cap = Capsule.connect("cl-1", api_key="wrn_test1234567890abcdef12345678") + assert cap.capsule_id == "cl-1" + + +class TestExecutionModels: + def test_execution_defaults(self): + e = Execution() + assert e.results == [] + assert e.logs.stdout == [] + assert e.logs.stderr == [] + assert e.error is None + assert e.text is None + + def test_result_from_bundle(self): + bundle = {"text/plain": "84", "image/png": "base64data"} + r = Result.from_bundle(bundle, is_main_result=True) + assert r.text == "84" + assert r.png == "base64data" + assert r.is_main_result is True + + def test_result_from_bundle_strips_quotes(self): + bundle = {"text/plain": "'hello'"} + r = Result.from_bundle(bundle) + assert r.text == "hello" + + def test_result_from_bundle_extra_mimes(self): + bundle = {"text/plain": "x", "application/vnd.custom": "data"} + r = Result.from_bundle(bundle) + assert r.extra == {"application/vnd.custom": "data"} + + def test_result_formats(self): + r = Result(text="hi", png="data") + assert "text" in r.formats() + assert "png" in r.formats() + assert "html" not in r.formats() + + def test_execution_text_property(self): + e = Execution( + results=[ + Result(text="chart", is_main_result=False), + Result(text="42", is_main_result=True), + ] + ) + assert e.text == "42" + + def test_execution_error(self): + err = ExecutionError( + name="ZeroDivisionError", + value="division by zero", + traceback="Traceback ...\nZeroDivisionError: division by zero", + ) + e = Execution(error=err) + assert e.error is not None + assert "ZeroDivisionError" in e.error.name + + def test_logs(self): + logs = Logs(stdout=["hello\n", "world\n"], stderr=["warn\n"]) + assert "".join(logs.stdout) == "hello\nworld\n" + assert "".join(logs.stderr) == "warn\n" + + +class TestDeprecationWarnings: + def test_import_sandbox_from_wrenn_warns(self): + import sys + import warnings + + # Clear cached attribute + if "Sandbox" in dir(sys.modules.get("wrenn", object())): + delattr(sys.modules["wrenn"], "Sandbox") + + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter("always") + from wrenn import Sandbox + + assert Sandbox is Capsule + fw = [x for x in w if issubclass(x.category, FutureWarning)] + assert len(fw) >= 1 + assert "Sandbox" in str(fw[0].message) diff --git a/tests/test_client.py b/tests/test_client.py new file mode 100644 index 0000000..08168a6 --- /dev/null +++ b/tests/test_client.py @@ -0,0 +1,262 @@ +from __future__ import annotations + +import pytest +import respx + +from wrenn.client import AsyncWrennClient, WrennClient +from wrenn.exceptions import ( + WrennAgentError, + WrennAuthenticationError, + WrennConflictError, + WrennInternalError, + WrennNotFoundError, + WrennValidationError, +) +from wrenn.models import ( + Capsule, + Status, + Template, +) + +BASE = "https://app.wrenn.dev/api" + + +@pytest.fixture +def client(): + with WrennClient(api_key="wrn_test1234567890abcdef12345678") as c: + yield c + + +@pytest.fixture +def async_client(): + return AsyncWrennClient(api_key="wrn_test1234567890abcdef12345678") + + +class TestCapsules: + @respx.mock + def test_create(self, client): + respx.post(f"{BASE}/v1/capsules").respond( + 201, + json={ + "id": "sb-1", + "status": "pending", + "template": "base-python", + "vcpus": 2, + "memory_mb": 1024, + }, + ) + resp = client.capsules.create(template="base-python", vcpus=2, memory_mb=1024) + assert isinstance(resp, Capsule) + assert resp.id == "sb-1" + assert resp.status == Status.pending + + @respx.mock + def test_create_defaults(self, client): + respx.post(f"{BASE}/v1/capsules").respond( + 201, json={"id": "sb-2", "status": "pending"} + ) + resp = client.capsules.create() + assert resp.id == "sb-2" + + @respx.mock + def test_list(self, client): + respx.get(f"{BASE}/v1/capsules").respond( + 200, json=[{"id": "sb-1", "status": "running"}] + ) + boxes = client.capsules.list() + assert len(boxes) == 1 + assert boxes[0].status == Status.running + + @respx.mock + def test_get(self, client): + respx.get(f"{BASE}/v1/capsules/sb-1").respond( + 200, json={"id": "sb-1", "status": "running"} + ) + resp = client.capsules.get("sb-1") + assert resp.id == "sb-1" + + @respx.mock + def test_destroy(self, client): + route = respx.delete(f"{BASE}/v1/capsules/sb-1").respond(204) + client.capsules.destroy("sb-1") + assert route.called + + @respx.mock + def test_pause(self, client): + respx.post(f"{BASE}/v1/capsules/sb-1/pause").respond( + 200, json={"id": "sb-1", "status": "paused"} + ) + resp = client.capsules.pause("sb-1") + assert resp.status == Status.paused + + @respx.mock + def test_resume(self, client): + respx.post(f"{BASE}/v1/capsules/sb-1/resume").respond( + 200, json={"id": "sb-1", "status": "running"} + ) + resp = client.capsules.resume("sb-1") + assert resp.status == Status.running + + @respx.mock + def test_ping(self, client): + route = respx.post(f"{BASE}/v1/capsules/sb-1/ping").respond(204) + client.capsules.ping("sb-1") + assert route.called + + +class TestSnapshots: + @respx.mock + def test_create(self, client): + respx.post(f"{BASE}/v1/snapshots").respond( + 201, + json={"name": "snap-1", "type": "snapshot", "vcpus": 1}, + ) + resp = client.snapshots.create(capsule_id="sb-1", name="snap-1") + assert isinstance(resp, Template) + assert resp.name == "snap-1" + + @respx.mock + def test_create_with_overwrite(self, client): + route = respx.post(f"{BASE}/v1/snapshots").respond( + 201, json={"name": "snap-1", "type": "snapshot"} + ) + client.snapshots.create(capsule_id="sb-1", overwrite=True) + req = route.calls[0].request + assert "overwrite=true" in str(req.url) + + @respx.mock + def test_list(self, client): + respx.get(f"{BASE}/v1/snapshots").respond( + 200, json=[{"name": "base-python", "type": "base"}] + ) + snaps = client.snapshots.list() + assert len(snaps) == 1 + + @respx.mock + def test_list_with_filter(self, client): + route = respx.get(f"{BASE}/v1/snapshots").respond(200, json=[]) + client.snapshots.list(type="snapshot") + req = route.calls[0].request + assert "type=snapshot" in str(req.url) + + @respx.mock + def test_delete(self, client): + route = respx.delete(f"{BASE}/v1/snapshots/snap-1").respond(204) + client.snapshots.delete("snap-1") + assert route.called + + +class TestErrorHandling: + @respx.mock + def test_validation_error(self, client): + respx.post(f"{BASE}/v1/capsules").respond( + 400, + json={"error": {"code": "invalid_request", "message": "bad input"}}, + ) + with pytest.raises(WrennValidationError) as exc_info: + client.capsules.create() + assert exc_info.value.code == "invalid_request" + assert exc_info.value.status_code == 400 + + @respx.mock + def test_auth_error(self, client): + respx.get(f"{BASE}/v1/capsules").respond( + 401, + json={"error": {"code": "unauthorized", "message": "bad key"}}, + ) + with pytest.raises(WrennAuthenticationError): + client.capsules.list() + + @respx.mock + def test_not_found_error(self, client): + respx.get(f"{BASE}/v1/capsules/nope").respond( + 404, + json={"error": {"code": "not_found", "message": "capsule not found"}}, + ) + with pytest.raises(WrennNotFoundError): + client.capsules.get("nope") + + @respx.mock + def test_conflict_error(self, client): + respx.get(f"{BASE}/v1/capsules/sb-1").respond( + 409, + json={"error": {"code": "invalid_state", "message": "not running"}}, + ) + with pytest.raises(WrennConflictError): + client.capsules.get("sb-1") + + @respx.mock + def test_agent_error(self, client): + respx.post(f"{BASE}/v1/capsules").respond( + 502, + json={"error": {"code": "agent_error", "message": "host agent failed"}}, + ) + with pytest.raises(WrennAgentError): + client.capsules.create() + + @respx.mock + def test_internal_error(self, client): + respx.get(f"{BASE}/v1/capsules/sb-1").respond( + 500, + json={"error": {"code": "internal_error", "message": "oops"}}, + ) + with pytest.raises(WrennInternalError): + client.capsules.get("sb-1") + + @respx.mock + def test_unknown_error_code_falls_back(self, client): + respx.get(f"{BASE}/v1/capsules/sb-1").respond( + 418, + json={"error": {"code": "teapot", "message": "I'm a teapot"}}, + ) + from wrenn.exceptions import WrennError + + with pytest.raises(WrennError) as exc_info: + client.capsules.get("sb-1") + assert exc_info.value.code == "teapot" + + +class TestAuthModes: + def test_api_key_header(self): + with WrennClient(api_key="wrn_test1234567890abcdef12345678") as c: + assert c._http.headers["X-API-Key"] == "wrn_test1234567890abcdef12345678" + + def test_no_auth_raises(self): + with pytest.raises(ValueError, match="No API key"): + WrennClient() + + def test_env_var_fallback(self, monkeypatch): + monkeypatch.setenv("WRENN_API_KEY", "wrn_from_env") + with WrennClient() as c: + assert c._http.headers["X-API-Key"] == "wrn_from_env" + + +class TestAsyncClient: + @pytest.mark.asyncio + @respx.mock + async def test_async_capsules_create(self, async_client): + async with async_client: + respx.post(f"{BASE}/v1/capsules").respond( + 201, json={"id": "sb-1", "status": "pending"} + ) + resp = await async_client.capsules.create(template="base-python") + assert resp.id == "sb-1" + + @pytest.mark.asyncio + @respx.mock + async def test_async_capsules_list(self, async_client): + async with async_client: + respx.get(f"{BASE}/v1/capsules").respond(200, json=[{"id": "sb-1"}]) + boxes = await async_client.capsules.list() + assert len(boxes) == 1 + + @pytest.mark.asyncio + @respx.mock + async def test_async_error_handling(self, async_client): + async with async_client: + respx.get(f"{BASE}/v1/capsules/nope").respond( + 404, + json={"error": {"code": "not_found", "message": "not found"}}, + ) + with pytest.raises(WrennNotFoundError): + await async_client.capsules.get("nope") diff --git a/tests/test_filesystem_pty.py b/tests/test_filesystem_pty.py new file mode 100644 index 0000000..62ed91e --- /dev/null +++ b/tests/test_filesystem_pty.py @@ -0,0 +1,491 @@ +from __future__ import annotations + +import base64 +import json +from unittest.mock import AsyncMock, MagicMock + +import pytest +import respx + +from wrenn.capsule import Capsule +from wrenn.models import FileEntry +from wrenn.pty import ( + AsyncPtySession, + PtyEventType, + PtySession, + _parse_pty_event, +) + +BASE = "https://app.wrenn.dev/api" + + +def _make_capsule(cap_id: str = "cl-abc") -> Capsule: + respx.post(f"{BASE}/v1/capsules").respond( + 201, json={"id": cap_id, "status": "running"} + ) + return Capsule(api_key="wrn_test1234567890abcdef12345678") + + +class TestFilesRead: + @respx.mock + def test_read_returns_string(self): + cap = _make_capsule() + content = b"file contents here" + respx.post(f"{BASE}/v1/capsules/cl-abc/files/read").respond( + 200, content=content + ) + data = cap.files.read("/app/main.py") + assert data == "file contents here" + + @respx.mock + def test_read_bytes(self): + cap = _make_capsule() + content = b"\x00\x01\x02" + respx.post(f"{BASE}/v1/capsules/cl-abc/files/read").respond( + 200, content=content + ) + data = cap.files.read_bytes("/bin/binary") + assert data == b"\x00\x01\x02" + + +class TestFilesWrite: + @respx.mock + def test_write_string(self): + cap = _make_capsule() + route = respx.post(f"{BASE}/v1/capsules/cl-abc/files/write").respond(204) + cap.files.write("/app/main.py", "print('hello')") + assert route.called + + @respx.mock + def test_write_bytes(self): + cap = _make_capsule() + route = respx.post(f"{BASE}/v1/capsules/cl-abc/files/write").respond(204) + cap.files.write("/app/data.bin", b"\x00\x01\x02") + assert route.called + + +class TestFilesList: + @respx.mock + def test_list_returns_entries(self): + cap = _make_capsule() + respx.post(f"{BASE}/v1/capsules/cl-abc/files/list").respond( + 200, + json={ + "entries": [ + { + "name": "main.py", + "path": "/home/user/main.py", + "type": "file", + "size": 1024, + "mode": 33188, + "permissions": "-rw-r--r--", + "owner": "root", + "group": "root", + "modified_at": 1712899200, + "symlink_target": None, + }, + { + "name": "config", + "path": "/home/user/config", + "type": "directory", + "size": 4096, + "mode": 16877, + "permissions": "drwxr-xr-x", + "owner": "root", + "group": "root", + "modified_at": 1712899100, + "symlink_target": None, + }, + ] + }, + ) + entries = cap.files.list("/home/user") + assert len(entries) == 2 + assert isinstance(entries[0], FileEntry) + assert entries[0].name == "main.py" + assert entries[0].type == "file" + assert entries[1].name == "config" + assert entries[1].type == "directory" + + @respx.mock + def test_list_with_depth(self): + cap = _make_capsule() + route = respx.post(f"{BASE}/v1/capsules/cl-abc/files/list").respond( + 200, json={"entries": []} + ) + cap.files.list("/home/user", depth=3) + body = json.loads(route.calls[0].request.content) + assert body["depth"] == 3 + + @respx.mock + def test_list_empty(self): + cap = _make_capsule() + respx.post(f"{BASE}/v1/capsules/cl-abc/files/list").respond( + 200, json={"entries": []} + ) + entries = cap.files.list("/empty") + assert entries == [] + + +class TestFilesMakeDir: + @respx.mock + def test_make_dir_returns_entry(self): + cap = _make_capsule() + respx.post(f"{BASE}/v1/capsules/cl-abc/files/mkdir").respond( + 200, + json={ + "entry": { + "name": "data", + "path": "/home/user/data", + "type": "directory", + "size": 4096, + "mode": 16877, + "permissions": "drwxr-xr-x", + "owner": "root", + "group": "root", + "modified_at": 1712899200, + "symlink_target": None, + } + }, + ) + entry = cap.files.make_dir("/home/user/data") + assert isinstance(entry, FileEntry) + assert entry.name == "data" + assert entry.type == "directory" + + @respx.mock + def test_make_dir_existing_returns_gracefully(self): + cap = _make_capsule() + respx.post(f"{BASE}/v1/capsules/cl-abc/files/mkdir").respond( + 409, + json={"error": {"code": "conflict", "message": "already exists"}}, + ) + respx.post(f"{BASE}/v1/capsules/cl-abc/files/list").respond( + 200, + json={ + "entries": [ + { + "name": "data", + "path": "/home/user/data", + "type": "directory", + "size": 4096, + "mode": 16877, + "permissions": "drwxr-xr-x", + "owner": "root", + "group": "root", + "modified_at": 1712899200, + "symlink_target": None, + } + ] + }, + ) + entry = cap.files.make_dir("/home/user/data") + assert entry.name == "data" + + +class TestFilesRemove: + @respx.mock + def test_remove_succeeds(self): + cap = _make_capsule() + route = respx.post(f"{BASE}/v1/capsules/cl-abc/files/remove").respond(204) + cap.files.remove("/home/user/old_data") + assert route.called + + @respx.mock + def test_remove_sends_path(self): + cap = _make_capsule() + route = respx.post(f"{BASE}/v1/capsules/cl-abc/files/remove").respond(204) + cap.files.remove("/tmp/test.txt") + body = json.loads(route.calls[0].request.content) + assert body["path"] == "/tmp/test.txt" + + +class TestFilesExists: + @respx.mock + def test_exists_true(self): + cap = _make_capsule() + respx.post(f"{BASE}/v1/capsules/cl-abc/files/list").respond( + 200, + json={ + "entries": [ + {"name": "hello.txt", "path": "/tmp/hello.txt", "type": "file"} + ] + }, + ) + assert cap.files.exists("/tmp/hello.txt") is True + + @respx.mock + def test_exists_false(self): + cap = _make_capsule() + respx.post(f"{BASE}/v1/capsules/cl-abc/files/list").respond( + 200, json={"entries": []} + ) + assert cap.files.exists("/tmp/nope.txt") is False + + +class TestPtyEventParsing: + def test_started_event(self): + raw = {"type": "started", "tag": "pty-a1b2c3d4", "pid": 42} + event = _parse_pty_event(raw) + assert event.type == PtyEventType.started + assert event.pid == 42 + assert event.tag == "pty-a1b2c3d4" + + def test_output_event_base64(self): + encoded = base64.b64encode(b"ls -la\n").decode() + raw = {"type": "output", "data": encoded} + event = _parse_pty_event(raw) + assert event.type == PtyEventType.output + assert event.data == b"ls -la\n" + + def test_output_event_empty(self): + raw = {"type": "output", "data": ""} + event = _parse_pty_event(raw) + assert event.data == b"" + + def test_exit_event(self): + raw = {"type": "exit", "exit_code": 0} + event = _parse_pty_event(raw) + assert event.type == PtyEventType.exit + assert event.exit_code == 0 + + def test_error_event(self): + raw = {"type": "error", "data": "process not found", "fatal": True} + event = _parse_pty_event(raw) + assert event.type == PtyEventType.error + assert event.data == "process not found" + assert event.fatal is True + + def test_ping_event(self): + raw = {"type": "ping"} + event = _parse_pty_event(raw) + assert event.type == PtyEventType.ping + + +class TestPtySessionWrite: + def test_write_sends_base64_input(self): + ws = MagicMock() + session = PtySession(ws, "cl-abc") + session.write(b"ls -la\n") + sent = json.loads(ws.send_text.call_args[0][0]) + assert sent["type"] == "input" + assert base64.b64decode(sent["data"]) == b"ls -la\n" + + +class TestPtySessionResize: + def test_resize_sends_dimensions(self): + ws = MagicMock() + session = PtySession(ws, "cl-abc") + session.resize(120, 40) + sent = json.loads(ws.send_text.call_args[0][0]) + assert sent["type"] == "resize" + assert sent["cols"] == 120 + assert sent["rows"] == 40 + + def test_resize_zero_raises(self): + ws = MagicMock() + session = PtySession(ws, "cl-abc") + with pytest.raises(ValueError, match="greater than 0"): + session.resize(0, 40) + with pytest.raises(ValueError, match="greater than 0"): + session.resize(80, 0) + + +class TestPtySessionKill: + def test_kill_sends_message(self): + ws = MagicMock() + session = PtySession(ws, "cl-abc") + session.kill() + sent = json.loads(ws.send_text.call_args[0][0]) + assert sent["type"] == "kill" + + +class TestPtySessionIteration: + def test_iter_yields_events_until_exit(self): + ws = MagicMock() + messages = [ + json.dumps({"type": "started", "tag": "pty-abc12345", "pid": 1}), + json.dumps({"type": "output", "data": base64.b64encode(b"hello").decode()}), + json.dumps({"type": "exit", "exit_code": 0}), + ] + ws.receive_text.side_effect = messages + session = PtySession(ws, "cl-abc") + events = list(session) + assert len(events) == 2 + assert events[0].type == PtyEventType.started + assert session.tag == "pty-abc12345" + assert session.pid == 1 + assert events[1].type == PtyEventType.output + assert events[1].data == b"hello" + + def test_iter_stops_on_fatal_error(self): + ws = MagicMock() + messages = [ + json.dumps({"type": "error", "data": "fatal", "fatal": True}), + ] + ws.receive_text.side_effect = messages + session = PtySession(ws, "cl-abc") + events = list(session) + assert len(events) == 1 + assert events[0].type == PtyEventType.error + + def test_iter_stops_on_disconnect(self): + import httpx_ws + + ws = MagicMock() + ws.receive_text.side_effect = httpx_ws.WebSocketDisconnect() + session = PtySession(ws, "cl-abc") + events = list(session) + assert events == [] + + +class TestPtySessionContextManager: + def test_exit_kills_and_closes(self): + ws = MagicMock() + session = PtySession(ws, "cl-abc") + with session: + pass + ws.send_text.assert_called() + ws.close.assert_called() + + def test_exit_ignores_errors(self): + ws = MagicMock() + ws.send_text.side_effect = Exception("already closed") + session = PtySession(ws, "cl-abc") + with session: + pass + + +class TestPtySessionSendStart: + def test_send_start_with_defaults(self): + ws = MagicMock() + session = PtySession(ws, "cl-abc") + session._send_start() + sent = json.loads(ws.send_text.call_args[0][0]) + assert sent["type"] == "start" + assert sent["cmd"] == "/bin/bash" + assert sent["cols"] == 80 + assert sent["rows"] == 24 + + def test_send_start_with_all_params(self): + ws = MagicMock() + session = PtySession(ws, "cl-abc") + session._send_start( + cmd="/bin/zsh", + args=["-l"], + cols=120, + rows=40, + envs={"TERM": "xterm-256color"}, + cwd="/home/user", + ) + sent = json.loads(ws.send_text.call_args[0][0]) + assert sent["cmd"] == "/bin/zsh" + assert sent["args"] == ["-l"] + assert sent["cols"] == 120 + + +class TestPtySessionSendConnect: + def test_send_connect(self): + ws = MagicMock() + session = PtySession(ws, "cl-abc") + session._send_connect("pty-abc12345") + sent = json.loads(ws.send_text.call_args[0][0]) + assert sent["type"] == "connect" + assert sent["tag"] == "pty-abc12345" + + +class TestAsyncPtySession: + @pytest.mark.asyncio + async def test_async_write_sends_base64(self): + ws = AsyncMock() + session = AsyncPtySession(ws, "cl-abc") + await session.write(b"hello") + sent = json.loads(ws.send_text.call_args[0][0]) + assert sent["type"] == "input" + assert base64.b64decode(sent["data"]) == b"hello" + + @pytest.mark.asyncio + async def test_async_resize(self): + ws = AsyncMock() + session = AsyncPtySession(ws, "cl-abc") + await session.resize(100, 30) + sent = json.loads(ws.send_text.call_args[0][0]) + assert sent["type"] == "resize" + assert sent["cols"] == 100 + assert sent["rows"] == 30 + + @pytest.mark.asyncio + async def test_async_resize_zero_raises(self): + ws = AsyncMock() + session = AsyncPtySession(ws, "cl-abc") + with pytest.raises(ValueError): + await session.resize(0, 10) + + @pytest.mark.asyncio + async def test_async_kill(self): + ws = AsyncMock() + session = AsyncPtySession(ws, "cl-abc") + await session.kill() + sent = json.loads(ws.send_text.call_args[0][0]) + assert sent["type"] == "kill" + + @pytest.mark.asyncio + async def test_async_context_manager(self): + ws = AsyncMock() + session = AsyncPtySession(ws, "cl-abc") + async with session: + pass + ws.send_text.assert_called() + ws.close.assert_called() + + @pytest.mark.asyncio + async def test_async_send_start(self): + ws = AsyncMock() + session = AsyncPtySession(ws, "cl-abc") + await session._send_start(cmd="/bin/zsh", cols=100, rows=30) + sent = json.loads(ws.send_text.call_args[0][0]) + assert sent["type"] == "start" + assert sent["cmd"] == "/bin/zsh" + assert sent["cols"] == 100 + + @pytest.mark.asyncio + async def test_async_iteration(self): + ws = AsyncMock() + messages = [ + json.dumps({"type": "started", "tag": "pty-xyz", "pid": 5}), + json.dumps({"type": "output", "data": base64.b64encode(b"hi").decode()}), + json.dumps({"type": "exit", "exit_code": 0}), + ] + ws.receive_text.side_effect = messages + session = AsyncPtySession(ws, "cl-abc") + events = [] + async for event in session: + events.append(event) + assert len(events) == 2 + assert events[0].type == PtyEventType.started + assert session.tag == "pty-xyz" + assert session.pid == 5 + + +class TestExports: + def test_file_entry_importable(self): + from wrenn import FileEntry as FE + + assert FE is not None + + def test_pty_session_importable(self): + from wrenn import PtySession as PS + + assert PS is not None + + def test_async_pty_session_importable(self): + from wrenn import AsyncPtySession as APS + + assert APS is not None + + def test_pty_event_importable(self): + from wrenn import PtyEvent as PE + from wrenn import PtyEventType as PET + + assert PE is not None + assert PET is not None diff --git a/tests/test_git.py b/tests/test_git.py new file mode 100644 index 0000000..e231834 --- /dev/null +++ b/tests/test_git.py @@ -0,0 +1,1137 @@ +from __future__ import annotations + +import json + +import pytest +import respx + +from wrenn._git import ( + AsyncGit, + FileStatus, + Git, + GitAuthError, + GitCommandError, + GitError, + GitStatus, + _check_result, + _derive_repo_dir, +) +from wrenn._git._auth import ( + build_credential_approve_cmd, + embed_credentials, + is_auth_error, + strip_credentials, +) +from wrenn._git._cmd import ( + build_add, + build_branches, + build_checkout, + build_clone, + build_commit, + build_config_get, + build_config_set, + build_create_branch, + build_delete_branch, + build_init, + build_pull, + build_push, + build_remote_add, + build_remote_get_url, + build_remote_set_url, + build_reset, + build_restore, + build_status, + parse_branches, + parse_status, +) +from wrenn.commands import CommandResult + +BASE = "https://app.wrenn.dev/api" +CAPSULE_ID = "cl-test123" +EXEC_URL = f"{BASE}/v1/capsules/{CAPSULE_ID}/exec" + + +# ── Helpers ──────────────────────────────────────────────────────── + + +def _exec_response( + stdout: str = "", + stderr: str = "", + exit_code: int = 0, + duration_ms: int = 10, +) -> dict: + """Build a mock exec API response body.""" + return { + "stdout": stdout, + "stderr": stderr, + "exit_code": exit_code, + "duration_ms": duration_ms, + } + + +def _make_git(respx_mock=None) -> Git: + """Create a Git instance bound to a test capsule.""" + from wrenn.client import WrennClient + + client = WrennClient(api_key="wrn_test1234567890abcdef12345678") + return Git(CAPSULE_ID, client.http) + + +def _make_async_git() -> AsyncGit: + """Create an AsyncGit instance bound to a test capsule.""" + from wrenn.client import AsyncWrennClient + + client = AsyncWrennClient(api_key="wrn_test1234567890abcdef12345678") + return AsyncGit(CAPSULE_ID, client.http) + + +# ══════════════════════════════════════════════════════════════════ +# Pure function tests — no I/O, no mocking +# ══════════════════════════════════════════════════════════════════ + + +class TestBuildClone: + def test_basic(self): + args = build_clone("https://github.com/user/repo.git") + assert args == ["git", "clone", "https://github.com/user/repo.git"] + + def test_with_dest(self): + args = build_clone("https://github.com/user/repo.git", "/tmp/repo") + assert args[-1] == "/tmp/repo" + + def test_with_branch(self): + args = build_clone("https://github.com/user/repo.git", branch="main") + assert "--branch" in args + assert "main" in args + assert "--single-branch" in args + + def test_with_depth(self): + args = build_clone("https://github.com/user/repo.git", depth=1) + assert "--depth" in args + assert "1" in args + + def test_all_options(self): + args = build_clone( + "https://github.com/user/repo.git", + "/tmp/repo", + branch="dev", + depth=5, + ) + assert args == [ + "git", + "clone", + "--branch", + "dev", + "--single-branch", + "--depth", + "5", + "https://github.com/user/repo.git", + "/tmp/repo", + ] + + +class TestBuildInit: + def test_basic(self): + assert build_init("/repo") == ["git", "init", "/repo"] + + def test_bare(self): + args = build_init("/repo", bare=True) + assert "--bare" in args + + def test_initial_branch(self): + args = build_init("/repo", initial_branch="main") + assert "--initial-branch" in args + assert "main" in args + + +class TestBuildAdd: + def test_default(self): + assert build_add() == ["git", "add", "."] + + def test_all(self): + assert build_add(all=True) == ["git", "add", "-A"] + + def test_specific_files(self): + args = build_add(["file1.py", "file2.py"]) + assert args == ["git", "add", "--", "file1.py", "file2.py"] + + +class TestBuildCommit: + def test_basic(self): + args = build_commit("initial commit") + assert args == ["git", "commit", "-m", "initial commit"] + + def test_allow_empty(self): + args = build_commit("empty", allow_empty=True) + assert "--allow-empty" in args + + def test_author_override(self): + args = build_commit("msg", author_name="Bob", author_email="bob@test.com") + assert "-c" in args + assert "user.name=Bob" in args + assert "user.email=bob@test.com" in args + + +class TestBuildPush: + def test_basic(self): + assert build_push() == ["git", "push", "origin"] + + def test_with_branch(self): + args = build_push("origin", "main") + assert args == ["git", "push", "origin", "main"] + + def test_force(self): + args = build_push(force=True) + assert "--force" in args + + def test_set_upstream(self): + args = build_push(set_upstream=True) + assert "--set-upstream" in args + + +class TestBuildPull: + def test_basic(self): + assert build_pull() == ["git", "pull", "origin"] + + def test_rebase(self): + args = build_pull(rebase=True) + assert "--rebase" in args + + def test_ff_only(self): + args = build_pull(ff_only=True) + assert "--ff-only" in args + + def test_with_branch(self): + args = build_pull("upstream", "feature") + assert args == ["git", "pull", "upstream", "feature"] + + +class TestBuildStatus: + def test_args(self): + assert build_status() == ["git", "status", "--porcelain=v1", "--branch"] + + +class TestBuildBranches: + def test_args(self): + assert build_branches() == [ + "git", + "branch", + "--format=%(refname:short)\t%(HEAD)", + ] + + +class TestBuildBranchOps: + def test_create(self): + assert build_create_branch("feat") == ["git", "checkout", "-b", "feat"] + + def test_create_with_start_point(self): + args = build_create_branch("feat", start_point="abc123") + assert args == ["git", "checkout", "-b", "feat", "abc123"] + + def test_checkout(self): + assert build_checkout("main") == ["git", "checkout", "main"] + + def test_delete(self): + assert build_delete_branch("old") == ["git", "branch", "-d", "old"] + + def test_force_delete(self): + assert build_delete_branch("old", force=True) == ["git", "branch", "-D", "old"] + + +class TestBuildRemote: + def test_add(self): + args = build_remote_add("origin", "https://example.com/repo.git") + assert args == [ + "git", + "remote", + "add", + "origin", + "https://example.com/repo.git", + ] + + def test_add_with_fetch(self): + args = build_remote_add("origin", "https://example.com/repo.git", fetch=True) + assert "-f" in args + + def test_get_url(self): + assert build_remote_get_url("origin") == ["git", "remote", "get-url", "origin"] + + def test_set_url(self): + args = build_remote_set_url("origin", "https://new.url/repo.git") + assert args == [ + "git", + "remote", + "set-url", + "origin", + "https://new.url/repo.git", + ] + + +class TestBuildReset: + def test_basic(self): + assert build_reset() == ["git", "reset"] + + def test_hard(self): + args = build_reset(mode="hard") + assert args == ["git", "reset", "--hard"] + + def test_with_ref(self): + args = build_reset(mode="soft", ref="HEAD~1") + assert args == ["git", "reset", "--soft", "HEAD~1"] + + def test_with_paths(self): + args = build_reset(paths=["file.py"]) + assert args == ["git", "reset", "--", "file.py"] + + def test_invalid_mode(self): + with pytest.raises(ValueError, match="Reset mode"): + build_reset(mode="invalid") + + +class TestBuildRestore: + def test_basic(self): + args = build_restore(["file.py"]) + assert args == ["git", "restore", "--worktree", "--", "file.py"] + + def test_staged(self): + args = build_restore(["file.py"], staged=True) + assert "--staged" in args + + def test_both(self): + args = build_restore(["file.py"], staged=True, worktree=True) + assert "--staged" in args + assert "--worktree" in args + + def test_with_source(self): + args = build_restore(["file.py"], source="HEAD~1") + assert "--source" in args + assert "HEAD~1" in args + + def test_empty_paths_raises(self): + with pytest.raises(ValueError, match="At least one path"): + build_restore([]) + + +class TestBuildConfig: + def test_set_local(self): + args = build_config_set("user.name", "Bob", scope="local", repo_path="/repo") + assert args == ["git", "-C", "/repo", "config", "--local", "user.name", "Bob"] + + def test_set_global(self): + args = build_config_set("user.name", "Bob", scope="global") + assert args == ["git", "config", "--global", "user.name", "Bob"] + + def test_get_global(self): + args = build_config_get("user.name", scope="global") + assert args == ["git", "config", "--global", "--get", "user.name"] + + def test_invalid_scope(self): + with pytest.raises(ValueError, match="scope"): + build_config_set("key", "val", scope="invalid") + + +# ── Parser tests ─────────────────────────────────────────────────── + + +class TestParseStatus: + def test_empty(self): + status = parse_status("") + assert status.branch is None + assert status.is_clean is True + assert status.files == [] + + def test_clean_repo(self): + status = parse_status("## main...origin/main\n") + assert status.branch == "main" + assert status.upstream == "origin/main" + assert status.is_clean is True + + def test_modified_file(self): + status = parse_status("## main\n M file.py\n") + assert len(status.files) == 1 + f = status.files[0] + assert f.path == "file.py" + assert f.work_tree_status == "M" + assert f.status == "modified" + assert f.staged is False + + def test_staged_file(self): + status = parse_status("## main\nM file.py\n") + f = status.files[0] + assert f.index_status == "M" + assert f.staged is True + + def test_untracked(self): + status = parse_status("## main\n?? new.txt\n") + f = status.files[0] + assert f.status == "untracked" + assert f.staged is False + + def test_renamed(self): + status = parse_status("## main\nR old.py -> new.py\n") + f = status.files[0] + assert f.status == "renamed" + assert f.path == "new.py" + assert f.renamed_from == "old.py" + + def test_ahead_behind(self): + status = parse_status("## main...origin/main [ahead 3, behind 1]\n") + assert status.ahead == 3 + assert status.behind == 1 + + def test_ahead_only(self): + status = parse_status("## main...origin/main [ahead 2]\n") + assert status.ahead == 2 + assert status.behind == 0 + + def test_detached_head(self): + status = parse_status("## HEAD (detached at abc1234)\n") + assert status.detached is True + assert status.branch == "abc1234" + + def test_no_commits_yet(self): + status = parse_status("## No commits yet on main\n") + assert status.branch == "main" + + def test_multiple_files(self): + output = "## dev\nM a.py\n M b.py\n?? c.txt\nA d.py\nD e.py\n" + status = parse_status(output) + assert len(status.files) == 5 + assert status.has_staged is True + assert status.has_untracked is True + + def test_has_conflicts(self): + status = parse_status("## main\nUU conflict.py\n") + assert status.has_conflicts is True + assert status.files[0].status == "conflict" + + +class TestParseBranches: + def test_single_branch(self): + branches = parse_branches("main\t*\n") + assert len(branches) == 1 + assert branches[0].name == "main" + assert branches[0].is_current is True + + def test_multiple(self): + branches = parse_branches("main\t*\ndev\t \nfeature\t \n") + assert len(branches) == 3 + current = [b for b in branches if b.is_current] + assert len(current) == 1 + assert current[0].name == "main" + + def test_empty(self): + branches = parse_branches("") + assert branches == [] + + def test_no_current(self): + branches = parse_branches("main\t \ndev\t \n") + assert all(not b.is_current for b in branches) + + +# ── Auth helper tests ────────────────────────────────────────────── + + +class TestEmbedCredentials: + def test_basic(self): + url = embed_credentials("https://github.com/user/repo.git", "user", "token") + assert url == "https://user:token@github.com/user/repo.git" + + def test_with_port(self): + url = embed_credentials("https://git.example.com:8443/repo.git", "u", "p") + assert "u:p@git.example.com:8443" in url + + def test_ssh_raises(self): + with pytest.raises(ValueError, match="http"): + embed_credentials("git@github.com:user/repo.git", "u", "p") + + +class TestStripCredentials: + def test_basic(self): + url = strip_credentials("https://user:token@github.com/user/repo.git") + assert url == "https://github.com/user/repo.git" + + def test_no_credentials(self): + url = "https://github.com/user/repo.git" + assert strip_credentials(url) == url + + def test_ssh_unchanged(self): + url = "git@github.com:user/repo.git" + assert strip_credentials(url) == url + + +class TestIsAuthError: + @pytest.mark.parametrize( + "msg", + [ + "fatal: Authentication failed for 'https://...'", + "fatal: could not read Username", + "remote: Invalid username or password", + "fatal: terminal prompts disabled", + "Permission denied (publickey)", + ], + ) + def test_auth_patterns(self, msg): + assert is_auth_error(msg) is True + + @pytest.mark.parametrize( + "msg", + [ + "fatal: repository 'https://...' not found", + "error: pathspec 'foo' did not match any file(s)", + "", + ], + ) + def test_non_auth_patterns(self, msg): + assert is_auth_error(msg) is False + + +class TestBuildCredentialApproveCmd: + def test_basic(self): + cmd = build_credential_approve_cmd("user", "token123", "github.com", "https") + assert "git credential approve" in cmd + assert "protocol=https" in cmd + assert "host=github.com" in cmd + assert "username=user" in cmd + assert "password=token123" in cmd + + def test_newline_rejected(self): + with pytest.raises(ValueError, match="newline"): + build_credential_approve_cmd("user", "tok\nen", "github.com", "https") + + +# ── _check_result tests ─────────────────────────────────────────── + + +class TestCheckResult: + def test_success(self): + result = CommandResult(stdout="ok\n", stderr="", exit_code=0) + _check_result(result, op="test") # should not raise + + def test_generic_failure(self): + result = CommandResult(stdout="", stderr="fatal: bad thing", exit_code=1) + with pytest.raises(GitCommandError) as exc_info: + _check_result(result, op="push") + assert exc_info.value.exit_code == 1 + assert "fatal: bad thing" in exc_info.value.message + + def test_auth_failure(self): + result = CommandResult( + stdout="", + stderr="fatal: Authentication failed for 'https://...'", + exit_code=128, + ) + with pytest.raises(GitAuthError) as exc_info: + _check_result(result, op="clone") + assert "authentication failed" in exc_info.value.message + assert exc_info.value.exit_code == 128 + + def test_fallback_message(self): + result = CommandResult(stdout="", stderr="", exit_code=42) + with pytest.raises(GitCommandError, match="git test failed"): + _check_result(result, op="test") + + +# ── _derive_repo_dir tests ──────────────────────────────────────── + + +class TestDeriveRepoDir: + def test_basic(self): + assert _derive_repo_dir("https://github.com/user/repo.git") == "repo" + + def test_no_git_suffix(self): + assert _derive_repo_dir("https://github.com/user/repo") == "repo" + + def test_trailing_slash(self): + assert _derive_repo_dir("https://github.com/user/repo.git/") == "repo" + + def test_ssh_returns_none(self): + assert _derive_repo_dir("git@github.com:user/repo.git") is None + + def test_empty_path(self): + assert _derive_repo_dir("https://github.com") is None + + +# ── FileStatus property tests ───────────────────────────────────── + + +class TestFileStatus: + def test_staged_property(self): + f = FileStatus(path="a.py", index_status="M", work_tree_status=" ") + assert f.staged is True + + def test_not_staged(self): + f = FileStatus(path="a.py", index_status=" ", work_tree_status="M") + assert f.staged is False + + def test_untracked_not_staged(self): + f = FileStatus(path="a.py", index_status="?", work_tree_status="?") + assert f.staged is False + + def test_status_property(self): + cases = [ + (("U", " "), "conflict"), + (("R", " "), "renamed"), + (("C", " "), "copied"), + (("D", " "), "deleted"), + (("A", " "), "added"), + (("M", " "), "modified"), + (("T", " "), "typechange"), + (("?", "?"), "untracked"), + ((" ", " "), "unknown"), + ] + for (idx, wt), expected in cases: + f = FileStatus(path="x", index_status=idx, work_tree_status=wt) + assert f.status == expected, f"Expected {expected} for ({idx!r}, {wt!r})" + + +# ── GitStatus property tests ────────────────────────────────────── + + +class TestGitStatus: + def test_is_clean(self): + s = GitStatus() + assert s.is_clean is True + + def test_has_staged(self): + s = GitStatus( + files=[ + FileStatus(path="a.py", index_status="M", work_tree_status=" "), + ] + ) + assert s.has_staged is True + + def test_has_untracked(self): + s = GitStatus( + files=[ + FileStatus(path="a.py", index_status="?", work_tree_status="?"), + ] + ) + assert s.has_untracked is True + + def test_has_conflicts(self): + s = GitStatus( + files=[ + FileStatus(path="a.py", index_status="U", work_tree_status="U"), + ] + ) + assert s.has_conflicts is True + + +# ══════════════════════════════════════════════════════════════════ +# Integration tests — Git class with mocked HTTP +# ══════════════════════════════════════════════════════════════════ + + +class TestGitInit: + @respx.mock + def test_init(self): + respx.post(EXEC_URL).respond( + 200, + json=_exec_response( + stdout="Initialized empty Git repository in /repo/.git/\n" + ), + ) + git = _make_git() + result = git.init("/repo") + assert result.exit_code == 0 + + @respx.mock + def test_init_failure(self): + respx.post(EXEC_URL).respond( + 200, + json=_exec_response(stderr="fatal: cannot mkdir /readonly", exit_code=128), + ) + git = _make_git() + with pytest.raises(GitCommandError): + git.init("/readonly") + + +class TestGitClone: + @respx.mock + def test_clone_basic(self): + route = respx.post(EXEC_URL).respond( + 200, json=_exec_response(stderr="Cloning into 'repo'...\n") + ) + git = _make_git() + result = git.clone("https://github.com/user/repo.git") + assert result.exit_code == 0 + req_body = route.calls[0].request.content.decode() + assert "git clone" in req_body + + @respx.mock + def test_clone_auth_failure(self): + respx.post(EXEC_URL).respond( + 200, + json=_exec_response( + stderr="fatal: Authentication failed for 'https://...'", + exit_code=128, + ), + ) + git = _make_git() + with pytest.raises(GitAuthError): + git.clone("https://github.com/private/repo.git") + + def test_clone_password_without_username(self): + git = _make_git() + with pytest.raises(ValueError, match="Username is required"): + git.clone("https://github.com/user/repo.git", password="token") + + @respx.mock + def test_clone_with_credentials_strips(self): + # First call: clone. Second call: set-url to strip creds. + respx.post(EXEC_URL).respond(200, json=_exec_response()) + git = _make_git() + git.clone( + "https://github.com/user/repo.git", + dest="/tmp/repo", + username="user", + password="token", + ) + # Should have made 2 calls: clone + set-url + assert len(respx.calls) == 2 + + +class TestGitAdd: + @respx.mock + def test_add_all(self): + respx.post(EXEC_URL).respond(200, json=_exec_response()) + git = _make_git() + result = git.add(all=True, cwd="/repo") + assert result.exit_code == 0 + + +class TestGitCommit: + @respx.mock + def test_commit(self): + respx.post(EXEC_URL).respond( + 200, json=_exec_response(stdout="[main abc1234] initial commit\n") + ) + git = _make_git() + result = git.commit("initial commit", cwd="/repo") + assert result.exit_code == 0 + + @respx.mock + def test_commit_nothing_to_commit(self): + respx.post(EXEC_URL).respond( + 200, + json=_exec_response( + stdout="nothing to commit, working tree clean\n", + stderr="", + exit_code=1, + ), + ) + git = _make_git() + with pytest.raises(GitCommandError): + git.commit("empty", cwd="/repo") + + +class TestGitPushPull: + @respx.mock + def test_push(self): + respx.post(EXEC_URL).respond(200, json=_exec_response()) + git = _make_git() + result = git.push(cwd="/repo") + assert result.exit_code == 0 + + @respx.mock + def test_pull(self): + respx.post(EXEC_URL).respond(200, json=_exec_response()) + git = _make_git() + result = git.pull(cwd="/repo") + assert result.exit_code == 0 + + +class TestGitStatusCommand: + @respx.mock + def test_status(self): + respx.post(EXEC_URL).respond( + 200, + json=_exec_response( + stdout="## main...origin/main [ahead 1]\n M file.py\n?? new.txt\n" + ), + ) + git = _make_git() + status = git.status(cwd="/repo") + assert isinstance(status, GitStatus) + assert status.branch == "main" + assert status.ahead == 1 + assert len(status.files) == 2 + + +class TestGitBranches: + @respx.mock + def test_branches(self): + respx.post(EXEC_URL).respond( + 200, json=_exec_response(stdout="main\t*\ndev\t \n") + ) + git = _make_git() + branches = git.branches(cwd="/repo") + assert len(branches) == 2 + assert branches[0].name == "main" + assert branches[0].is_current is True + + @respx.mock + def test_create_branch(self): + respx.post(EXEC_URL).respond( + 200, json=_exec_response(stderr="Switched to a new branch 'feat'\n") + ) + git = _make_git() + result = git.create_branch("feat", cwd="/repo") + assert result.exit_code == 0 + + @respx.mock + def test_checkout_branch(self): + respx.post(EXEC_URL).respond( + 200, json=_exec_response(stderr="Switched to branch 'main'\n") + ) + git = _make_git() + result = git.checkout_branch("main", cwd="/repo") + assert result.exit_code == 0 + + @respx.mock + def test_delete_branch(self): + respx.post(EXEC_URL).respond( + 200, json=_exec_response(stdout="Deleted branch old (was abc1234).\n") + ) + git = _make_git() + result = git.delete_branch("old", cwd="/repo") + assert result.exit_code == 0 + + +class TestGitRemote: + @respx.mock + def test_remote_add(self): + respx.post(EXEC_URL).respond(200, json=_exec_response()) + git = _make_git() + result = git.remote_add("origin", "https://example.com/repo.git", cwd="/repo") + assert result.exit_code == 0 + + @respx.mock + def test_remote_get(self): + respx.post(EXEC_URL).respond( + 200, json=_exec_response(stdout="https://example.com/repo.git\n") + ) + git = _make_git() + url = git.remote_get("origin", cwd="/repo") + assert url == "https://example.com/repo.git" + + @respx.mock + def test_remote_get_not_found(self): + respx.post(EXEC_URL).respond( + 200, json=_exec_response(stderr="fatal: No such remote 'nope'", exit_code=2) + ) + git = _make_git() + url = git.remote_get("nope", cwd="/repo") + assert url is None + + +class TestGitResetRestore: + @respx.mock + def test_reset(self): + respx.post(EXEC_URL).respond(200, json=_exec_response()) + git = _make_git() + result = git.reset(mode="hard", ref="HEAD~1", cwd="/repo") + assert result.exit_code == 0 + + @respx.mock + def test_restore(self): + respx.post(EXEC_URL).respond(200, json=_exec_response()) + git = _make_git() + result = git.restore(["file.py"], staged=True, cwd="/repo") + assert result.exit_code == 0 + + +class TestGitConfig: + @respx.mock + def test_set_config(self): + respx.post(EXEC_URL).respond(200, json=_exec_response()) + git = _make_git() + result = git.set_config("user.name", "Bob", scope="global") + assert result.exit_code == 0 + + @respx.mock + def test_get_config(self): + respx.post(EXEC_URL).respond(200, json=_exec_response(stdout="Bob\n")) + git = _make_git() + val = git.get_config("user.name", scope="global") + assert val == "Bob" + + @respx.mock + def test_get_config_not_set(self): + respx.post(EXEC_URL).respond(200, json=_exec_response(stderr="", exit_code=1)) + git = _make_git() + val = git.get_config("nonexistent.key", scope="global") + assert val is None + + @respx.mock + def test_configure_user(self): + respx.post(EXEC_URL).respond(200, json=_exec_response()) + git = _make_git() + git.configure_user("Bob", "bob@test.com", scope="global") + assert len(respx.calls) == 2 # user.name + user.email + + def test_configure_user_empty_name(self): + git = _make_git() + with pytest.raises(ValueError, match="Both name and email"): + git.configure_user("", "bob@test.com") + + +class TestDangerouslyAuthenticate: + @respx.mock + def test_authenticate(self): + respx.post(EXEC_URL).respond(200, json=_exec_response()) + git = _make_git() + git.dangerously_authenticate("user", "token123") + # Should make 2 calls: config set + credential approve + assert len(respx.calls) == 2 + + def test_empty_credentials(self): + git = _make_git() + with pytest.raises(ValueError, match="Both username and password"): + git.dangerously_authenticate("", "token") + + +# ── Exception hierarchy tests ───────────────────────────────────── + + +class TestExceptionHierarchy: + def test_git_command_error_is_git_error(self): + assert issubclass(GitCommandError, GitError) + + def test_git_auth_error_is_git_error(self): + assert issubclass(GitAuthError, GitError) + + def test_git_error_is_not_wrenn_error(self): + from wrenn.exceptions import WrennError + + assert not issubclass(GitError, WrennError) + + def test_error_attributes(self): + err = GitCommandError("msg", stderr="err output", exit_code=42) + assert err.message == "msg" + assert err.stderr == "err output" + assert err.exit_code == 42 + assert str(err) == "msg" + + +# ── Capsule wiring tests ────────────────────────────────────────── + + +class TestCapsuleWiring: + @respx.mock + def test_capsule_has_git(self): + from wrenn.capsule import Capsule + + respx.post(f"{BASE}/v1/capsules").respond( + 201, json={"id": "cl-1", "status": "pending"} + ) + cap = Capsule(api_key="wrn_test1234567890abcdef12345678") + assert hasattr(cap, "git") + assert isinstance(cap.git, Git) + + +# ── Async tests ─────────────────────────────────────────────────── + + +class TestAsyncGit: + @pytest.mark.asyncio + @respx.mock + async def test_async_init(self): + respx.post(EXEC_URL).respond( + 200, json=_exec_response(stdout="Initialized empty Git repository\n") + ) + git = _make_async_git() + result = await git.init("/repo") + assert result.exit_code == 0 + + @pytest.mark.asyncio + @respx.mock + async def test_async_status(self): + respx.post(EXEC_URL).respond( + 200, json=_exec_response(stdout="## main\n M file.py\n") + ) + git = _make_async_git() + status = await git.status(cwd="/repo") + assert isinstance(status, GitStatus) + assert status.branch == "main" + + @pytest.mark.asyncio + @respx.mock + async def test_async_clone_auth_error(self): + respx.post(EXEC_URL).respond( + 200, + json=_exec_response(stderr="fatal: Authentication failed", exit_code=128), + ) + git = _make_async_git() + with pytest.raises(GitAuthError): + await git.clone("https://github.com/private/repo.git") + + @pytest.mark.asyncio + @respx.mock + async def test_async_commit(self): + respx.post(EXEC_URL).respond( + 200, json=_exec_response(stdout="[main abc1234] test\n") + ) + git = _make_async_git() + result = await git.commit("test", cwd="/repo") + assert result.exit_code == 0 + + @pytest.mark.asyncio + @respx.mock + async def test_async_branches(self): + respx.post(EXEC_URL).respond( + 200, json=_exec_response(stdout="main\t*\ndev\t \n") + ) + git = _make_async_git() + branches = await git.branches(cwd="/repo") + assert len(branches) == 2 + + +# ════════════════════════════════��═════════════════════════════════ +# Command payload tests — verify /bin/sh -c wrapping +# ════════════════════════════���══════════════════════���══════════════ + + +class TestCommandPayloadWrapping: + """Verify that Commands.run sends cmd=/bin/sh args=['-c', cmd_string] + so the server-side wrapper expands "${@}" into proper argv.""" + + @respx.mock + def test_simple_command(self): + route = respx.post(EXEC_URL).respond( + 200, json=_exec_response(stdout="hello world\n") + ) + git = _make_git() + git.init("/repo") + body = json.loads(route.calls[0].request.content) + assert body["cmd"] == "/bin/sh" + assert body["args"] == ["-c", git_cmd_from_body(body)] + # args[1] should contain the actual git command + assert body["args"][0] == "-c" + assert "git" in body["args"][1] + + @respx.mock + def test_command_with_pipes(self): + """Pipes and redirects work because /bin/sh interprets them.""" + from wrenn.client import WrennClient + from wrenn.commands import Commands + + client = WrennClient(api_key="wrn_test1234567890abcdef12345678") + commands = Commands(CAPSULE_ID, client.http) + + route = respx.post(EXEC_URL).respond(200, json=_exec_response(stdout="3\n")) + commands.run("cat /etc/passwd | wc -l") + body = json.loads(route.calls[0].request.content) + assert body["cmd"] == "/bin/sh" + assert body["args"] == ["-c", "cat /etc/passwd | wc -l"] + + @respx.mock + def test_command_with_semicolons(self): + from wrenn.client import WrennClient + from wrenn.commands import Commands + + client = WrennClient(api_key="wrn_test1234567890abcdef12345678") + commands = Commands(CAPSULE_ID, client.http) + + route = respx.post(EXEC_URL).respond(200, json=_exec_response()) + commands.run("cd /tmp; ls -la && echo done") + body = json.loads(route.calls[0].request.content) + assert body["cmd"] == "/bin/sh" + assert body["args"] == ["-c", "cd /tmp; ls -la && echo done"] + + @respx.mock + def test_command_with_env_vars(self): + from wrenn.client import WrennClient + from wrenn.commands import Commands + + client = WrennClient(api_key="wrn_test1234567890abcdef12345678") + commands = Commands(CAPSULE_ID, client.http) + + route = respx.post(EXEC_URL).respond(200, json=_exec_response()) + commands.run("FOO=bar echo $FOO") + body = json.loads(route.calls[0].request.content) + assert body["cmd"] == "/bin/sh" + assert body["args"] == ["-c", "FOO=bar echo $FOO"] + + @respx.mock + def test_command_with_subshell(self): + from wrenn.client import WrennClient + from wrenn.commands import Commands + + client = WrennClient(api_key="wrn_test1234567890abcdef12345678") + commands = Commands(CAPSULE_ID, client.http) + + route = respx.post(EXEC_URL).respond(200, json=_exec_response()) + commands.run("echo $(date +%s)") + body = json.loads(route.calls[0].request.content) + assert body["cmd"] == "/bin/sh" + assert body["args"] == ["-c", "echo $(date +%s)"] + + @respx.mock + def test_command_with_quotes_and_spaces(self): + from wrenn.client import WrennClient + from wrenn.commands import Commands + + client = WrennClient(api_key="wrn_test1234567890abcdef12345678") + commands = Commands(CAPSULE_ID, client.http) + + route = respx.post(EXEC_URL).respond(200, json=_exec_response()) + commands.run("""echo "hello 'world'" | grep -o "'[^']*'" """) + body = json.loads(route.calls[0].request.content) + assert body["cmd"] == "/bin/sh" + assert body["args"][0] == "-c" + # The command string is passed verbatim — shell interprets it + assert "hello 'world'" in body["args"][1] + + @respx.mock + def test_heredoc_style_command(self): + from wrenn.client import WrennClient + from wrenn.commands import Commands + + client = WrennClient(api_key="wrn_test1234567890abcdef12345678") + commands = Commands(CAPSULE_ID, client.http) + + route = respx.post(EXEC_URL).respond(200, json=_exec_response()) + commands.run("python3 -c 'import sys; print(sys.version)'") + body = json.loads(route.calls[0].request.content) + assert body["cmd"] == "/bin/sh" + assert body["args"] == ["-c", "python3 -c 'import sys; print(sys.version)'"] + + @respx.mock + def test_git_shlex_joined_command(self): + """Git module uses shlex.join — verify it passes through correctly.""" + route = respx.post(EXEC_URL).respond(200, json=_exec_response()) + git = _make_git() + git.clone("https://github.com/user/repo.git", "/tmp/repo", depth=1) + body = json.loads(route.calls[0].request.content) + assert body["cmd"] == "/bin/sh" + assert body["args"][0] == "-c" + # shlex.join produces: git clone --depth 1 https://... /tmp/repo + shell_cmd = body["args"][1] + assert "git" in shell_cmd + assert "clone" in shell_cmd + assert "--depth" in shell_cmd + assert "https://github.com/user/repo.git" in shell_cmd + + @respx.mock + def test_background_command_also_wrapped(self): + from wrenn.client import WrennClient + from wrenn.commands import Commands + + client = WrennClient(api_key="wrn_test1234567890abcdef12345678") + commands = Commands(CAPSULE_ID, client.http) + + route = respx.post(EXEC_URL).respond(200, json={"pid": 42, "tag": "bg-1"}) + commands.run("tail -f /var/log/syslog", background=True) + body = json.loads(route.calls[0].request.content) + assert body["cmd"] == "/bin/sh" + assert body["args"] == ["-c", "tail -f /var/log/syslog"] + assert body["background"] is True + + +def git_cmd_from_body(body: dict) -> str: + """Extract the shell command string from a wrapped payload.""" + assert body["cmd"] == "/bin/sh" + assert body["args"][0] == "-c" + return body["args"][1] diff --git a/tests/test_integration.py b/tests/test_integration.py new file mode 100644 index 0000000..ff66983 --- /dev/null +++ b/tests/test_integration.py @@ -0,0 +1,405 @@ +from __future__ import annotations + +import os +import time +from pathlib import Path + +import pytest + +from wrenn import Capsule, CommandResult +from wrenn.commands import CommandHandle, ProcessInfo +from wrenn.models import Capsule as CapsuleModel, FileEntry, Status + +pytestmark = pytest.mark.integration + +_env_loaded = False + + +def _ensure_env() -> None: + global _env_loaded + if _env_loaded: + return + _env_loaded = True + env_file = Path(__file__).resolve().parent.parent / ".env" + if not env_file.exists(): + return + for line in env_file.read_text().splitlines(): + line = line.strip() + if not line or line.startswith("#") or "=" not in line: + continue + key, _, value = line.partition("=") + key, value = key.strip(), value.strip().strip("\"'") + if key and key not in os.environ: + os.environ[key] = value + + +class TestCapsuleLifecycle: + """Each test manages its own capsule to test create/destroy paths.""" + + def setup_method(self): + _ensure_env() + + def test_create_and_destroy(self): + capsule = Capsule() + capsule_id = capsule.capsule_id + try: + assert capsule_id + assert capsule.info is not None + finally: + capsule.destroy() + + info = Capsule.get_info(capsule_id) + assert info.status in (Status.stopped, Status.missing) + + def test_create_with_wait(self): + capsule = Capsule(wait=True) + try: + assert capsule.info is not None + assert capsule.info.status == Status.running + finally: + capsule.destroy() + + def test_context_manager_destroys(self): + with Capsule(wait=True) as capsule: + capsule_id = capsule.capsule_id + assert capsule.is_running() + + info = Capsule.get_info(capsule_id) + assert info.status in (Status.stopped, Status.missing) + + def test_get_info(self): + capsule = Capsule(wait=True) + try: + info = capsule.get_info() + assert isinstance(info, CapsuleModel) + assert info.id == capsule.capsule_id + assert info.status == Status.running + finally: + capsule.destroy() + + def test_pause_and_resume(self): + capsule = Capsule(wait=True) + try: + paused = capsule.pause() + assert paused.status == Status.paused + assert not capsule.is_running() + + resumed = capsule.resume() + assert resumed.status == Status.running + finally: + capsule.destroy() + + def test_static_destroy(self): + capsule = Capsule(wait=True) + capsule_id = capsule.capsule_id + try: + Capsule.destroy(capsule_id) + except Exception: + capsule.destroy() + raise + + info = Capsule.get_info(capsule_id) + assert info.status in (Status.stopped, Status.missing) + + def test_connect_to_existing(self): + capsule = Capsule(wait=True) + try: + connected = Capsule.connect(capsule.capsule_id) + assert connected.capsule_id == capsule.capsule_id + assert connected.info is not None + assert connected.info.status == Status.running + finally: + capsule.destroy() + + def test_connect_resumes_paused(self): + capsule = Capsule(wait=True) + try: + capsule.pause() + connected = Capsule.connect(capsule.capsule_id) + assert connected.info is not None + assert connected.info.status == Status.running + finally: + capsule.destroy() + + def test_list_capsules(self): + capsule = Capsule(wait=True) + try: + capsules = Capsule.list() + assert isinstance(capsules, list) + ids = [c.id for c in capsules] + assert capsule.capsule_id in ids + finally: + capsule.destroy() + + def test_wait_ready(self): + capsule = Capsule() + try: + capsule.wait_ready(timeout=60) + assert capsule.is_running() + finally: + capsule.destroy() + + def test_ping(self): + capsule = Capsule(wait=True) + try: + capsule.ping() + finally: + capsule.destroy() + + +class TestCommands: + """Shared capsule for command execution tests.""" + + capsule: Capsule + + @classmethod + def setup_class(cls): + _ensure_env() + cls.capsule = Capsule(wait=True) + + @classmethod + def teardown_class(cls): + try: + cls.capsule.destroy() + except Exception: + pass + + def test_run_foreground(self): + result = self.capsule.commands.run("echo hello") + assert isinstance(result, CommandResult) + assert result.exit_code == 0 + assert "hello" in result.stdout + + def test_run_stderr(self): + result = self.capsule.commands.run("echo error >&2") + assert "error" in result.stderr + + def test_run_exit_code(self): + result = self.capsule.commands.run("exit 42") + assert result.exit_code == 42 + + def test_run_with_envs(self): + result = self.capsule.commands.run("export MY_VAR=test_value && echo $MY_VAR") + assert "test_value" in result.stdout + + def test_run_with_cwd(self): + result = self.capsule.commands.run("cd /tmp && pwd") + assert result.stdout.strip() == "/tmp" + + def test_run_multiline_output(self): + result = self.capsule.commands.run("echo -e 'line1\\nline2\\nline3'") + assert result.exit_code == 0 + lines = result.stdout.strip().splitlines() + assert len(lines) == 3 + + def test_run_background(self): + handle = self.capsule.commands.run("sleep 30", background=True, tag="bg-test") + assert isinstance(handle, CommandHandle) + assert handle.pid > 0 + assert handle.tag == "bg-test" + assert handle.capsule_id == self.capsule.capsule_id + + self.capsule.commands.kill(handle.pid) + + def test_list_processes(self): + handle = self.capsule.commands.run("sleep 30", background=True, tag="list-test") + try: + time.sleep(0.5) + processes = self.capsule.commands.list() + assert isinstance(processes, list) + pids = [p.pid for p in processes] + assert handle.pid in pids + + proc = next(p for p in processes if p.pid == handle.pid) + assert isinstance(proc, ProcessInfo) + finally: + self.capsule.commands.kill(handle.pid) + + def test_kill_process(self): + handle = self.capsule.commands.run("sleep 30", background=True) + self.capsule.commands.kill(handle.pid) + time.sleep(0.5) + + processes = self.capsule.commands.list() + pids = [p.pid for p in processes] + assert handle.pid not in pids + + def test_run_duration_ms(self): + result = self.capsule.commands.run("sleep 1") + assert result.duration_ms is None or result.duration_ms >= 900 + + +class TestFiles: + """Shared capsule for filesystem tests.""" + + capsule: Capsule + + @classmethod + def setup_class(cls): + _ensure_env() + cls.capsule = Capsule(wait=True) + + @classmethod + def teardown_class(cls): + try: + cls.capsule.destroy() + except Exception: + pass + + def test_write_and_read(self): + self.capsule.files.write("/tmp/test.txt", "hello world") + content = self.capsule.files.read("/tmp/test.txt") + assert content == "hello world" + + def test_write_and_read_bytes(self): + data = b"\x00\x01\x02\xff" + self.capsule.files.write("/tmp/test.bin", data) + result = self.capsule.files.read_bytes("/tmp/test.bin") + assert result == data + + def test_list_directory(self): + self.capsule.files.write("/tmp/listdir/a.txt", "a") + self.capsule.files.write("/tmp/listdir/b.txt", "b") + entries = self.capsule.files.list("/tmp/listdir") + assert isinstance(entries, list) + names = [e.name for e in entries] + assert "a.txt" in names + assert "b.txt" in names + + def test_exists(self): + self.capsule.files.write("/tmp/exists_test.txt", "x") + assert self.capsule.files.exists("/tmp/exists_test.txt") + assert not self.capsule.files.exists("/tmp/does_not_exist_xyz.txt") + + def test_make_dir(self): + entry = self.capsule.files.make_dir("/tmp/newdir") + assert isinstance(entry, FileEntry) + assert self.capsule.files.exists("/tmp/newdir") + + def test_make_dir_idempotent(self): + self.capsule.files.make_dir("/tmp/idempotent_dir") + entry = self.capsule.files.make_dir("/tmp/idempotent_dir") + assert isinstance(entry, FileEntry) + + def test_remove_file(self): + self.capsule.files.write("/tmp/to_remove.txt", "delete me") + assert self.capsule.files.exists("/tmp/to_remove.txt") + self.capsule.files.remove("/tmp/to_remove.txt") + assert not self.capsule.files.exists("/tmp/to_remove.txt") + + def test_remove_directory(self): + self.capsule.files.make_dir("/tmp/dir_to_remove") + self.capsule.files.write("/tmp/dir_to_remove/child.txt", "data") + self.capsule.files.remove("/tmp/dir_to_remove") + assert not self.capsule.files.exists("/tmp/dir_to_remove") + + def test_write_creates_parent_dirs(self): + self.capsule.files.write("/tmp/deep/nested/dir/file.txt", "nested") + content = self.capsule.files.read("/tmp/deep/nested/dir/file.txt") + assert content == "nested" + + def test_list_with_depth(self): + self.capsule.files.write("/tmp/depth_test/a/b.txt", "deep") + entries_shallow = self.capsule.files.list("/tmp/depth_test", depth=1) + entries_deep = self.capsule.files.list("/tmp/depth_test", depth=2) + assert len(entries_deep) >= len(entries_shallow) + + def test_overwrite_file(self): + self.capsule.files.write("/tmp/overwrite.txt", "original") + self.capsule.files.write("/tmp/overwrite.txt", "updated") + content = self.capsule.files.read("/tmp/overwrite.txt") + assert content == "updated" + + def test_upload_and_download_stream(self): + chunks = [b"chunk1", b"chunk2", b"chunk3"] + self.capsule.files.upload_stream("/tmp/streamed.bin", iter(chunks)) + downloaded = b"".join(self.capsule.files.download_stream("/tmp/streamed.bin")) + assert downloaded == b"chunk1chunk2chunk3" + + +class TestGit: + """Shared capsule for git operation tests. + + Initializes a repo at /root (default cwd) since the exec API + does not support the cwd parameter. + """ + + capsule: Capsule + + @classmethod + def setup_class(cls): + _ensure_env() + cls.capsule = Capsule(wait=True) + cls.capsule.git.init(".", initial_branch="main") + cls.capsule.git.configure_user("Test User", "test@example.com") + + @classmethod + def teardown_class(cls): + try: + cls.capsule.destroy() + except Exception: + pass + + def test_init_created_repo(self): + assert self.capsule.files.exists("/root/.git") + + def test_status_clean(self): + status = self.capsule.git.status() + assert status.branch == "main" + + def test_add_and_commit(self): + self.capsule.files.write("/root/hello.txt", "hello git") + self.capsule.git.add(all=True) + result = self.capsule.git.commit("initial commit") + assert result.exit_code == 0 + + def test_status_after_commit(self): + status = self.capsule.git.status() + assert status.is_clean + + def test_status_with_changes(self): + self.capsule.files.write("/root/dirty.txt", "uncommitted") + try: + status = self.capsule.git.status() + assert not status.is_clean + paths = [f.path for f in status.files] + assert "dirty.txt" in paths + finally: + self.capsule.files.remove("/root/dirty.txt") + + def test_branches(self): + branches = self.capsule.git.branches() + assert len(branches) >= 1 + names = [b.name for b in branches] + assert "main" in names + current = [b for b in branches if b.is_current] + assert len(current) == 1 + + def test_create_and_checkout_branch(self): + self.capsule.git.create_branch("feature-1") + branches = self.capsule.git.branches() + names = [b.name for b in branches] + assert "feature-1" in names + + current = [b for b in branches if b.is_current] + assert current[0].name == "feature-1" + + self.capsule.git.checkout_branch("main") + + def test_delete_branch(self): + self.capsule.git.create_branch("to-delete") + self.capsule.git.checkout_branch("main") + self.capsule.git.delete_branch("to-delete") + + branches = self.capsule.git.branches() + names = [b.name for b in branches] + assert "to-delete" not in names + + def test_set_and_get_config(self): + self.capsule.git.set_config("test.key", "test-value") + value = self.capsule.git.get_config("test.key") + assert value == "test-value" + + def test_get_config_missing_returns_none(self): + value = self.capsule.git.get_config("nonexistent.key") + assert value is None diff --git a/uv.lock b/uv.lock index 852c192..985de91 100644 --- a/uv.lock +++ b/uv.lock @@ -1,5 +1,5 @@ version = 1 -revision = 2 +revision = 3 requires-python = ">=3.13" resolution-markers = [ "python_full_version >= '3.14'", @@ -112,6 +112,33 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/ed/3a/7f169ffc7a2d69a4f9158b1ac083f685b7f4a1a8a1db5d1e4abbb4e741b7/datamodel_code_generator-0.56.0-py3-none-any.whl", hash = "sha256:a0559683fbe90cdf2ce9b6637e3adae3e3a8056a8d0516df581d486e2834ead2", size = 256545, upload-time = "2026-04-04T09:46:17.582Z" }, ] +[package.optional-dependencies] +ruff = [ + { name = "ruff" }, +] + +[[package]] +name = "dnspython" +version = "2.8.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/8c/8b/57666417c0f90f08bcafa776861060426765fdb422eb10212086fb811d26/dnspython-2.8.0.tar.gz", hash = "sha256:181d3c6996452cb1189c4046c61599b84a5a86e099562ffde77d26984ff26d0f", size = 368251, upload-time = "2025-09-07T18:58:00.022Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ba/5a/18ad964b0086c6e62e2e7500f7edc89e3faa45033c71c1893d34eed2b2de/dnspython-2.8.0-py3-none-any.whl", hash = "sha256:01d9bbc4a2d76bf0db7c1f729812ded6d912bd318d3b1cf81d30c0f845dbf3af", size = 331094, upload-time = "2025-09-07T18:57:58.071Z" }, +] + +[[package]] +name = "email-validator" +version = "2.3.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "dnspython" }, + { name = "idna" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/f5/22/900cb125c76b7aaa450ce02fd727f452243f2e91a61af068b40adba60ea9/email_validator-2.3.0.tar.gz", hash = "sha256:9fc05c37f2f6cf439ff414f8fc46d917929974a82244c20eb10231ba60c54426", size = 51238, upload-time = "2025-08-26T13:09:06.831Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/de/15/545e2b6cf2e3be84bc1ed85613edd75b8aea69807a71c26f4ca6a9258e82/email_validator-2.3.0-py3-none-any.whl", hash = "sha256:80f13f623413e6b197ae73bb10bf4eb0908faf509ad8362c5edeb0be7fd450b4", size = 35604, upload-time = "2025-08-26T13:09:05.858Z" }, +] + [[package]] name = "genson" version = "1.3.0" @@ -158,6 +185,21 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/2a/39/e50c7c3a983047577ee07d2a9e53faf5a69493943ec3f6a384bdc792deb2/httpx-0.28.1-py3-none-any.whl", hash = "sha256:d909fcccc110f8c7faf814ca82a9a4d816bc5a6dbfea25d6591d6985b8ba59ad", size = 73517, upload-time = "2024-12-06T15:37:21.509Z" }, ] +[[package]] +name = "httpx-ws" +version = "0.9.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "anyio" }, + { name = "httpcore" }, + { name = "httpx" }, + { name = "wsproto" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/cd/cd/ca91a07ae446451f7476bf3fcc909e98cb942ff032ebfda0e3fe449aca7b/httpx_ws-0.9.0.tar.gz", hash = "sha256:797373326f70eec1ae96f6e43ae9f12002fd7d73aee139a4985eaab964338a08", size = 107105, upload-time = "2026-03-28T14:11:10.781Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/98/f8/a6bc80313a9e93c888fa10534dfce2ad76ff86911b6f485777ce6de6a073/httpx_ws-0.9.0-py3-none-any.whl", hash = "sha256:71640d2fb1bf9a225775015b33cd755cfd4c5f7e21c885192fe3adc4c387b248", size = 15759, upload-time = "2026-03-28T14:11:11.887Z" }, +] + [[package]] name = "idna" version = "3.11" @@ -564,6 +606,18 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/f1/12/de94a39c2ef588c7e6455cfbe7343d3b2dc9d6b6b2f40c4c6565744c873d/pyyaml-6.0.3-cp314-cp314t-win_arm64.whl", hash = "sha256:ebc55a14a21cb14062aa4162f906cd962b28e2e9ea38f9b4391244cd8de4ae0b", size = 149341, upload-time = "2025-09-25T21:32:56.828Z" }, ] +[[package]] +name = "respx" +version = "0.23.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "httpx" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/43/98/4e55c9c486404ec12373708d015ebce157966965a5ebe7f28ff2c784d41b/respx-0.23.1.tar.gz", hash = "sha256:242dcc6ce6b5b9bf621f5870c82a63997e8e82bc7c947f9ffe272b8f3dd5a780", size = 29243, upload-time = "2026-04-08T14:37:16.008Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/1d/4a/221da6ca167db45693d8d26c7dc79ccfc978a440251bf6721c9aaf251ac0/respx-0.23.1-py2.py3-none-any.whl", hash = "sha256:b18004b029935384bccfa6d7d9d74b4ec9af73a081cc28600fffc0447f4b8c1a", size = 25557, upload-time = "2026-04-08T14:37:14.613Z" }, +] + [[package]] name = "ruff" version = "0.15.10" @@ -627,30 +681,48 @@ name = "wrenn" version = "0.1.0" source = { editable = "." } dependencies = [ + { name = "email-validator" }, { name = "httpx" }, + { name = "httpx-ws" }, { name = "pydantic" }, ] [package.dev-dependencies] dev = [ - { name = "datamodel-code-generator" }, + { name = "datamodel-code-generator", extra = ["ruff"] }, { name = "mypy" }, { name = "pytest" }, { name = "pytest-asyncio" }, + { name = "respx" }, { name = "ruff" }, ] [package.metadata] requires-dist = [ + { name = "email-validator", specifier = ">=2.3.0" }, { name = "httpx", specifier = ">=0.28.1" }, + { name = "httpx-ws", specifier = ">=0.9.0" }, { name = "pydantic", specifier = ">=2.12.5" }, ] [package.metadata.requires-dev] dev = [ - { name = "datamodel-code-generator", specifier = ">=0.56.0" }, + { name = "datamodel-code-generator", extras = ["ruff"], specifier = ">=0.56.0" }, { name = "mypy", specifier = ">=1.20.0" }, { name = "pytest", specifier = ">=9.0.3" }, { name = "pytest-asyncio", specifier = ">=1.3.0" }, + { name = "respx", specifier = ">=0.23.1" }, { name = "ruff", specifier = ">=0.15.10" }, ] + +[[package]] +name = "wsproto" +version = "1.3.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "h11" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/c7/79/12135bdf8b9c9367b8701c2c19a14c913c120b882d50b014ca0d38083c2c/wsproto-1.3.2.tar.gz", hash = "sha256:b86885dcf294e15204919950f666e06ffc6c7c114ca900b060d6e16293528294", size = 50116, upload-time = "2025-11-20T18:18:01.871Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a4/f5/10b68b7b1544245097b2a1b8238f66f2fc6dcaeb24ba5d917f52bd2eed4f/wsproto-1.3.2-py3-none-any.whl", hash = "sha256:61eea322cdf56e8cc904bd3ad7573359a242ba65688716b0710a5eb12beab584", size = 24405, upload-time = "2025-11-20T18:18:00.454Z" }, +]