Repository navigation
feat: Phase 1b — real sandbox dispatch with per-user API keys #4
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
50 commits
Select commit
Hold shift + click to select a range
40f9370
feat: phase 1b dispatch — real sandbox execution with per-user API keys
openhands-agent 35b812f
fix: remove integration tests, fix pre-commit (pyright, ruff)
openhands-agent afd32c2
rewrite test_automation.py to simulate dispatcher lifecycle
openhands-agent 1a220ba
rewrite test_automation.py as single streaming lifecycle test
openhands-agent 3d9be66
fix output markers + add .pr/test_automation.log
openhands-agent 49d1629
add .pr/test_automation.log (force-add past .gitignore)
openhands-agent b15b229
extract tarball contents to scripts/test_tarball/
openhands-agent 236f983
test_tarball: realistic SDK automation script (ADR pattern)
openhands-agent 6f0e3a8
Merge remote-tracking branch 'origin/main' into dispatch-phase1b
openhands-agent 38fb133
feat: Phase 1b dispatch — timeout_at, conversation_id, watchdog, oh-i…
openhands-agent 3aa993f
fix: add --no-cache-dir to setup.sh to avoid stale SDK installs
openhands-agent 2540046
fix: address PR review — callback auth, race conditions, cleanup
openhands-agent 505b92b
feat: pass SANDBOX_ID/SESSION_API_KEY env vars for SDK saas_runtime_mode
openhands-agent f01493b
docs: add AGENTS.md with repo knowledge
openhands-agent b490435
Simplify dispatch: on-demand API key fetch, standard callback auth
openhands-agent 282c0a5
fix: use "key" field name matching OpenHands API response
openhands-agent c75f3dc
Squash migrations: merge 003+004, drop callback_token entirely
openhands-agent a97d65c
test: add conversation creation to sandbox test script
openhands-agent 36acab2
Delete tests/integration/test_automation_e2e.py
xingyaoww afbdc0a
Add test_automation.py run log against staging
openhands-agent ec80299
refactor: rename callback_base_url to base_url across the repo
openhands-agent f2c3c8f
Add exc_info=True to logger.error calls for stack trace logging
openhands-agent 1af3e83
refactor: remove DispatchConfig, use Settings directly
openhands-agent 7886473
Update test log: workspace+llm+secrets pass, conversation 401
openhands-agent e7df60a
fix: ruff format and lint issues in scripts
openhands-agent b83b33d
Update test log: full E2E pass including Conversation
openhands-agent 3bd1e90
Update test log: full E2E pass (SDK lint fix @ 13a4aa65)
openhands-agent 5f9ddcb
refactor: extract _find_agent_server_url to reduce nesting in _create…
openhands-agent 28c4e06
feat: download external tarballs directly inside sandbox
openhands-agent b30a602
fix: show last 1000 chars of stderr in error detail
openhands-agent c338b97
feat: log full stdout/stderr on run failure
openhands-agent 1873e84
fix: propagate setup.sh failures and include stdout in error
openhands-agent 8a94d46
feat: add run_id and automation_id to all structured logs
openhands-agent 9813217
fix: mark run as COMPLETED when entrypoint succeeds
openhands-agent b159e9d
fix: add rate limit retry for sandbox API calls
openhands-agent a699f75
refactor(dispatcher): make settings non-optional in dispatch functions
openhands-agent 2f45269
feat: fire-and-forget dispatch with sandbox verification
openhands-agent 5df2be8
fix: include error_code and error_message in sandbox failure logs
openhands-agent 673b220
fix: delete sandbox on dispatch failure
openhands-agent 48fd69b
refactor: deduplicate delete_sandbox function
openhands-agent 437b67e
Add timeout parameter to automation creation
openhands-agent f7e1c81
Fix lint: add missing blank line in constants.py
openhands-agent 263f11d
Replace dataclasses with pydantic dataclasses
openhands-agent 06ffe48
Move _mark_run_terminal to utils/run.py
openhands-agent d2c7697
refactor: align with SDK rename saas_runtime_mode -> local_agent_serv…
openhands-agent 98b8e39
Merge branch 'main' into dispatch-phase1b
malhotra5 abeb139
fix: rename triggers→trigger to match model after #11 merge, fix ruff…
openhands-agent 37d94b6
fix: rename remaining triggers→trigger in test_router.py
openhands-agent a2b9dd8
chore: remove empty tests/integration/ scaffolding
openhands-agent dc6a1a1
docs: update AGENTS.md to match actual codebase
openhands-agent File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -173,6 +173,9 @@ yarn-error.log* | |
|
|
||
| logs | ||
|
|
||
| # PR artifacts / logs | ||
| .pr/*.log | ||
|
|
||
| # agent | ||
| .envrc | ||
| cache | ||
|
|
||
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,126 @@ | ||
| # Automations Service | ||
|
|
||
| Self-contained microservice that schedules and dispatches automation runs inside OpenHands Cloud sandboxes. | ||
|
|
||
| ## Repository Structure | ||
|
|
||
| ``` | ||
| automation/ | ||
| ├── automation/ # Main application package | ||
| │ ├── app.py # FastAPI app, lifespan, background tasks | ||
| │ ├── auth.py # API key auth via OpenHands /api/keys/current | ||
| │ ├── config.py # Pydantic settings (Settings, env prefix AUTOMATION_) | ||
| │ ├── constants.py # Timeouts, polling intervals, sandbox constants | ||
| │ ├── db.py # Database engine and session factory (asyncpg / Cloud SQL) | ||
| │ ├── dispatcher.py # Polls PENDING runs, dispatches to sandbox (fire-and-forget) | ||
| │ ├── execution.py # Sandbox lifecycle: create → upload → execute → delete | ||
| │ ├── logger.py # JSON structured logging configuration | ||
| │ ├── models.py # SQLAlchemy models (Automation, AutomationRun, TarballUpload) | ||
| │ ├── router.py # API routes (CRUD, trigger, callback, runs list) | ||
| │ ├── scheduler.py # Cron scheduler — polls automations, creates PENDING runs | ||
| │ ├── schemas.py # Pydantic request/response schemas | ||
| │ ├── uploads.py # Tarball upload router | ||
| │ ├── watchdog.py # Staleness watchdog — marks hung runs as FAILED | ||
| │ ├── storage/ # File storage abstraction | ||
| │ │ ├── file_store.py # Abstract base class for file storage | ||
| │ │ └── google_cloud.py # GCS implementation | ||
| │ └── utils/ # Utility modules | ||
| │ ├── api_key.py # Per-user API key minting via service key | ||
| │ ├── cron.py # Cron schedule utilities (next/prev fire time) | ||
| │ ├── run.py # Run status transitions (create, mark, update) | ||
| │ ├── sandbox.py # Sandbox verification and cleanup | ||
| │ ├── tarball_validation.py # Tarball path validation (internal/external) | ||
| │ └── time.py # UTC time helpers | ||
| ├── containers/ | ||
| │ └── Dockerfile # Container image definition | ||
| ├── migrations/ # Alembic migrations | ||
| ├── scripts/ | ||
| │ ├── test_automation.py # E2E test (sandbox lifecycle with live streaming) | ||
| │ └── test_tarball/ # Tarball contents uploaded to sandbox during test | ||
| │ ├── main.py # Test script run inside sandbox (SDK workspace test) | ||
| │ └── setup.sh # Installs SDK inside sandbox | ||
| ├── tests/ # Unit tests (flat structure, no external deps) | ||
| │ ├── integration/ # Integration tests (require OPENHANDS_API_KEY) | ||
| │ ├── test_auth.py | ||
| │ ├── test_dispatcher.py | ||
| │ ├── test_execution.py | ||
| │ ├── test_router.py | ||
| │ ├── test_scheduler.py | ||
| │ └── ... | ||
| └── pyproject.toml | ||
| ``` | ||
|
|
||
| ## Cross-Repo Coordination | ||
|
|
||
| Three repos work together: | ||
|
|
||
| | Repo | Branch | Purpose | | ||
| |------|--------|---------| | ||
| | `OpenHands/automation` | `dispatch-phase1b` | Automation service (this repo) | | ||
| | `OpenHands/deploy` (aka `All-Hands-AI/deploy`) | `dispatch-phase1b` | Deploys automation as a sidecar | | ||
| | `OpenHands/software-agent-sdk` | `feat/saas-runtime-mode` | SDK changes for in-sandbox execution | | ||
|
|
||
| **AUTOMATION_SHA linking**: The deploy repo references a specific automation commit in two workflow files: | ||
| - `.github/workflows/deploy.yaml` → `AUTOMATION_SHA: "<full-sha>"` | ||
| - `.github/workflows/deploy-automation.yaml` → `AUTOMATION_SHA: "<full-sha>"` | ||
|
|
||
| After pushing to the automation repo, update both files in the deploy repo. | ||
|
|
||
| ## Build & Test Commands | ||
|
|
||
| ```bash | ||
| # Pre-commit (run from repo root) | ||
| pre-commit run --files automation/**/*.py scripts/**/*.py tests/**/*.py --show-diff-on-failure | ||
|
|
||
| # Unit tests (no external deps, skips Docker-dependent tests) | ||
| uv run pytest tests/ -v --ignore=tests/integration | ||
|
|
||
| # Integration test (requires OPENHANDS_API_KEY) | ||
| OPENHANDS_API_KEY=sk-oh-... uv run pytest tests/integration/ -v | ||
|
|
||
| # E2E test script (live sandbox, ~80s) | ||
| OPENHANDS_API_KEY=sk-oh-... uv run python scripts/test_automation.py --api-url https://staging.all-hands.dev | ||
| ``` | ||
|
|
||
| ## Dispatch Pipeline | ||
|
|
||
| The dispatcher uses a **fire-and-forget** model. For each PENDING run: | ||
|
|
||
| 1. **Fetch per-user API key** — `get_api_key_for_automation_run()` mints a key via the service key | ||
| 2. **Resolve tarball** — Internal (`oh-internal://`) downloads from GCS; external (HTTP) URLs are downloaded inside the sandbox | ||
| 3. **Create sandbox** — `POST /api/v1/sandboxes` (Cloud API, Bearer token auth) | ||
| 4. **Wait for RUNNING** — Poll `GET /api/v1/sandboxes?id=<id>` until status=RUNNING | ||
| 5. **Upload/download tarball** — `POST /api/file/upload/<path>` (agent-server) or `curl` inside sandbox | ||
| 6. **Start entrypoint** — `POST /api/bash/start_bash_command` (agent-server) | ||
| - Extracts tarball, runs setup.sh (if present), exports env vars, runs entrypoint | ||
| 7. **Return immediately** — Dispatcher does not wait for completion | ||
|
|
||
| Completion is handled asynchronously: | ||
| - **Happy path**: SDK inside sandbox POSTs to `POST /api/v1/automations/runs/{id}/complete` | ||
| - **Fallback**: Watchdog scans for runs past their `timeout_at` deadline, verifies status via sandbox bash history, and marks as COMPLETED or FAILED | ||
|
|
||
| ### Env Vars Injected Into Sandbox | ||
|
|
||
| | Variable | Source | Purpose | | ||
| |----------|--------|---------| | ||
| | `OPENHANDS_API_KEY` | Per-user key issued via service key | SDK auth for get_llm()/get_secrets() | | ||
| | `OPENHANDS_CLOUD_API_URL` | Config (`openhands_api_base_url`) | Cloud API base URL | | ||
| | `SANDBOX_ID` | From sandbox creation response | SDK reads for settings API calls | | ||
| | `SESSION_API_KEY` | From sandbox creation response | SDK reads for settings API auth | | ||
| | `AUTOMATION_CALLBACK_URL` | Constructed by dispatcher | SDK posts completion status here | | ||
| | `AUTOMATION_RUN_ID` | Run ID | Included in callback payload | | ||
| | `AUTOMATION_EVENT_PAYLOAD` | Trigger context JSON | Available to user's script | | ||
|
|
||
| The SDK's `OpenHandsCloudWorkspace(local_agent_server_mode=True)` reads `SANDBOX_ID`, `SESSION_API_KEY`, and `AGENT_SERVER_PORT` from env vars automatically. | ||
|
|
||
| ## Callback & Race Condition Handling | ||
|
|
||
| - **Callback auth**: The completion endpoint (`/runs/{id}/complete`) uses standard API key auth — the per-user `OPENHANDS_API_KEY` passed into the sandbox is validated via `authenticate_request`, and ownership is verified against the run's parent automation. | ||
| - **Optimistic locking**: Both callback endpoint and watchdog use `UPDATE ... WHERE status = 'RUNNING'` and check `CursorResult.rowcount` to handle races. Returns 409 on conflict. | ||
| - **Sandbox cleanup**: On callback, sandbox is deleted in a fire-and-forget background task (unless `keep_alive=True`). On dispatch failure, the dispatcher deletes the sandbox immediately. | ||
|
|
||
| ## Database | ||
|
|
||
| - **Engine**: SQLAlchemy async with asyncpg; supports direct PostgreSQL (`AUTOMATION_DB_HOST`, `AUTOMATION_DB_PORT`, etc.) or GCP Cloud SQL connector (`AUTOMATION_GCP_DB_INSTANCE`) | ||
| - **Migrations**: Alembic in `migrations/` directory | ||
| - **Locking patterns**: `FOR UPDATE SKIP LOCKED` in scheduler/dispatcher polling, optimistic `UPDATE WHERE status=X` for callback/watchdog |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,27 @@ | ||
| """Constants for the automation service.""" | ||
|
|
||
| from datetime import timedelta | ||
|
|
||
|
|
||
| # Maximum allowed timeout for automation runs (10 minutes) | ||
| # Used for: | ||
| # - Validation in API requests (timeout field) | ||
| # - Default timeout passed to sandbox execution | ||
| # - Watchdog staleness detection | ||
| MAX_RUN_DURATION = timedelta(minutes=10) | ||
| MAX_RUN_DURATION_SECONDS = int(MAX_RUN_DURATION.total_seconds()) | ||
|
|
||
| # Sandbox execution constants | ||
| SANDBOX_POLL_INTERVAL = 5 # seconds between status checks | ||
| SANDBOX_READY_TIMEOUT = 300 # max wait for sandbox to become ready | ||
| WORK_DIR = "/workspace/automation" | ||
| TARBALL_PATH = "/tmp/automation.tar.gz" | ||
|
|
||
| # Limits for external tarball downloads (in sandbox) | ||
| EXTERNAL_DOWNLOAD_TIMEOUT = 120 # seconds | ||
| EXTERNAL_MAX_FILESIZE = 100 * 1024 * 1024 # 100 MB | ||
|
|
||
| # Rate limit retry settings | ||
| RATE_LIMIT_MIN_WAIT = 10 # initial wait after a 429 | ||
| RATE_LIMIT_MAX_WAIT = 60 # max wait between retries | ||
| RATE_LIMIT_MAX_RETRIES = 5 |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.