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,408 @@
|
|
|
1
|
+
"""Local sandbox for running agent-env environments on the local machine.
|
|
2
|
+
|
|
3
|
+
A drop-in replacement for a remote VM sandbox that executes all commands locally
|
|
4
|
+
via subprocess instead of on a remote VM.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import asyncio
|
|
10
|
+
import contextlib
|
|
11
|
+
import glob
|
|
12
|
+
import logging
|
|
13
|
+
import os
|
|
14
|
+
import platform
|
|
15
|
+
import re
|
|
16
|
+
import shlex
|
|
17
|
+
import shutil
|
|
18
|
+
import signal
|
|
19
|
+
import socket
|
|
20
|
+
import subprocess
|
|
21
|
+
import tempfile
|
|
22
|
+
from pathlib import Path
|
|
23
|
+
from typing import TYPE_CHECKING, Any, Optional
|
|
24
|
+
from uuid import uuid4
|
|
25
|
+
|
|
26
|
+
from agent_env.attribution import Attribution
|
|
27
|
+
from agent_env.providers.sandbox_providers.sandbox import NetworkPolicy, VmSandbox
|
|
28
|
+
from agent_env.providers.sandbox_providers.sandbox_provider import (
|
|
29
|
+
SANDBOX_MODE_CONTAINER,
|
|
30
|
+
SANDBOX_MODE_VM,
|
|
31
|
+
SandboxProvider,
|
|
32
|
+
refuse_unenforceable_policy,
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
if TYPE_CHECKING:
|
|
36
|
+
from agent_env.store.object_store import ObjectStore
|
|
37
|
+
|
|
38
|
+
logger = logging.getLogger(__name__)
|
|
39
|
+
|
|
40
|
+
_APP_PATH_PATTERN = re.compile(r"(?<![A-Za-z0-9_./~})$-])/app(?=(?:/|:|[\s'\";)&|]|$))")
|
|
41
|
+
_IN_CONTAINER_SCRIPT = re.compile(r"\s*(?:sudo\s+)?docker\s+exec\b")
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _runs_in_container(cmd: list[str]) -> bool:
|
|
45
|
+
"""A ``docker exec``, as arguments or as a ``bash -c`` script: its /app is the container's."""
|
|
46
|
+
return cmd[:2] == ["docker", "exec"] or (
|
|
47
|
+
cmd[:2] == ["bash", "-c"] and len(cmd) > 2 and bool(_IN_CONTAINER_SCRIPT.match(cmd[2]))
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
_REAP_SECONDS = 5
|
|
52
|
+
|
|
53
|
+
# Marker dropped in the work dir when this sandbox runs a container, so a later get_sandbox()
|
|
54
|
+
# (post-run teardown reconstructs the sandbox from disk) can restore container mode and clean up.
|
|
55
|
+
_CONTAINER_MODE_MARKER = ".agent-container-mode"
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _local_sandbox_root_path() -> Path:
|
|
59
|
+
"""Base dir for local-sandbox work dirs (pure — no side effects, safe for read-only lookups).
|
|
60
|
+
|
|
61
|
+
It MUST live on a path Docker Desktop shares with its VM: the gateway compose bind-mounts files
|
|
62
|
+
from here (e.g. init-schemas.sql), and on macOS the default temp dirs ($TMPDIR under /var/folders,
|
|
63
|
+
and /tmp) are NOT shared — a bind mount from there silently becomes an empty directory (Postgres
|
|
64
|
+
then reads a dir as SQL and the init crashes). The user's home (/Users/…) is shared by default.
|
|
65
|
+
Override with AGENT_ENV_LOCAL_SANDBOX_DIR."""
|
|
66
|
+
base = os.environ.get("AGENT_ENV_LOCAL_SANDBOX_DIR")
|
|
67
|
+
return Path(base) if base else Path.home() / ".agent-env-sandboxes"
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _local_sandbox_root() -> Path:
|
|
71
|
+
"""The shared root, created if missing — for placing a *new* work dir. Lookups must not use this
|
|
72
|
+
(its mkdir can raise); scan via _local_sandbox_root_path instead so an uncreatable new root never
|
|
73
|
+
blocks reconstructing an existing sandbox."""
|
|
74
|
+
root = _local_sandbox_root_path()
|
|
75
|
+
root.mkdir(parents=True, exist_ok=True)
|
|
76
|
+
return root
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _free_host_port() -> int:
|
|
80
|
+
"""A currently-free host port.
|
|
81
|
+
|
|
82
|
+
Binds all interfaces, as docker does when publishing a port: a port free on loopback
|
|
83
|
+
alone can still be taken on another interface.
|
|
84
|
+
|
|
85
|
+
Racy: the port is released before docker binds it. The window is small and a loser
|
|
86
|
+
fails loudly at bind time.
|
|
87
|
+
"""
|
|
88
|
+
with socket.socket() as s:
|
|
89
|
+
s.bind(("", 0))
|
|
90
|
+
return int(s.getsockname()[1])
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
class LocalSandbox(VmSandbox):
|
|
94
|
+
"""Sandbox implementation that runs everything on the local machine.
|
|
95
|
+
|
|
96
|
+
Implements the same VmSandbox interface as the remote providers but executes commands
|
|
97
|
+
locally via asyncio.create_subprocess_exec. This gives 1:1 behavior
|
|
98
|
+
parity with prod for docker compose generation, data loading, etc.
|
|
99
|
+
|
|
100
|
+
The /app path used by EnvironmentGatewayProvider is redirected to a local temp
|
|
101
|
+
directory since /app is not writable on macOS.
|
|
102
|
+
"""
|
|
103
|
+
|
|
104
|
+
type = "local"
|
|
105
|
+
|
|
106
|
+
def __init__(self, exposed_ports: list[int] | None = None, work_dir: Path | None = None, sandbox_id: str | None = None,
|
|
107
|
+
port_map: dict[int, int] | None = None):
|
|
108
|
+
self.sandbox_id = sandbox_id or f"local-{uuid4().hex[:8]}"
|
|
109
|
+
# Container port -> host port. Deployments share one host, so the reserved ports
|
|
110
|
+
# can only be published once; the provider supplies a map to spread them. Callers
|
|
111
|
+
# that just want a handle pass `exposed_ports` and get identity.
|
|
112
|
+
self._port_map = dict(port_map) if port_map is not None else {
|
|
113
|
+
port: port for port in (exposed_ports or [])
|
|
114
|
+
}
|
|
115
|
+
# Keyed by container port: callers index this with the well-known constants.
|
|
116
|
+
self.tunnel_urls = {
|
|
117
|
+
container: f"http://localhost:{host}" for container, host in self._port_map.items()
|
|
118
|
+
}
|
|
119
|
+
self.vnc_url = None
|
|
120
|
+
self.mode = SANDBOX_MODE_VM
|
|
121
|
+
self._work_dir = work_dir or Path(
|
|
122
|
+
tempfile.mkdtemp(prefix=f"agent-env-{self.sandbox_id}-", dir=_local_sandbox_root())
|
|
123
|
+
)
|
|
124
|
+
|
|
125
|
+
def host_port(self, port: int) -> int:
|
|
126
|
+
"""The allocated host port for a published container port (identity if unmapped)."""
|
|
127
|
+
return self._port_map.get(port, port)
|
|
128
|
+
|
|
129
|
+
@classmethod
|
|
130
|
+
def find_work_dir(cls, sandbox_id: str) -> Path | None:
|
|
131
|
+
"""Find the work directory for a previously created local sandbox.
|
|
132
|
+
|
|
133
|
+
Scans the current shared root first, then the legacy temp-dir root: sandboxes created before
|
|
134
|
+
the work-dir relocation landed under ``tempfile.gettempdir()``, and must still be locatable
|
|
135
|
+
(e.g. for teardown) after an upgrade."""
|
|
136
|
+
seen: set[Path] = set()
|
|
137
|
+
for root in (_local_sandbox_root_path(), Path(tempfile.gettempdir())):
|
|
138
|
+
if root in seen:
|
|
139
|
+
continue
|
|
140
|
+
seen.add(root)
|
|
141
|
+
matches = sorted(glob.glob(f"{root}/agent-env-{glob.escape(sandbox_id)}-*"))
|
|
142
|
+
if matches:
|
|
143
|
+
return Path(matches[-1])
|
|
144
|
+
return None
|
|
145
|
+
|
|
146
|
+
@property
|
|
147
|
+
def container_name(self) -> str:
|
|
148
|
+
"""Per-sandbox agent container name. The local backend packs every agent onto one Docker
|
|
149
|
+
host, so a fixed name (the VmSandbox default) would collide across concurrent deploys and
|
|
150
|
+
make teardown ownership-blind. Deriving it from the sandbox id gives each deploy its own
|
|
151
|
+
container and lets teardown remove only the one this sandbox created."""
|
|
152
|
+
return f"agent-{self.sandbox_id}"
|
|
153
|
+
|
|
154
|
+
@property
|
|
155
|
+
def work_dir(self) -> Path:
|
|
156
|
+
return self._work_dir
|
|
157
|
+
|
|
158
|
+
def _rewrite_app_arg(self, arg: str) -> str:
|
|
159
|
+
if arg == "/app" or arg.startswith(("/app/", "/app:")):
|
|
160
|
+
return str(self._work_dir) + arg[4:]
|
|
161
|
+
return arg
|
|
162
|
+
|
|
163
|
+
def _rewrite_app_script(self, script: str) -> str:
|
|
164
|
+
return _APP_PATH_PATTERN.sub(lambda _: str(self._work_dir), script)
|
|
165
|
+
|
|
166
|
+
async def terminate(self) -> None:
|
|
167
|
+
"""Tear down whatever this sandbox is running.
|
|
168
|
+
|
|
169
|
+
A container-mode sandbox (the A2A agent) owns the ``self.container_name`` container that
|
|
170
|
+
create_container started — remove it. A VM-mode sandbox (env/gateway) runs a docker compose
|
|
171
|
+
stack out of its work dir — ``docker compose down`` it — and may carry an agent placed on it,
|
|
172
|
+
which runs as the same ``self.container_name`` container. Each path only touches resources
|
|
173
|
+
this sandbox created: the container name is per-sandbox (LocalSandbox.container_name), so a
|
|
174
|
+
stale marker from an old run can only target that run's own (already-gone) container, never a
|
|
175
|
+
newer one; and the compose-down is scoped to this sandbox's project via its work dir. Without
|
|
176
|
+
this, local runs leak their containers/compose stacks, which squat host ports and block the
|
|
177
|
+
next deploy. Prod backends override terminate() to tear the whole VM down.
|
|
178
|
+
"""
|
|
179
|
+
await self.exec_script(f"docker rm -f {shlex.quote(self.container_name)} >/dev/null 2>&1 || true")
|
|
180
|
+
if self.mode == SANDBOX_MODE_VM and (self._work_dir / "docker-compose.yml").exists():
|
|
181
|
+
# No `|| true`: `docker compose down` is idempotent (an already-down stack exits 0), so a
|
|
182
|
+
# non-zero exit is a real failure — surface it (exec_script raises, with the compose output)
|
|
183
|
+
# instead of silently leaving the stack running and its host ports held. Callers wrap
|
|
184
|
+
# terminate() in try/except, so a raised teardown failure is caught, not fatal.
|
|
185
|
+
await self.exec_script(
|
|
186
|
+
f"cd {shlex.quote(str(self._work_dir))} && docker compose down -v --remove-orphans"
|
|
187
|
+
)
|
|
188
|
+
|
|
189
|
+
async def exec(self, *command: str) -> Any:
|
|
190
|
+
"""Execute a command locally via subprocess.
|
|
191
|
+
|
|
192
|
+
Strips 'sudo' and points /app at the local work directory, both as a path argument and
|
|
193
|
+
inside the script of a top-level ``bash -c``, unless the command runs in a container.
|
|
194
|
+
Returns an object with .stdout, .stderr streams and .wait() method, matching the
|
|
195
|
+
interface expected by exec_with_output().
|
|
196
|
+
"""
|
|
197
|
+
cmd = [c for c in command if c != "sudo"]
|
|
198
|
+
if not _runs_in_container(cmd):
|
|
199
|
+
is_script = cmd[:2] == ["bash", "-c"]
|
|
200
|
+
cmd = [
|
|
201
|
+
self._rewrite_app_script(c) if is_script and i == 2 else self._rewrite_app_arg(c)
|
|
202
|
+
for i, c in enumerate(cmd)
|
|
203
|
+
]
|
|
204
|
+
logger.debug(f"LocalSandbox exec: {' '.join(cmd)}")
|
|
205
|
+
process = await asyncio.create_subprocess_exec(
|
|
206
|
+
*cmd,
|
|
207
|
+
stdout=asyncio.subprocess.PIPE,
|
|
208
|
+
stderr=asyncio.subprocess.PIPE,
|
|
209
|
+
)
|
|
210
|
+
return process
|
|
211
|
+
|
|
212
|
+
async def exec_with_output(self, *args: str) -> tuple[int, str, str]:
|
|
213
|
+
"""Like the base, except that cancelling it kills the command and every process it started. This host
|
|
214
|
+
is the sandbox's VM, so nothing else would."""
|
|
215
|
+
spawning = asyncio.ensure_future(self.exec(*args))
|
|
216
|
+
try:
|
|
217
|
+
process = await asyncio.shield(spawning)
|
|
218
|
+
except asyncio.CancelledError:
|
|
219
|
+
with contextlib.suppress(Exception):
|
|
220
|
+
await _stop(await spawning)
|
|
221
|
+
raise
|
|
222
|
+
try:
|
|
223
|
+
stdout, stderr = await asyncio.gather(process.stdout.read(), process.stderr.read())
|
|
224
|
+
exit_code = await process.wait()
|
|
225
|
+
except asyncio.CancelledError:
|
|
226
|
+
await _stop(process)
|
|
227
|
+
raise
|
|
228
|
+
return exit_code, stdout.decode(), stderr.decode()
|
|
229
|
+
|
|
230
|
+
async def _write_unsigned_object(self, object_store: ObjectStore, object_url: str, vm_path: str) -> None:
|
|
231
|
+
"""This host is the VM, so the store writes the object in place, with no exec transport."""
|
|
232
|
+
await asyncio.to_thread(object_store.download_to_file, object_url, self._rewrite_app_arg(vm_path))
|
|
233
|
+
|
|
234
|
+
async def setup_vm_for_gateway(self, exposed_ports=None) -> None:
|
|
235
|
+
"""No-op — Docker is already installed locally."""
|
|
236
|
+
logger.info("Local sandbox: skipping VM setup (Docker assumed installed)")
|
|
237
|
+
|
|
238
|
+
async def wait_for_vm(self) -> None:
|
|
239
|
+
"""No-op — local machine is always ready."""
|
|
240
|
+
pass
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
async def _stop(process: asyncio.subprocess.Process) -> None:
|
|
244
|
+
"""SIGKILL ``process`` and every process it started, then reap it, waiting a few seconds at most for one
|
|
245
|
+
that escaped the kill to let go of its output."""
|
|
246
|
+
_kill_tree(process.pid)
|
|
247
|
+
with contextlib.suppress(TimeoutError):
|
|
248
|
+
await asyncio.wait_for(process.wait(), _REAP_SECONDS)
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def _kill_tree(root: int) -> None:
|
|
252
|
+
"""SIGKILL ``root`` and its descendants, as one ``ps`` lists them."""
|
|
253
|
+
try:
|
|
254
|
+
listing = subprocess.run(["ps", "-A", "-o", "pid=", "-o", "ppid="], capture_output=True, text=True,
|
|
255
|
+
timeout=_REAP_SECONDS).stdout
|
|
256
|
+
except (OSError, subprocess.SubprocessError):
|
|
257
|
+
listing = ""
|
|
258
|
+
children: dict[int, list[int]] = {}
|
|
259
|
+
for line in listing.splitlines():
|
|
260
|
+
pid, _, parent = line.strip().partition(" ")
|
|
261
|
+
if pid.isdigit() and parent.strip().isdigit():
|
|
262
|
+
children.setdefault(int(parent), []).append(int(pid))
|
|
263
|
+
tree, pending = [], [root]
|
|
264
|
+
while pending:
|
|
265
|
+
tree.append(pid := pending.pop())
|
|
266
|
+
pending.extend(children.get(pid, ()))
|
|
267
|
+
for pid in tree:
|
|
268
|
+
with contextlib.suppress(ProcessLookupError):
|
|
269
|
+
os.kill(pid, signal.SIGKILL)
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def remove_local_work_dir(sandbox_id: str) -> Path | None:
|
|
273
|
+
"""Delete a local sandbox's work folder, and return it, when it lies directly under the sandbox root and
|
|
274
|
+
isn't a symlink; anything else, a legacy folder under the temp dir included, is left alone. Raises OSError
|
|
275
|
+
when the folder can't be removed."""
|
|
276
|
+
work_dir = LocalSandbox.find_work_dir(sandbox_id)
|
|
277
|
+
root = _local_sandbox_root_path().resolve()
|
|
278
|
+
if work_dir is None or work_dir.is_symlink() or work_dir.parent.resolve() != root:
|
|
279
|
+
return None
|
|
280
|
+
shutil.rmtree(work_dir)
|
|
281
|
+
return work_dir
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
class LocalSandboxProvider(SandboxProvider):
|
|
285
|
+
"""SandboxProvider that runs VM-style gateway deployments on local Docker."""
|
|
286
|
+
|
|
287
|
+
# Only Linux lacks a native host.docker.internal; on Rancher Desktop this mapping would point it at the VM.
|
|
288
|
+
EXTRA_CONTAINER_RUN_ARGS = "--add-host host.docker.internal:host-gateway" if platform.system() == "Linux" else ""
|
|
289
|
+
|
|
290
|
+
async def create_vm(
|
|
291
|
+
self,
|
|
292
|
+
*,
|
|
293
|
+
image: Optional[str] = None,
|
|
294
|
+
boot_mode: Optional[str] = None,
|
|
295
|
+
cpu: float = 1.0,
|
|
296
|
+
memory: int = 8192,
|
|
297
|
+
disk_size_gb: float = 10,
|
|
298
|
+
timeout: int = 3600 * 2,
|
|
299
|
+
exposed_ports: Optional[list[int]] = None,
|
|
300
|
+
setup_for_gateway: bool = True,
|
|
301
|
+
attribution: Optional[Attribution] = None,
|
|
302
|
+
priority: Optional[int] = None,
|
|
303
|
+
network_policy: Optional[NetworkPolicy] = None,
|
|
304
|
+
) -> LocalSandbox:
|
|
305
|
+
refuse_unenforceable_policy(self, network_policy)
|
|
306
|
+
# Allocated here rather than in the sandbox constructor: probing for a free port
|
|
307
|
+
# is I/O, and callers that only need a handle must not pay for it.
|
|
308
|
+
sandbox = LocalSandbox(
|
|
309
|
+
port_map={port: _free_host_port() for port in (exposed_ports or [])},
|
|
310
|
+
)
|
|
311
|
+
sandbox.network_policy = self.effective_network_policy(network_policy)
|
|
312
|
+
return sandbox
|
|
313
|
+
|
|
314
|
+
async def create_container(
|
|
315
|
+
self,
|
|
316
|
+
*,
|
|
317
|
+
image_name: str,
|
|
318
|
+
port: int,
|
|
319
|
+
env: dict[str, str],
|
|
320
|
+
cpu: float = 1.0,
|
|
321
|
+
memory: int = 8192,
|
|
322
|
+
disk_size_gb: float = 10,
|
|
323
|
+
timeout: int = 3600 * 2,
|
|
324
|
+
attribution: Optional[Attribution] = None,
|
|
325
|
+
priority: Optional[int] = None,
|
|
326
|
+
network_policy: Optional[NetworkPolicy] = None,
|
|
327
|
+
) -> LocalSandbox:
|
|
328
|
+
sandbox = await super().create_container(
|
|
329
|
+
image_name=image_name,
|
|
330
|
+
port=port,
|
|
331
|
+
env=env,
|
|
332
|
+
cpu=cpu,
|
|
333
|
+
memory=memory,
|
|
334
|
+
disk_size_gb=disk_size_gb,
|
|
335
|
+
timeout=timeout,
|
|
336
|
+
attribution=attribution,
|
|
337
|
+
priority=priority, network_policy=network_policy,
|
|
338
|
+
)
|
|
339
|
+
# The marker is how a later get_sandbox() (post-run teardown rebuilds the sandbox from disk)
|
|
340
|
+
# learns this is a container and removes it. If we can't persist it, that reconstructed
|
|
341
|
+
# teardown would take the VM path and leak the running container — so we can't just swallow
|
|
342
|
+
# the error. Tear the container down now (the live handle is still container-mode) and fail
|
|
343
|
+
# loudly, rather than return a container nothing can reliably reclaim.
|
|
344
|
+
if sandbox.mode == SANDBOX_MODE_CONTAINER:
|
|
345
|
+
try:
|
|
346
|
+
(sandbox.work_dir / _CONTAINER_MODE_MARKER).write_text(sandbox.container_name)
|
|
347
|
+
except OSError as e:
|
|
348
|
+
# Can't persist the marker → a reconstructed teardown couldn't find/remove this
|
|
349
|
+
# container. Remove it now, but do NOT go through terminate() (its `docker rm … || true`
|
|
350
|
+
# would mask a failed removal): run the removal so a genuinely stuck container is
|
|
351
|
+
# escalated (ERROR) rather than silently leaked with its host port held.
|
|
352
|
+
logger.warning(
|
|
353
|
+
"Could not persist container-mode marker for %s: %s; removing the container",
|
|
354
|
+
sandbox.sandbox_id, e,
|
|
355
|
+
)
|
|
356
|
+
try:
|
|
357
|
+
await sandbox.exec_script(f"docker rm -f {shlex.quote(sandbox.container_name)}")
|
|
358
|
+
except Exception:
|
|
359
|
+
logger.error(
|
|
360
|
+
"Container %s could not be removed after marker-persist failure; it may still "
|
|
361
|
+
"be running and holding its host port — remove it manually.",
|
|
362
|
+
sandbox.container_name, exc_info=True,
|
|
363
|
+
)
|
|
364
|
+
raise
|
|
365
|
+
return sandbox
|
|
366
|
+
|
|
367
|
+
async def create_sandbox(
|
|
368
|
+
self,
|
|
369
|
+
*,
|
|
370
|
+
image_name: str,
|
|
371
|
+
port: int,
|
|
372
|
+
env: dict[str, str],
|
|
373
|
+
cpu: float = 1.0,
|
|
374
|
+
memory: int = 8192,
|
|
375
|
+
disk_size_gb: float = 10,
|
|
376
|
+
timeout: int = 3600 * 2,
|
|
377
|
+
attribution: Optional[Attribution] = None,
|
|
378
|
+
priority: Optional[int] = None,
|
|
379
|
+
network_policy: Optional[NetworkPolicy] = None,
|
|
380
|
+
) -> LocalSandbox:
|
|
381
|
+
return await self.create_container(
|
|
382
|
+
image_name=image_name, port=port, env=env, cpu=cpu, memory=memory, disk_size_gb=disk_size_gb,
|
|
383
|
+
timeout=timeout, attribution=attribution, priority=priority, network_policy=network_policy,
|
|
384
|
+
)
|
|
385
|
+
|
|
386
|
+
async def get_sandbox(self, sandbox_id: str) -> LocalSandbox:
|
|
387
|
+
work_dir = LocalSandbox.find_work_dir(sandbox_id)
|
|
388
|
+
if work_dir is None:
|
|
389
|
+
raise RuntimeError(f"Local sandbox work directory not found for sandbox_id={sandbox_id!r}")
|
|
390
|
+
sandbox = LocalSandbox(sandbox_id=sandbox_id, work_dir=work_dir)
|
|
391
|
+
if (work_dir / _CONTAINER_MODE_MARKER).exists():
|
|
392
|
+
sandbox.mode = SANDBOX_MODE_CONTAINER
|
|
393
|
+
return sandbox
|
|
394
|
+
|
|
395
|
+
@classmethod
|
|
396
|
+
def shares_network_with(cls, sandbox_type: Optional[str]) -> bool:
|
|
397
|
+
"""Local sandboxes never share a Docker network. The agent runs via ``docker run`` on the
|
|
398
|
+
default bridge; the env/gateway runs in its own compose network. They reach each other only
|
|
399
|
+
through published host ports — so cross-sandbox URLs must be externalized (below), never kept
|
|
400
|
+
as-is. (The base default assumes same-provider ⇒ shared network, which is wrong here.)"""
|
|
401
|
+
return False
|
|
402
|
+
|
|
403
|
+
@classmethod
|
|
404
|
+
def get_external_url(cls, url: str) -> str:
|
|
405
|
+
"""Rewrite a ``localhost`` URL (a published host port) to the form a workload reaches from
|
|
406
|
+
inside a container: ``host.docker.internal``. Docker Desktop and Rancher Desktop (macOS/Windows)
|
|
407
|
+
resolve this themselves; on Linux ``EXTRA_CONTAINER_RUN_ARGS`` maps it via ``--add-host …:host-gateway``."""
|
|
408
|
+
return url.replace("localhost", "host.docker.internal").replace("127.0.0.1", "host.docker.internal")
|