agentenv-framework 0.9.1254__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- agent_env/__init__.py +0 -0
- agent_env/a2a_agent/__init__.py +23 -0
- agent_env/a2a_agent/a2a_agent.py +600 -0
- agent_env/a2a_agent/conversation_store.py +356 -0
- agent_env/a2a_agent/object_transfer.py +609 -0
- agent_env/a2a_agent/protocol.py +238 -0
- agent_env/a2a_agent/store.py +201 -0
- agent_env/a2a_agent/validator.py +901 -0
- agent_env/artifact/__init__.py +48 -0
- agent_env/artifact/artifact.py +74 -0
- agent_env/artifact/artifacts/__init__.py +0 -0
- agent_env/artifact/artifacts/cli.py +83 -0
- agent_env/artifact/artifacts/docker_image.py +457 -0
- agent_env/artifact/artifacts/environment.py +89 -0
- agent_env/artifact/artifacts/environment_universe.py +156 -0
- agent_env/artifact/artifacts/file.py +214 -0
- agent_env/artifact/artifacts/file_artifact_universe.py +206 -0
- agent_env/artifact/artifacts/skill.py +206 -0
- agent_env/artifact/artifacts/vm_image.py +95 -0
- agent_env/artifact/ref.py +15 -0
- agent_env/artifact/registry.py +251 -0
- agent_env/artifact/store.py +295 -0
- agent_env/artifact/universe.py +38 -0
- agent_env/attribution.py +41 -0
- agent_env/bundle/__init__.py +4 -0
- agent_env/bundle/_fs.py +128 -0
- agent_env/bundle/authoring.py +239 -0
- agent_env/bundle/installed.py +175 -0
- agent_env/bundle/ledger.py +269 -0
- agent_env/bundle/materialize.py +204 -0
- agent_env/bundle/parse.py +594 -0
- agent_env/bundle/plan.py +414 -0
- agent_env/bundle/resolve.py +404 -0
- agent_env/bundle/run.py +361 -0
- agent_env/cli/__init__.py +69 -0
- agent_env/cli/__main__.py +10 -0
- agent_env/cli/_installers.py +576 -0
- agent_env/cli/_plugin_changes.py +947 -0
- agent_env/cli/a2a_agent/__init__.py +22 -0
- agent_env/cli/a2a_agent/add_skill.py +97 -0
- agent_env/cli/a2a_agent/deploy.py +60 -0
- agent_env/cli/a2a_agent/get.py +15 -0
- agent_env/cli/a2a_agent/get_instance.py +26 -0
- agent_env/cli/a2a_agent/put.py +78 -0
- agent_env/cli/a2a_agent/validate.py +56 -0
- agent_env/cli/artifact/__init__.py +20 -0
- agent_env/cli/artifact/cli.py +83 -0
- agent_env/cli/artifact/environment.py +44 -0
- agent_env/cli/artifact/environment_universe.py +163 -0
- agent_env/cli/artifact/file_artifact_universe.py +281 -0
- agent_env/cli/artifact/skill.py +128 -0
- agent_env/cli/banner.py +25 -0
- agent_env/cli/config.py +263 -0
- agent_env/cli/env/__init__.py +31 -0
- agent_env/cli/env/deploy.py +112 -0
- agent_env/cli/env/gateway.py +57 -0
- agent_env/cli/env/get_instance.py +40 -0
- agent_env/cli/env/mcp_server.py +410 -0
- agent_env/cli/env/multi.py +282 -0
- agent_env/cli/env/service_db.py +99 -0
- agent_env/cli/env/snapshot.py +35 -0
- agent_env/cli/env/state/__init__.py +6 -0
- agent_env/cli/env/state/init.py +108 -0
- agent_env/cli/env/state/teardown.py +44 -0
- agent_env/cli/env/website.py +216 -0
- agent_env/cli/env/website_browser.py +67 -0
- agent_env/cli/eval/__init__.py +16 -0
- agent_env/cli/eval/add_tasks.py +63 -0
- agent_env/cli/eval/create.py +49 -0
- agent_env/cli/eval/run.py +194 -0
- agent_env/cli/identity/__init__.py +5 -0
- agent_env/cli/identity/client_identity.py +37 -0
- agent_env/cli/plugin.py +438 -0
- agent_env/cli/run.py +285 -0
- agent_env/cli/task/__init__.py +21 -0
- agent_env/cli/task/create.py +109 -0
- agent_env/cli/task/get.py +17 -0
- agent_env/cli/task/get_instance.py +34 -0
- agent_env/cli/task/run.py +615 -0
- agent_env/cli/task/validate.py +31 -0
- agent_env/cli/up.py +123 -0
- agent_env/cli/utils.py +183 -0
- agent_env/config/__init__.py +50 -0
- agent_env/config/describe.py +1067 -0
- agent_env/config/errors.py +13 -0
- agent_env/config/loader.py +245 -0
- agent_env/config/model.py +154 -0
- agent_env/config/paths.py +25 -0
- agent_env/config/plugin_tables.py +101 -0
- agent_env/config/provenance.py +134 -0
- agent_env/config/runtime.py +1064 -0
- agent_env/config/snapshot.py +81 -0
- agent_env/entity_refs.py +186 -0
- agent_env/env/__init__.py +49 -0
- agent_env/env/env.py +433 -0
- agent_env/env/env_artifact_store.py +87 -0
- agent_env/env/envs/__init__.py +7 -0
- agent_env/env/envs/_deployment.py +281 -0
- agent_env/env/envs/gateway_server.py +32 -0
- agent_env/env/envs/mcp_server.py +387 -0
- agent_env/env/envs/multi_env.py +780 -0
- agent_env/env/envs/service_db/Dockerfile +20 -0
- agent_env/env/envs/service_db/Dockerfile.db-mcp +42 -0
- agent_env/env/envs/service_db/Dockerfile.db-web +8 -0
- agent_env/env/envs/service_db.py +92 -0
- agent_env/env/envs/website.py +294 -0
- agent_env/env/envs/website_browser/Dockerfile +40 -0
- agent_env/env/envs/website_browser/__init__.py +17 -0
- agent_env/env/envs/website_browser/entrypoint.sh +13 -0
- agent_env/env/gateway/Dockerfile +14 -0
- agent_env/env/gateway/__init__.py +37 -0
- agent_env/env/gateway/clock.py +184 -0
- agent_env/env/gateway/constants.py +190 -0
- agent_env/env/gateway/entrypoint.py +156 -0
- agent_env/env/gateway/gateway.py +1095 -0
- agent_env/env/gateway/get_time.py +60 -0
- agent_env/env/gateway/requirements.txt +4 -0
- agent_env/env/gateway/triggers.py +1193 -0
- agent_env/env/legacy_protocol.py +146 -0
- agent_env/env/registry.py +93 -0
- agent_env/env/snapshot_store.py +372 -0
- agent_env/env/store.py +411 -0
- agent_env/eval/__init__.py +14 -0
- agent_env/eval/eval.py +68 -0
- agent_env/eval/store.py +116 -0
- agent_env/examples/hello/README.md +9 -0
- agent_env/examples/hello/artifacts/greeting/check.sh +1 -0
- agent_env/examples/hello/artifacts/greeting/hello.txt +1 -0
- agent_env/examples/hello/tasks/hello.json +10 -0
- agent_env/explorer/__init__.py +12 -0
- agent_env/explorer/app.py +277 -0
- agent_env/explorer/openapi_docs.py +242 -0
- agent_env/explorer/plugin.py +95 -0
- agent_env/explorer/routers/__init__.py +1 -0
- agent_env/explorer/routers/common.py +174 -0
- agent_env/explorer/routers/conversations.py +25 -0
- agent_env/explorer/routers/objects.py +112 -0
- agent_env/explorer/routers/runs.py +475 -0
- agent_env/plugins/__init__.py +59 -0
- agent_env/plugins/_cli.py +244 -0
- agent_env/plugins/_discovery.py +97 -0
- agent_env/plugins/_inventory.py +262 -0
- agent_env/plugins/_registration.py +268 -0
- agent_env/plugins/_report.py +47 -0
- agent_env/plugins/_requirements.py +55 -0
- agent_env/providers/__init__.py +37 -0
- agent_env/providers/env_providers/__init__.py +12 -0
- agent_env/providers/env_providers/constants.py +13 -0
- agent_env/providers/env_providers/env_gateway_provider.py +1354 -0
- agent_env/providers/env_providers/env_provider.py +237 -0
- agent_env/providers/env_providers/env_server_provider.py +133 -0
- agent_env/providers/env_state/__init__.py +49 -0
- agent_env/providers/env_state/env_state_provider.py +554 -0
- agent_env/providers/env_state/local_postgres.py +390 -0
- agent_env/providers/env_state/store.py +112 -0
- agent_env/providers/sandbox_providers/__init__.py +29 -0
- agent_env/providers/sandbox_providers/chained_sandbox_provider.py +93 -0
- agent_env/providers/sandbox_providers/e2b/__init__.py +6 -0
- agent_env/providers/sandbox_providers/e2b/provider.py +376 -0
- agent_env/providers/sandbox_providers/e2b/sandbox.py +342 -0
- agent_env/providers/sandbox_providers/e2b/template.py +158 -0
- agent_env/providers/sandbox_providers/local_sandbox.py +408 -0
- agent_env/providers/sandbox_providers/modal_sandbox.py +500 -0
- agent_env/providers/sandbox_providers/modal_vm_sandbox.py +466 -0
- agent_env/providers/sandbox_providers/sandbox.py +387 -0
- agent_env/providers/sandbox_providers/sandbox_provider.py +614 -0
- agent_env/py.typed +0 -0
- agent_env/runner/__init__.py +16 -0
- agent_env/runner/local_runner.py +190 -0
- agent_env/runner/runner.py +127 -0
- agent_env/runner/store.py +94 -0
- agent_env/store/__init__.py +126 -0
- agent_env/store/_google.py +68 -0
- agent_env/store/base.py +33 -0
- agent_env/store/document_store/__init__.py +60 -0
- agent_env/store/document_store/document_store.py +519 -0
- agent_env/store/document_store/dynamodb_document_store.py +306 -0
- agent_env/store/document_store/evaluation.py +199 -0
- agent_env/store/document_store/firestore_mongo_document_store.py +242 -0
- agent_env/store/document_store/mongo_document_store.py +259 -0
- agent_env/store/document_store/sqlite_document_store.py +314 -0
- agent_env/store/ids.py +123 -0
- agent_env/store/image_store/__init__.py +34 -0
- agent_env/store/image_store/ecr_image_store.py +131 -0
- agent_env/store/image_store/google_credentials.py +113 -0
- agent_env/store/image_store/image_store.py +113 -0
- agent_env/store/image_store/local_registry_image_store.py +106 -0
- agent_env/store/image_store/oci_registry_credentials.py +196 -0
- agent_env/store/local_state.py +27 -0
- agent_env/store/object_store/__init__.py +24 -0
- agent_env/store/object_store/gcs_object_store.py +415 -0
- agent_env/store/object_store/local_object_store.py +143 -0
- agent_env/store/object_store/object_store.py +198 -0
- agent_env/store/object_store/s3_object_store.py +354 -0
- agent_env/store/query.py +112 -0
- agent_env/store/routing.py +609 -0
- agent_env/store/secret_store/__init__.py +19 -0
- agent_env/store/secret_store/aws_secrets_manager_secret_store.py +293 -0
- agent_env/store/secret_store/gcp_secret_manager_secret_store.py +319 -0
- agent_env/store/secret_store/local_secret_store.py +47 -0
- agent_env/store/secret_store/secret_store.py +19 -0
- agent_env/task/__init__.py +27 -0
- agent_env/task/interrupts.py +109 -0
- agent_env/task/registry.py +27 -0
- agent_env/task/step_journal.py +99 -0
- agent_env/task/store.py +940 -0
- agent_env/task/task.py +815 -0
- agent_env/task/teardown.py +142 -0
- agent_env/task_step/__init__.py +47 -0
- agent_env/task_step/context.py +195 -0
- agent_env/task_step/context_ops.py +224 -0
- agent_env/task_step/registry.py +182 -0
- agent_env/task_step/review_store.py +118 -0
- agent_env/task_step/snapshot_utils/__init__.py +2 -0
- agent_env/task_step/snapshot_utils/agent_state_capture.py +261 -0
- agent_env/task_step/snapshot_utils/snapshot_series.py +631 -0
- agent_env/task_step/store.py +129 -0
- agent_env/task_step/task_step.py +173 -0
- agent_env/task_step/task_steps/__init__.py +27 -0
- agent_env/task_step/task_steps/a2a_agent_validator/__init__.py +31 -0
- agent_env/task_step/task_steps/a2a_agent_validator/fixtures/README.md +158 -0
- agent_env/task_step/task_steps/a2a_agent_validator/fixtures/clip.m4a +0 -0
- agent_env/task_step/task_steps/a2a_agent_validator/fixtures/clip.mp3 +0 -0
- agent_env/task_step/task_steps/a2a_agent_validator/fixtures/clip.mp4 +0 -0
- agent_env/task_step/task_steps/a2a_agent_validator/fixtures/clip.ogg +0 -0
- agent_env/task_step/task_steps/a2a_agent_validator/fixtures/clip.wav +0 -0
- agent_env/task_step/task_steps/a2a_agent_validator/fixtures/document.pdf +0 -0
- agent_env/task_step/task_steps/a2a_agent_validator/fixtures/red.gif +0 -0
- agent_env/task_step/task_steps/a2a_agent_validator/fixtures/red.jpg +0 -0
- agent_env/task_step/task_steps/a2a_agent_validator/fixtures/red.png +0 -0
- agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_agent_card.py +103 -0
- agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_agent_config_identity.py +69 -0
- agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_agent_mcp.py +178 -0
- agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_core_protocol.py +67 -0
- agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_install.py +115 -0
- agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_litellm_attribution.py +124 -0
- agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_litellm_attribution_runtime.py +173 -0
- agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_modalities.py +270 -0
- agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_peer_agents.py +102 -0
- agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_role.py +151 -0
- agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_skill_config.py +194 -0
- agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_snapshot.py +111 -0
- agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_system_prompt.py +215 -0
- agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_trajectory.py +164 -0
- agent_env/task_step/task_steps/add_skills.py +240 -0
- agent_env/task_step/task_steps/apply_server_config.py +288 -0
- agent_env/task_step/task_steps/collect_artifacts.py +940 -0
- agent_env/task_step/task_steps/deploy_agent.py +626 -0
- agent_env/task_step/task_steps/deploy_env.py +197 -0
- agent_env/task_step/task_steps/deploy_human_agent.py +100 -0
- agent_env/task_step/task_steps/deploy_sandbox.py +170 -0
- agent_env/task_step/task_steps/env_card_validator/__init__.py +4 -0
- agent_env/task_step/task_steps/env_card_validator/verify_env_card.py +109 -0
- agent_env/task_step/task_steps/env_card_validator/verify_env_core_protocol.py +108 -0
- agent_env/task_step/task_steps/install_agent.py +376 -0
- agent_env/task_step/task_steps/load_artifact.py +775 -0
- agent_env/task_step/task_steps/mcp_cli_builder/__init__.py +4 -0
- agent_env/task_step/task_steps/mcp_cli_builder/build_mcp_cli.py +201 -0
- agent_env/task_step/task_steps/mcp_cli_builder/codegen.py +627 -0
- agent_env/task_step/task_steps/mcp_env_validator/__init__.py +44 -0
- agent_env/task_step/task_steps/mcp_env_validator/validation_gate_aggregator.py +102 -0
- agent_env/task_step/task_steps/mcp_env_validator/verify_mcp_env_assessment.py +78 -0
- agent_env/task_step/task_steps/mcp_env_validator/verify_mcp_tool_schema.py +152 -0
- agent_env/task_step/task_steps/mcp_env_validator/verify_spec_conformance.py +486 -0
- agent_env/task_step/task_steps/modify_env_tool_access.py +80 -0
- agent_env/task_step/task_steps/multienv_validator/__init__.py +3 -0
- agent_env/task_step/task_steps/multienv_validator/combine_universe_verdicts.py +107 -0
- agent_env/task_step/task_steps/multienv_validator/universe_comparison.py +253 -0
- agent_env/task_step/task_steps/multienv_validator/verify_universe_agent_judge.py +180 -0
- agent_env/task_step/task_steps/multienv_validator/verify_universe_roundtrip.py +241 -0
- agent_env/task_step/task_steps/peer_agents.py +92 -0
- agent_env/task_step/task_steps/prompt_agent.py +900 -0
- agent_env/task_step/task_steps/register_agent_triggers.py +113 -0
- agent_env/task_step/task_steps/register_env_triggers.py +97 -0
- agent_env/task_step/task_steps/reset_env.py +71 -0
- agent_env/task_step/task_steps/review.py +152 -0
- agent_env/task_step/task_steps/run_code.py +461 -0
- agent_env/task_step/task_steps/run_code_runner.py +52 -0
- agent_env/task_step/task_steps/run_docker_container.py +380 -0
- agent_env/task_step/task_steps/sandbox_utils/__init__.py +0 -0
- agent_env/task_step/task_steps/sandbox_utils/sandbox_utils.py +79 -0
- agent_env/task_step/task_steps/snapshot_agent_state.py +205 -0
- agent_env/task_step/task_steps/snapshot_env.py +637 -0
- agent_env/task_step/task_steps/sync_env_clock.py +132 -0
- agent_env/task_step/task_steps/teardown_sandboxes.py +170 -0
- agent_env/task_step/task_steps/verifiers/__init__.py +23 -0
- agent_env/task_step/task_steps/verifiers/agent_prompt_response_verifier.py +166 -0
- agent_env/task_step/task_steps/verifiers/aggregate_verifiers.py +90 -0
- agent_env/task_step/task_steps/verifiers/env_outcome_verifier.py +127 -0
- agent_env/task_step/task_steps/verifiers/judge_utils/__init__.py +2 -0
- agent_env/task_step/task_steps/verifiers/judge_utils/frame_selection.py +377 -0
- agent_env/task_step/task_steps/verifiers/judge_utils/judge_output_format.py +1293 -0
- agent_env/task_step/task_steps/verifiers/judge_utils/trajectory_filter.py +514 -0
- agent_env/task_step/task_steps/verifiers/rubrics_verifier.py +1318 -0
- agent_env/task_step/task_steps/verifiers/run_container_unit_tests_verifier.py +434 -0
- agent_env/task_step/task_steps/verifiers/scoring.py +40 -0
- agent_env/task_step/task_steps/verifiers/verify_sandbox.py +308 -0
- agent_env/task_step/thread_work.py +61 -0
- agent_env/utils/__init__.py +0 -0
- agent_env/utils/card_naming.py +108 -0
- agent_env/utils/deprecation.py +109 -0
- agent_env/utils/docker_build.py +29 -0
- agent_env/utils/exec_retry.py +77 -0
- agent_env/utils/litellm_attribution.py +59 -0
- agent_env/utils/paths.py +20 -0
- agentenv_framework-0.9.1254.dist-info/METADATA +394 -0
- agentenv_framework-0.9.1254.dist-info/RECORD +312 -0
- agentenv_framework-0.9.1254.dist-info/WHEEL +4 -0
- agentenv_framework-0.9.1254.dist-info/entry_points.txt +5 -0
- agentenv_framework-0.9.1254.dist-info/licenses/LICENSE +202 -0
- agentenv_framework-0.9.1254.dist-info/licenses/NOTICE +4 -0
- agentenv_framework-0.9.1254.dist-info/licenses/THIRD_PARTY_NOTICES.md +7665 -0
|
@@ -0,0 +1,387 @@
|
|
|
1
|
+
"""Sandbox interfaces for agent-env compute backends."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import logging
|
|
7
|
+
import os
|
|
8
|
+
import shlex
|
|
9
|
+
import time
|
|
10
|
+
import uuid
|
|
11
|
+
import weakref
|
|
12
|
+
from abc import ABC, abstractmethod
|
|
13
|
+
from dataclasses import dataclass, replace
|
|
14
|
+
from enum import Enum
|
|
15
|
+
from typing import TYPE_CHECKING, Any, Iterable, Optional
|
|
16
|
+
|
|
17
|
+
from agent_env.config import get_config
|
|
18
|
+
|
|
19
|
+
if TYPE_CHECKING:
|
|
20
|
+
from agent_env.store.object_store import ObjectStore
|
|
21
|
+
|
|
22
|
+
logger = logging.getLogger(__name__)
|
|
23
|
+
|
|
24
|
+
# curl flags that make in-VM downloads resilient to transient DNS / network
|
|
25
|
+
# blips inside the sandbox VM — most notably `curl: (6) Could not resolve host`
|
|
26
|
+
# (exit 6), which we've seen cascade into thousands of step failures when
|
|
27
|
+
# per-node DNS throughput is throttled on busy worker nodes.
|
|
28
|
+
#
|
|
29
|
+
# curl does NOT retry exit 6 by default, and `--retry-connrefused` only covers
|
|
30
|
+
# connection-refused — neither retries a resolution failure. `--retry-all-errors`
|
|
31
|
+
# is required to retry on exit 6 (curl >= 7.71; the Ubuntu 22.04 containerdisk
|
|
32
|
+
# ships 7.81). Without it, a single transient DNS hiccup escalates straight to
|
|
33
|
+
# runner-level step retries instead of being absorbed locally in ~seconds.
|
|
34
|
+
#
|
|
35
|
+
# IMPORTANT: only safe for downloads written to a file via `-o`. curl cannot
|
|
36
|
+
# rewind data it has already streamed to stdout, so retrying a
|
|
37
|
+
# `curl ... | gunzip | docker load` pipeline would append a second response to
|
|
38
|
+
# the partial bytes already consumed, corrupting the stream. Pipe consumers must
|
|
39
|
+
# download to a temp file first, then read the file (see load_docker_images).
|
|
40
|
+
CURL_RETRY_FLAGS = "--retry 5 --retry-all-errors --retry-delay 1"
|
|
41
|
+
|
|
42
|
+
# At most this many image signs in flight per event loop: each holds a worker thread, for up to a
|
|
43
|
+
# remote signer's whole retry window, and a connection from its session's pool.
|
|
44
|
+
_CONCURRENT_SIGNS = 8
|
|
45
|
+
_sign_slots: weakref.WeakKeyDictionary[asyncio.AbstractEventLoop, asyncio.Semaphore] = weakref.WeakKeyDictionary()
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class NetworkPolicyUnsupportedError(NotImplementedError):
|
|
49
|
+
"""A backend was asked to enforce a policy it cannot."""
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class NetworkMode(str, Enum):
|
|
53
|
+
ALLOW_ALL = "allow_all"
|
|
54
|
+
ALLOWLIST = "allowlist"
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
@dataclass(frozen=True)
|
|
58
|
+
class NetworkPolicy:
|
|
59
|
+
"""Outbound egress intent for a sandbox; hostnames are the primary form."""
|
|
60
|
+
|
|
61
|
+
mode: NetworkMode = NetworkMode.ALLOW_ALL
|
|
62
|
+
allow_hosts: tuple[str, ...] = ()
|
|
63
|
+
allow_cidrs: tuple[str, ...] = ()
|
|
64
|
+
|
|
65
|
+
def __post_init__(self) -> None:
|
|
66
|
+
# NetworkMode subclasses str, so an uncoerced mode misreads every `is` comparison.
|
|
67
|
+
object.__setattr__(self, "mode", NetworkMode(self.mode))
|
|
68
|
+
for field in ("allow_hosts", "allow_cidrs"):
|
|
69
|
+
value = getattr(self, field)
|
|
70
|
+
if isinstance(value, (str, bytes)):
|
|
71
|
+
raise ValueError(f"{field} must be a sequence of entries, not the string {value!r}")
|
|
72
|
+
object.__setattr__(self, field, tuple(value))
|
|
73
|
+
if "*" in self.allow_hosts:
|
|
74
|
+
raise ValueError("allow_hosts cannot contain a bare '*'; use mode=allow_all instead")
|
|
75
|
+
if self.mode is NetworkMode.ALLOW_ALL and (self.allow_hosts or self.allow_cidrs):
|
|
76
|
+
raise ValueError("allow_all permits everything; entries would be silently ignored")
|
|
77
|
+
|
|
78
|
+
@property
|
|
79
|
+
def restricts_egress(self) -> bool:
|
|
80
|
+
return self.mode is not NetworkMode.ALLOW_ALL
|
|
81
|
+
|
|
82
|
+
def with_hosts(self, hosts: Iterable[str]) -> "NetworkPolicy":
|
|
83
|
+
"""Copy with ``hosts`` unioned in; a no-op for ALLOW_ALL, which needs no list."""
|
|
84
|
+
if self.mode is not NetworkMode.ALLOWLIST:
|
|
85
|
+
return self
|
|
86
|
+
merged = list(self.allow_hosts) + [h for h in hosts if h not in self.allow_hosts]
|
|
87
|
+
return replace(self, allow_hosts=tuple(merged))
|
|
88
|
+
|
|
89
|
+
def to_dict(self) -> dict:
|
|
90
|
+
return {
|
|
91
|
+
"mode": self.mode.value,
|
|
92
|
+
"allow_hosts": list(self.allow_hosts),
|
|
93
|
+
"allow_cidrs": list(self.allow_cidrs),
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
@classmethod
|
|
97
|
+
def from_dict(cls, data: dict) -> "NetworkPolicy":
|
|
98
|
+
if not isinstance(data, dict):
|
|
99
|
+
raise ValueError(f"network policy must be a mapping, got {type(data).__name__}")
|
|
100
|
+
raw = data.get("mode", NetworkMode.ALLOW_ALL.value)
|
|
101
|
+
try:
|
|
102
|
+
mode = NetworkMode(raw)
|
|
103
|
+
except ValueError:
|
|
104
|
+
raise ValueError(f"Unknown network policy mode {raw!r}; expected one of {[m.value for m in NetworkMode]}")
|
|
105
|
+
# Raw, not tuple()'d: __post_init__ must see a string to reject it.
|
|
106
|
+
return cls(
|
|
107
|
+
mode=mode,
|
|
108
|
+
allow_hosts=data.get("allow_hosts") or (),
|
|
109
|
+
allow_cidrs=data.get("allow_cidrs") or (),
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
class Sandbox(ABC):
|
|
114
|
+
"""Universal sandbox contract — anything that can host a process and expose ports."""
|
|
115
|
+
|
|
116
|
+
type: str
|
|
117
|
+
mode: str # "vm" or "container"
|
|
118
|
+
sandbox_id: str
|
|
119
|
+
tunnel_urls: dict[int, str]
|
|
120
|
+
vnc_url: str | None
|
|
121
|
+
# Effective, as applied by the backend; None when it cannot tell us.
|
|
122
|
+
network_policy: NetworkPolicy | None = None
|
|
123
|
+
|
|
124
|
+
_VM_READY_TIMEOUT = 1200 # wait_for_vm wall-clock budget (s)
|
|
125
|
+
_VM_READY_POLL_INTERVAL = 30 # sparse polling (s)
|
|
126
|
+
|
|
127
|
+
def host_port(self, port: int) -> int:
|
|
128
|
+
"""The host-side port a published container port is reachable on.
|
|
129
|
+
|
|
130
|
+
Identity for any backend that gives a deployment its own network namespace.
|
|
131
|
+
Backends that share a host override this to avoid collisions between concurrent
|
|
132
|
+
deployments; container ports are unaffected either way.
|
|
133
|
+
"""
|
|
134
|
+
return port
|
|
135
|
+
|
|
136
|
+
@abstractmethod
|
|
137
|
+
async def terminate(self) -> None:
|
|
138
|
+
"""Terminate the sandbox."""
|
|
139
|
+
|
|
140
|
+
async def exec(self, *command: str) -> Any:
|
|
141
|
+
"""Execute a command in the sandbox. Returns a ContainerProcess-like object with stdout, stderr, wait()."""
|
|
142
|
+
raise NotImplementedError(f"{self.__class__.__name__} does not support exec")
|
|
143
|
+
|
|
144
|
+
async def exec_with_output(self, *args: str) -> tuple[int, str, str]:
|
|
145
|
+
"""Execute command and return (exit_code, stdout, stderr)."""
|
|
146
|
+
process = await self.exec(*args)
|
|
147
|
+
stdout, stderr = await asyncio.gather(process.stdout.read(), process.stderr.read())
|
|
148
|
+
exit_code = await process.wait()
|
|
149
|
+
return exit_code, stdout.decode(), stderr.decode()
|
|
150
|
+
|
|
151
|
+
async def write_file_from_s3(self, s3_url: str, destination_path: str) -> None:
|
|
152
|
+
"""Write a file from S3 into the agent process's filesystem at destination_path."""
|
|
153
|
+
raise NotImplementedError(f"{self.__class__.__name__} does not support write_file_from_s3")
|
|
154
|
+
|
|
155
|
+
async def write_file_from_url(self, url: str, destination_path: str) -> None:
|
|
156
|
+
"""Download an HTTP(S) URL into the agent process's filesystem at destination_path."""
|
|
157
|
+
raise NotImplementedError(f"{self.__class__.__name__} does not support write_file_from_url")
|
|
158
|
+
|
|
159
|
+
async def write_file_from_text(self, content: str, destination_path: str) -> None:
|
|
160
|
+
"""Write inline text content into the agent process's filesystem at destination_path."""
|
|
161
|
+
raise NotImplementedError(f"{self.__class__.__name__} does not support write_file_from_text")
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
class VmSandbox(Sandbox):
|
|
165
|
+
"""VM-style sandbox with a Docker daemon and shell access inside."""
|
|
166
|
+
|
|
167
|
+
_VM_READY_TIMEOUT = 180
|
|
168
|
+
_VM_READY_POLL_INTERVAL = 5
|
|
169
|
+
|
|
170
|
+
@property
|
|
171
|
+
def container_name(self) -> str:
|
|
172
|
+
"""Docker name of the agent container this sandbox runs. Fixed ``agent-api`` by default —
|
|
173
|
+
one agent per VM, so callers can find it by name. A backend that packs multiple agents onto
|
|
174
|
+
one Docker host (the local sandbox) overrides this per-sandbox so they don't collide and
|
|
175
|
+
teardown removes only its own container."""
|
|
176
|
+
return "agent-api"
|
|
177
|
+
|
|
178
|
+
async def exec_script(self, script: str, *, max_retries: int = 0) -> str:
|
|
179
|
+
"""Execute a bash script in the sandbox.
|
|
180
|
+
|
|
181
|
+
Set ``max_retries`` > 0 only for idempotent scripts. Retries are gated
|
|
182
|
+
on exit code -1, which a provider's exec client returns when the server
|
|
183
|
+
closes the websocket without sending an exit frame (e.g. a control
|
|
184
|
+
plane wrapping a transient port-forward 500 as a generic error). Real
|
|
185
|
+
script failures (positive exit codes) raise immediately.
|
|
186
|
+
"""
|
|
187
|
+
for attempt in range(max_retries + 1):
|
|
188
|
+
exit_code, stdout, stderr = await self.exec_with_output("sudo", "bash", "-c", script)
|
|
189
|
+
if exit_code == 0:
|
|
190
|
+
return stdout
|
|
191
|
+
if exit_code != -1 or attempt == max_retries:
|
|
192
|
+
raise RuntimeError(f"Script failed (exit {exit_code}):\nstdout: {stdout[-1500:]}\nstderr: {stderr[-1500:]}")
|
|
193
|
+
backoff = 2 ** attempt
|
|
194
|
+
logger.warning(
|
|
195
|
+
f"exec_script exit -1 (transient server error), retrying in {backoff}s "
|
|
196
|
+
f"(attempt {attempt + 1}/{max_retries + 1}); stderr tail: {stderr[-200:]!r}"
|
|
197
|
+
)
|
|
198
|
+
await asyncio.sleep(backoff)
|
|
199
|
+
raise AssertionError("unreachable")
|
|
200
|
+
|
|
201
|
+
async def setup_vm_for_gateway(self, exposed_ports: Optional[list[int]] = None) -> None:
|
|
202
|
+
"""Wait for VM and open firewall ports. Docker is pre-installed in the containerdisk image."""
|
|
203
|
+
await self.wait_for_vm()
|
|
204
|
+
if exposed_ports:
|
|
205
|
+
logger.info("Configuring firewall for exposed ports...")
|
|
206
|
+
for port in exposed_ports:
|
|
207
|
+
await self.exec_script(f"iptables -I INPUT -p tcp --dport {port} -j ACCEPT || true")
|
|
208
|
+
|
|
209
|
+
async def wait_for_vm(self) -> None:
|
|
210
|
+
"""Poll until the VM's /exec endpoint is reachable, bounded by
|
|
211
|
+
``_VM_READY_TIMEOUT`` wall-clock seconds."""
|
|
212
|
+
logger.info(
|
|
213
|
+
f"Waiting for VM /exec to become reachable "
|
|
214
|
+
f"(budget {self._VM_READY_TIMEOUT}s wall-clock)..."
|
|
215
|
+
)
|
|
216
|
+
deadline = time.monotonic() + self._VM_READY_TIMEOUT
|
|
217
|
+
attempts = 0
|
|
218
|
+
last_err: BaseException | None = None
|
|
219
|
+
while time.monotonic() < deadline:
|
|
220
|
+
attempts += 1
|
|
221
|
+
try:
|
|
222
|
+
# Probe both bash and the Docker data dir — confirms /exec is
|
|
223
|
+
# routing, the rootfs is mounted, and Docker is installed
|
|
224
|
+
# before the deploy starts loading images into the daemon.
|
|
225
|
+
await self.exec_script("ls /var/lib/docker > /dev/null && echo ready")
|
|
226
|
+
elapsed = self._VM_READY_TIMEOUT - max(0.0, deadline - time.monotonic())
|
|
227
|
+
logger.info(f"VM /exec reachable after {elapsed:.0f}s ({attempts} attempts)")
|
|
228
|
+
return
|
|
229
|
+
except Exception as e:
|
|
230
|
+
last_err = e
|
|
231
|
+
# Sleep is unconditional (every iteration); the log just throttles
|
|
232
|
+
# to one line per 5 attempts so the deploy log isn't flooded.
|
|
233
|
+
if attempts % 5 == 0:
|
|
234
|
+
elapsed = self._VM_READY_TIMEOUT - max(0.0, deadline - time.monotonic())
|
|
235
|
+
logger.info(
|
|
236
|
+
f" Still waiting for VM /exec... ({elapsed:.0f}s elapsed, "
|
|
237
|
+
f"{attempts} attempts)"
|
|
238
|
+
)
|
|
239
|
+
await asyncio.sleep(self._VM_READY_POLL_INTERVAL)
|
|
240
|
+
raise RuntimeError(
|
|
241
|
+
f"VM {self.sandbox_id} /exec not reachable after "
|
|
242
|
+
f"{self._VM_READY_TIMEOUT}s wall-clock ({attempts} attempts; "
|
|
243
|
+
f"last error: {type(last_err).__name__}: {last_err}) — "
|
|
244
|
+
f"platform reports Running but /exec proxy not routing to the VM"
|
|
245
|
+
)
|
|
246
|
+
|
|
247
|
+
async def load_docker_images(self, artifacts: list) -> None:
|
|
248
|
+
"""Load Docker images from DockerImageArtifacts into the sandbox in parallel."""
|
|
249
|
+
if not artifacts:
|
|
250
|
+
return
|
|
251
|
+
await self._load_docker_images(artifacts, await self._signed_image_urls(artifacts))
|
|
252
|
+
|
|
253
|
+
@staticmethod
|
|
254
|
+
async def _signed_image_urls(artifacts: list) -> list[str | None]:
|
|
255
|
+
"""Each image tarball's signed URL, or None where the store cannot sign one. Signed
|
|
256
|
+
concurrently and off the event loop, since a remote signer is a network round trip."""
|
|
257
|
+
logger.info(f"Loading {len(artifacts)} Docker image(s) into the sandbox...")
|
|
258
|
+
object_store = get_config().get_object_store()
|
|
259
|
+
slots = _sign_slots.setdefault(asyncio.get_running_loop(), asyncio.Semaphore(_CONCURRENT_SIGNS))
|
|
260
|
+
failed = False
|
|
261
|
+
|
|
262
|
+
async def sign(artifact) -> str | None:
|
|
263
|
+
nonlocal failed
|
|
264
|
+
async with slots:
|
|
265
|
+
if failed:
|
|
266
|
+
return None
|
|
267
|
+
try:
|
|
268
|
+
return await asyncio.to_thread(object_store.signed_get_url, artifact.tar_gz_object_url)
|
|
269
|
+
except BaseException:
|
|
270
|
+
failed = True
|
|
271
|
+
raise
|
|
272
|
+
|
|
273
|
+
return list(await asyncio.gather(*(sign(artifact) for artifact in artifacts)))
|
|
274
|
+
|
|
275
|
+
async def _load_docker_images(self, artifacts: list, signed_urls: list[str | None]) -> None:
|
|
276
|
+
load_commands = []
|
|
277
|
+
for idx, (artifact, signed) in enumerate(zip(artifacts, signed_urls, strict=True)):
|
|
278
|
+
tmp_tar = f"/tmp/_docker_image_{self.sandbox_id}_{idx}.tar.gz"
|
|
279
|
+
if signed is not None:
|
|
280
|
+
# Download to a file first (retry-safe with -o); a `curl | ... docker load`
|
|
281
|
+
# pipe can't be retried without corrupting the stream (curl won't rewind).
|
|
282
|
+
load_commands.append(
|
|
283
|
+
f'(curl -fsSL {CURL_RETRY_FLAGS} "{signed}" -o {shlex.quote(tmp_tar)} '
|
|
284
|
+
f"&& gunzip -c {shlex.quote(tmp_tar)} | docker load && rm -f {shlex.quote(tmp_tar)})"
|
|
285
|
+
)
|
|
286
|
+
else:
|
|
287
|
+
await self._download_object_to_vm(artifact.tar_gz_object_url, tmp_tar)
|
|
288
|
+
load_commands.append(
|
|
289
|
+
f"(gunzip -c {shlex.quote(tmp_tar)} | docker load && rm -f {shlex.quote(tmp_tar)})"
|
|
290
|
+
)
|
|
291
|
+
logger.info(f" Queued: {artifact.image_name}")
|
|
292
|
+
await self.exec_script(" & ".join(load_commands) + " & wait", max_retries=2)
|
|
293
|
+
|
|
294
|
+
logger.info("Verifying Docker images...")
|
|
295
|
+
exit_code, stdout, stderr = await self.exec_with_output("sudo", "docker", "images")
|
|
296
|
+
if exit_code != 0:
|
|
297
|
+
raise RuntimeError(f"docker images failed: {stderr}")
|
|
298
|
+
for artifact in artifacts:
|
|
299
|
+
base_name = artifact.image_name.split(":")[0]
|
|
300
|
+
if base_name not in stdout:
|
|
301
|
+
raise RuntimeError(f"{artifact.image_name} image not found. stdout: {stdout}")
|
|
302
|
+
logger.info(" All images loaded successfully")
|
|
303
|
+
|
|
304
|
+
async def load_s3_file(self, s3_url: str, destination_path: str) -> None:
|
|
305
|
+
"""Download an object from the object store into the sandbox."""
|
|
306
|
+
await self._download_object_to_vm(s3_url, destination_path)
|
|
307
|
+
|
|
308
|
+
async def _download_object_to_vm(self, object_url: str, vm_path: str) -> None:
|
|
309
|
+
"""Place object_url onto the VM host at vm_path, backend-agnostically."""
|
|
310
|
+
object_store = get_config().get_object_store()
|
|
311
|
+
signed = await asyncio.to_thread(object_store.signed_get_url, object_url)
|
|
312
|
+
if signed is not None:
|
|
313
|
+
await self.exec_script(f"curl -fsSL {CURL_RETRY_FLAGS} {shlex.quote(signed)} -o {shlex.quote(vm_path)}")
|
|
314
|
+
else:
|
|
315
|
+
await self._write_unsigned_object(object_store, object_url, vm_path)
|
|
316
|
+
|
|
317
|
+
async def _write_unsigned_object(self, object_store: ObjectStore, object_url: str, vm_path: str) -> None:
|
|
318
|
+
"""Place an object the store cannot sign a URL for: its bytes, streamed over exec."""
|
|
319
|
+
await self._write_bytes_to_vm_path(await asyncio.to_thread(object_store.get, object_url), vm_path)
|
|
320
|
+
|
|
321
|
+
async def _remove_vm_temp_file(self, *vm_paths: str) -> None:
|
|
322
|
+
try:
|
|
323
|
+
await self.exec_script(f"rm -f {' '.join(shlex.quote(p) for p in vm_paths)}")
|
|
324
|
+
except Exception as e:
|
|
325
|
+
logger.warning(f"Best-effort cleanup of {', '.join(vm_paths)} failed (ignored): {e}")
|
|
326
|
+
|
|
327
|
+
async def _copy_into_container(self, vm_path: str, destination_path: str) -> None:
|
|
328
|
+
parent = os.path.dirname(destination_path)
|
|
329
|
+
if parent:
|
|
330
|
+
await self.exec_script(f"docker exec -u 0 {shlex.quote(self.container_name)} mkdir -p {shlex.quote(parent)}")
|
|
331
|
+
await self.exec_script(f"docker cp {shlex.quote(vm_path)} {self.container_name}:{shlex.quote(destination_path)}")
|
|
332
|
+
|
|
333
|
+
@staticmethod
|
|
334
|
+
def _staging_path(kind: str, destination_path: str) -> str:
|
|
335
|
+
"""Where one write is staged on the VM host: unique per call, since sandboxes can share a
|
|
336
|
+
host's /tmp, as local ones do."""
|
|
337
|
+
return f"/tmp/_{kind}_{uuid.uuid4().hex[:12]}_{destination_path.replace('/', '_').lstrip('_')}"
|
|
338
|
+
|
|
339
|
+
async def write_file_from_s3(self, s3_url: str, destination_path: str) -> None:
|
|
340
|
+
vm_path = self._staging_path("s3", destination_path)
|
|
341
|
+
try:
|
|
342
|
+
await self.load_s3_file(s3_url, vm_path)
|
|
343
|
+
await self._copy_into_container(vm_path, destination_path)
|
|
344
|
+
finally:
|
|
345
|
+
await self._remove_vm_temp_file(vm_path)
|
|
346
|
+
|
|
347
|
+
async def write_file_from_url(self, url: str, destination_path: str) -> None:
|
|
348
|
+
vm_path = self._staging_path("url", destination_path)
|
|
349
|
+
try:
|
|
350
|
+
await self.exec_script(f"curl -fsSL {CURL_RETRY_FLAGS} {shlex.quote(url)} -o {shlex.quote(vm_path)}")
|
|
351
|
+
await self._copy_into_container(vm_path, destination_path)
|
|
352
|
+
finally:
|
|
353
|
+
await self._remove_vm_temp_file(vm_path)
|
|
354
|
+
|
|
355
|
+
# One exec_script is a single `bash -c <script>` arg, capped by Linux MAX_ARG_STRLEN
|
|
356
|
+
# (128 KiB); 96 KiB leaves room for the printf wrapper.
|
|
357
|
+
_WFT_CHUNK_BYTES = 96 * 1024
|
|
358
|
+
|
|
359
|
+
async def _write_bytes_to_vm_path(self, data: bytes, vm_path: str) -> None:
|
|
360
|
+
"""Stream bytes from agent-env onto the VM host at vm_path (base64 over exec)."""
|
|
361
|
+
import base64
|
|
362
|
+
|
|
363
|
+
encoded = base64.b64encode(data).decode()
|
|
364
|
+
if len(encoded) <= self._WFT_CHUNK_BYTES:
|
|
365
|
+
await self.exec_script(f"base64 -d <<'ENDB64' > {shlex.quote(vm_path)}\n{encoded}\nENDB64")
|
|
366
|
+
return
|
|
367
|
+
# Too big for one heredoc arg: append the (shell-safe) base64 in bounded chunks.
|
|
368
|
+
vm_b64 = f"{vm_path}.b64"
|
|
369
|
+
await self.exec_script(f": > {shlex.quote(vm_b64)}")
|
|
370
|
+
for i in range(0, len(encoded), self._WFT_CHUNK_BYTES):
|
|
371
|
+
await self.exec_script(f"printf '%s' {shlex.quote(encoded[i:i + self._WFT_CHUNK_BYTES])} >> {shlex.quote(vm_b64)}")
|
|
372
|
+
await self.exec_script(f"base64 -d {shlex.quote(vm_b64)} > {shlex.quote(vm_path)} && rm -f {shlex.quote(vm_b64)}")
|
|
373
|
+
|
|
374
|
+
async def write_host_file(self, data: bytes, vm_path: str) -> None:
|
|
375
|
+
"""Write bytes to vm_path on the VM host itself, not into the agent container."""
|
|
376
|
+
parent = os.path.dirname(vm_path)
|
|
377
|
+
if parent:
|
|
378
|
+
await self.exec_script(f"mkdir -p {shlex.quote(parent)}")
|
|
379
|
+
await self._write_bytes_to_vm_path(data, vm_path)
|
|
380
|
+
|
|
381
|
+
async def write_file_from_text(self, content: str, destination_path: str) -> None:
|
|
382
|
+
vm_path = self._staging_path("wft", destination_path)
|
|
383
|
+
try:
|
|
384
|
+
await self._write_bytes_to_vm_path(content.encode(), vm_path)
|
|
385
|
+
await self._copy_into_container(vm_path, destination_path)
|
|
386
|
+
finally:
|
|
387
|
+
await self._remove_vm_temp_file(vm_path, f"{vm_path}.b64")
|