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,390 @@
|
|
|
1
|
+
"""LocalPostgresStateProvider — today's shared per-service Postgres as an EnvStateProvider.
|
|
2
|
+
|
|
3
|
+
The environment provider ( compute layer ) stands up the ``servicedb`` container (from this provider's
|
|
4
|
+
declared ``store_spec``) and hands its address back on the acquire context. ``acquire`` does NOT
|
|
5
|
+
create the container and does NOT load data — it builds the connection URL, persists an
|
|
6
|
+
``EnvStateInstance``, and returns it. ``teardown`` only marks the record retired (sets
|
|
7
|
+
``expires_at_utc`` to now): the container itself is reaped with the sandbox.
|
|
8
|
+
|
|
9
|
+
All the Postgres store knowledge lives here — connection URLs, the schema + changelog init
|
|
10
|
+
SQL, and the container healthcheck. ``ServiceDBEnv`` keeps only the docker image artifacts
|
|
11
|
+
(its ``ServiceDBConfig``); this provider owns how the store is set up and run.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import logging
|
|
17
|
+
from dataclasses import dataclass
|
|
18
|
+
from typing import Optional, TYPE_CHECKING
|
|
19
|
+
|
|
20
|
+
from agent_env.config import get_config
|
|
21
|
+
from agent_env.env.envs.service_db import (
|
|
22
|
+
DATABASE_SERVICE_NAME,
|
|
23
|
+
DB_MCP_CONTAINER_PORT,
|
|
24
|
+
DB_MCP_PORT,
|
|
25
|
+
DB_MCP_SERVICE_NAME,
|
|
26
|
+
DB_NAME,
|
|
27
|
+
DB_PASSWORD,
|
|
28
|
+
DB_USER,
|
|
29
|
+
DB_WEB_PORT,
|
|
30
|
+
PGWEB_SERVICE_NAME,
|
|
31
|
+
SERVICE_DB_PORT,
|
|
32
|
+
)
|
|
33
|
+
from agent_env.providers.env_state.env_state_provider import (
|
|
34
|
+
DatabaseStateProvider,
|
|
35
|
+
DEFAULT_STATE_TTL_SECONDS,
|
|
36
|
+
EnvStateInstance,
|
|
37
|
+
StateContext,
|
|
38
|
+
LOCAL_POSTGRES_STATE_TYPE,
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
if TYPE_CHECKING:
|
|
42
|
+
from collections.abc import Awaitable, Callable
|
|
43
|
+
|
|
44
|
+
from agent_env.artifact import DockerImageArtifact
|
|
45
|
+
from agent_env.env.envs.service_db import ServiceDBConfig, ServiceDBEnv
|
|
46
|
+
|
|
47
|
+
logger = logging.getLogger(__name__)
|
|
48
|
+
|
|
49
|
+
# Where the schema-init SQL is mounted inside the Postgres container — the image's
|
|
50
|
+
# entrypoint runs everything here on first boot. A Postgres-image convention, so it's
|
|
51
|
+
# owned by this backend rather than hardcoded in the compute layer.
|
|
52
|
+
INIT_SCRIPT_MOUNT_PATH = "/docker-entrypoint-initdb.d/init-schemas.sql"
|
|
53
|
+
|
|
54
|
+
_STOCK_POSTGRES_IMAGE = "public.ecr.aws/docker/library/postgres:16-alpine"
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
@dataclass
|
|
58
|
+
class ContainerSpec:
|
|
59
|
+
"""Declarative spec for a store/sidecar container the compute layer provisions (Modal
|
|
60
|
+
path). The gateway's ``create_container`` loop consumes these and adds its own sandbox
|
|
61
|
+
knobs (i6pn, attribution, priority)
|
|
62
|
+
"""
|
|
63
|
+
|
|
64
|
+
name: str
|
|
65
|
+
image: str
|
|
66
|
+
env: dict[str, str]
|
|
67
|
+
port: int
|
|
68
|
+
command: list[str] | None = None
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
@dataclass
|
|
72
|
+
class LocalPostgresStoreSpec:
|
|
73
|
+
"""The servicedb container the compute layer stands up for the local-Postgres backend."""
|
|
74
|
+
|
|
75
|
+
env: dict[str, str]
|
|
76
|
+
healthcheck: dict
|
|
77
|
+
init_sql: str
|
|
78
|
+
port: int
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
@dataclass
|
|
82
|
+
class LocalPostgresStateContext(StateContext):
|
|
83
|
+
"""``acquire`` input for the local-Postgres backend.
|
|
84
|
+
|
|
85
|
+
environment_names: the services this shared store must host, one schema each.
|
|
86
|
+
host: the servicedb address, supplied by the compute layer after it stands the
|
|
87
|
+
container up — e.g. ``"servicedb"`` (compose) or ``"[fdaa::…]"`` (i6pn container).
|
|
88
|
+
ttl_seconds: the deploy TTL, used to stamp the record's ``expires_at_utc``.
|
|
89
|
+
"""
|
|
90
|
+
|
|
91
|
+
environment_names: list[str]
|
|
92
|
+
host: str
|
|
93
|
+
ttl_seconds: int = DEFAULT_STATE_TTL_SECONDS
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
class LocalPostgresStateProvider(DatabaseStateProvider):
|
|
97
|
+
type = LOCAL_POSTGRES_STATE_TYPE
|
|
98
|
+
|
|
99
|
+
# The co-deployed servicedb is snapshottable as a container image
|
|
100
|
+
supports_restore_from_snapshot = True
|
|
101
|
+
|
|
102
|
+
def __init__(self, service_db_config: "ServiceDBConfig | None" = None):
|
|
103
|
+
"""``service_db_config`` (the servicedb image config) is static per provider, so it's held
|
|
104
|
+
here rather than threaded through each render call. Pass it to inject baked image tags
|
|
105
|
+
(export/snapshot); ``None`` resolves the deploy's default ServiceDBEnv lazily."""
|
|
106
|
+
super().__init__()
|
|
107
|
+
self._service_db_config = service_db_config
|
|
108
|
+
self._service_db_env: "ServiceDBEnv | None" = None
|
|
109
|
+
|
|
110
|
+
def deploy_state_context(
|
|
111
|
+
self, *, ttl_seconds: int = DEFAULT_STATE_TTL_SECONDS, name_hint: str | None = None
|
|
112
|
+
) -> None:
|
|
113
|
+
"""None: its context needs the compose host, so the gateway acquires this store, not the deploy."""
|
|
114
|
+
return None
|
|
115
|
+
|
|
116
|
+
def _default_service_db_env(self) -> "ServiceDBEnv":
|
|
117
|
+
"""The deploy's default ServiceDBEnv, resolved once + cached. Source of both the image
|
|
118
|
+
config (names, for compose) and the images to load (artifacts, for the VM). Also caches
|
|
119
|
+
``service_db_config`` off the same resolve unless one was injected at construction."""
|
|
120
|
+
if self._service_db_env is None:
|
|
121
|
+
from agent_env.env.env import Env
|
|
122
|
+
from agent_env.config import get_config
|
|
123
|
+
|
|
124
|
+
self._service_db_env = Env.get(get_config().default_service_db_env_id)
|
|
125
|
+
if self._service_db_config is None:
|
|
126
|
+
self._service_db_config = self._service_db_env.to_config()
|
|
127
|
+
return self._service_db_env
|
|
128
|
+
|
|
129
|
+
@property
|
|
130
|
+
def service_db_config(self) -> "ServiceDBConfig":
|
|
131
|
+
"""The injected config, else the deploy's default ServiceDBEnv config (resolved once)."""
|
|
132
|
+
if self._service_db_config is None:
|
|
133
|
+
self._default_service_db_env() # resolves the env and caches _service_db_config
|
|
134
|
+
return self._service_db_config
|
|
135
|
+
|
|
136
|
+
def store_images_to_load(self) -> list["DockerImageArtifact"]:
|
|
137
|
+
"""The servicedb image set (servicedb + pgweb + db-mcp) the VM preloads via S3 tar — the
|
|
138
|
+
artifacts (with ``tar_gz_s3_url``), which the image-name config can't provide. Reuses the
|
|
139
|
+
cached default env, so no extra ``Env.get`` beyond ``service_db_config``'s."""
|
|
140
|
+
env = self._default_service_db_env()
|
|
141
|
+
return [
|
|
142
|
+
env.db_docker_image_artifact,
|
|
143
|
+
env.db_web_docker_image_artifact,
|
|
144
|
+
env.db_mcp_docker_image_artifact,
|
|
145
|
+
]
|
|
146
|
+
|
|
147
|
+
@classmethod
|
|
148
|
+
def default_instance(cls) -> EnvStateInstance:
|
|
149
|
+
"""Static (unpersisted) instance for the co-deployed local store, used when reattaching an
|
|
150
|
+
env that has no recorded state instance (ie. envs deployed before EnvStateInstance was created, or the
|
|
151
|
+
EnvStateInstance is expired). """
|
|
152
|
+
return EnvStateInstance(
|
|
153
|
+
state_type=cls.type,
|
|
154
|
+
metadata={"host": DATABASE_SERVICE_NAME},
|
|
155
|
+
_db_url_base=cls._pg_url(DATABASE_SERVICE_NAME), # static compose-network base
|
|
156
|
+
)
|
|
157
|
+
|
|
158
|
+
def store_spec(self, environment_names: list[str]) -> LocalPostgresStoreSpec:
|
|
159
|
+
return LocalPostgresStoreSpec(
|
|
160
|
+
env={
|
|
161
|
+
"POSTGRES_USER": DB_USER,
|
|
162
|
+
"POSTGRES_PASSWORD": DB_PASSWORD,
|
|
163
|
+
"POSTGRES_DB": DB_NAME,
|
|
164
|
+
},
|
|
165
|
+
healthcheck={
|
|
166
|
+
"test": ["CMD-SHELL", f"pg_isready -U {DB_USER}"],
|
|
167
|
+
"interval": "5s",
|
|
168
|
+
"timeout": "5s",
|
|
169
|
+
"retries": 5,
|
|
170
|
+
},
|
|
171
|
+
init_sql=self.get_init_script(environment_names),
|
|
172
|
+
port=SERVICE_DB_PORT,
|
|
173
|
+
)
|
|
174
|
+
|
|
175
|
+
async def acquire(self, ctx: StateContext) -> EnvStateInstance:
|
|
176
|
+
if not isinstance(ctx, LocalPostgresStateContext):
|
|
177
|
+
raise TypeError(
|
|
178
|
+
"LocalPostgresStateProvider.acquire requires a LocalPostgresStateContext, "
|
|
179
|
+
f"got {type(ctx).__name__}."
|
|
180
|
+
)
|
|
181
|
+
if not ctx.host:
|
|
182
|
+
raise ValueError(
|
|
183
|
+
"LocalPostgresStateProvider.acquire requires ctx.host — the servicedb "
|
|
184
|
+
"address, supplied by the compute layer after standup."
|
|
185
|
+
)
|
|
186
|
+
from agent_env.providers.env_state.store import register_env_state_instance
|
|
187
|
+
|
|
188
|
+
db_url_base = self._pg_url(ctx.host) # base URL, no search_path
|
|
189
|
+
instance = EnvStateInstance(
|
|
190
|
+
state_type=self.type,
|
|
191
|
+
metadata={"host": ctx.host},
|
|
192
|
+
_db_url_base=db_url_base,
|
|
193
|
+
)
|
|
194
|
+
return register_env_state_instance(instance, ctx.ttl_seconds)
|
|
195
|
+
|
|
196
|
+
async def _teardown(self, instance: EnvStateInstance) -> None:
|
|
197
|
+
# The servicedb container is reaped with the sandbox/VM — nothing to release here
|
|
198
|
+
return None
|
|
199
|
+
|
|
200
|
+
# --- URL construction (single source) ----------------------------------------------
|
|
201
|
+
|
|
202
|
+
@staticmethod
|
|
203
|
+
def _pg_url(
|
|
204
|
+
host: str,
|
|
205
|
+
*,
|
|
206
|
+
port: int = SERVICE_DB_PORT,
|
|
207
|
+
scheme: str = "postgresql",
|
|
208
|
+
sslmode: str | None = None,
|
|
209
|
+
) -> str:
|
|
210
|
+
"""Build the local postgres (servicedb) connection URL from the store creds."""
|
|
211
|
+
url = f"{scheme}://{DB_USER}:{DB_PASSWORD}@{host}:{port}/{DB_NAME}"
|
|
212
|
+
return f"{url}?sslmode={sslmode}" if sslmode else url
|
|
213
|
+
|
|
214
|
+
# --- DatabaseStateProvider seam (Postgres/compose specifics live here) -------------
|
|
215
|
+
|
|
216
|
+
def base_url(self, instance: EnvStateInstance) -> str:
|
|
217
|
+
return instance._db_url_base
|
|
218
|
+
|
|
219
|
+
def url_for_environment(self, environment_name: str, *, instance: EnvStateInstance) -> str:
|
|
220
|
+
base = self.base_url(instance)
|
|
221
|
+
sep = "&" if "?" in base else "?"
|
|
222
|
+
return f"{base}{sep}options=-c%20search_path%3D%22{environment_name}%22,public"
|
|
223
|
+
|
|
224
|
+
def env_state_docker_service_name(self) -> str:
|
|
225
|
+
return DATABASE_SERVICE_NAME
|
|
226
|
+
|
|
227
|
+
def render_healthcheck_service(
|
|
228
|
+
self,
|
|
229
|
+
environment_names: list[str],
|
|
230
|
+
*,
|
|
231
|
+
instance: EnvStateInstance | None = None,
|
|
232
|
+
) -> list[str]:
|
|
233
|
+
"""The readiness service for local Postgres IS the servicedb container itself (its own
|
|
234
|
+
``pg_isready`` healthcheck). ``environment_names`` are the MCP services hosted here (one schema
|
|
235
|
+
each); ``instance`` is unused (the container is described statically)."""
|
|
236
|
+
cfg = self.service_db_config
|
|
237
|
+
spec = self.store_spec(environment_names)
|
|
238
|
+
hc = spec.healthcheck
|
|
239
|
+
return [
|
|
240
|
+
f" {self.env_state_docker_service_name()}:",
|
|
241
|
+
f" image: {cfg.db_image}",
|
|
242
|
+
" environment:",
|
|
243
|
+
*[f" - {key}={value}" for key, value in spec.env.items()],
|
|
244
|
+
" healthcheck:",
|
|
245
|
+
f" test: {hc['test']}",
|
|
246
|
+
f" interval: {hc['interval']}",
|
|
247
|
+
f" timeout: {hc['timeout']}",
|
|
248
|
+
f" retries: {hc['retries']}",
|
|
249
|
+
" volumes:",
|
|
250
|
+
f" - ./init-schemas.sql:{INIT_SCRIPT_MOUNT_PATH}",
|
|
251
|
+
" networks:",
|
|
252
|
+
" - env-network",
|
|
253
|
+
"",
|
|
254
|
+
]
|
|
255
|
+
|
|
256
|
+
def render_sidecar_containers(
|
|
257
|
+
self,
|
|
258
|
+
environment_names: list[str],
|
|
259
|
+
*,
|
|
260
|
+
host_port: Optional[Callable[[int], int]] = None,
|
|
261
|
+
) -> list[str]:
|
|
262
|
+
"""The pgweb + db-mcp direct-SQL browse UIs (VM/compose path), each gated on the
|
|
263
|
+
servicedb's health. Beyond the mandatory readiness service."""
|
|
264
|
+
publish = host_port or (lambda port: port)
|
|
265
|
+
cfg = self.service_db_config
|
|
266
|
+
lines: list[str] = []
|
|
267
|
+
if cfg.db_web_image:
|
|
268
|
+
lines.extend([
|
|
269
|
+
f" {PGWEB_SERVICE_NAME}:",
|
|
270
|
+
f" image: {cfg.db_web_image}",
|
|
271
|
+
" restart: unless-stopped",
|
|
272
|
+
" depends_on:",
|
|
273
|
+
f" {DATABASE_SERVICE_NAME}:",
|
|
274
|
+
" condition: service_healthy",
|
|
275
|
+
" environment:",
|
|
276
|
+
f" - PGWEB_DATABASE_URL={self._pg_url(DATABASE_SERVICE_NAME, scheme='postgres', sslmode='disable')}",
|
|
277
|
+
# Lock to the single connection + hide Connect/Disconnect (see
|
|
278
|
+
# sidecar_specs for why: Disconnect tore down pgweb's shared
|
|
279
|
+
# session and 500'd the changelog export on Save & Next).
|
|
280
|
+
" - PGWEB_LOCK_SESSION=true",
|
|
281
|
+
" ports:",
|
|
282
|
+
f' - "{publish(DB_WEB_PORT)}:{DB_WEB_PORT}"',
|
|
283
|
+
" networks:",
|
|
284
|
+
" - env-network",
|
|
285
|
+
"",
|
|
286
|
+
])
|
|
287
|
+
if cfg.db_mcp_image:
|
|
288
|
+
lines.extend([
|
|
289
|
+
f" {DB_MCP_SERVICE_NAME}:",
|
|
290
|
+
f" image: {cfg.db_mcp_image}",
|
|
291
|
+
" restart: unless-stopped",
|
|
292
|
+
" depends_on:",
|
|
293
|
+
f" {DATABASE_SERVICE_NAME}:",
|
|
294
|
+
" condition: service_healthy",
|
|
295
|
+
" environment:",
|
|
296
|
+
f" - DATABASE_URI={self._pg_url(DATABASE_SERVICE_NAME, scheme='postgresql')}",
|
|
297
|
+
" command: --transport=streamable-http --streamable-http-host=0.0.0.0 --access-mode=unrestricted",
|
|
298
|
+
" ports:",
|
|
299
|
+
f' - "{publish(DB_MCP_PORT)}:{DB_MCP_CONTAINER_PORT}"',
|
|
300
|
+
" networks:",
|
|
301
|
+
" - env-network",
|
|
302
|
+
"",
|
|
303
|
+
])
|
|
304
|
+
return lines
|
|
305
|
+
|
|
306
|
+
def rendered_sidecar_service_names(self) -> list[str]:
|
|
307
|
+
"""The sidecar services ``render_sidecar_containers`` actually emits (same per-image gating),
|
|
308
|
+
so the gateway can check/wire what was rendered without reading ``ServiceDBConfig`` itself."""
|
|
309
|
+
cfg = self.service_db_config
|
|
310
|
+
names: list[str] = []
|
|
311
|
+
if cfg.db_web_image:
|
|
312
|
+
names.append(PGWEB_SERVICE_NAME)
|
|
313
|
+
if cfg.db_mcp_image:
|
|
314
|
+
names.append(DB_MCP_SERVICE_NAME)
|
|
315
|
+
return names
|
|
316
|
+
|
|
317
|
+
@staticmethod
|
|
318
|
+
def _in_image_store(image: str | None) -> bool:
|
|
319
|
+
"""Whether the image store serving ``image`` owns it: the container path pulls with that
|
|
320
|
+
store's credentials, and has none for any other image."""
|
|
321
|
+
return bool(image) and get_config().get_image_store_at(image).owns(image)
|
|
322
|
+
|
|
323
|
+
def container_store_image(self) -> str:
|
|
324
|
+
"""servicedb image for the Modal container path: the configured image when the image store
|
|
325
|
+
owns it, else stock postgres (postgres needs no customization — schema init runs via
|
|
326
|
+
``psql -f``)."""
|
|
327
|
+
db_image = self.service_db_config.db_image
|
|
328
|
+
if self._in_image_store(db_image):
|
|
329
|
+
return db_image
|
|
330
|
+
if db_image != _STOCK_POSTGRES_IMAGE:
|
|
331
|
+
logger.warning(f"servicedb image {db_image} is not in the image store; running {_STOCK_POSTGRES_IMAGE}")
|
|
332
|
+
return _STOCK_POSTGRES_IMAGE
|
|
333
|
+
|
|
334
|
+
def sidecar_specs(self, *, instance: EnvStateInstance | None = None) -> list[ContainerSpec]:
|
|
335
|
+
"""pgweb + db-mcp container specs (Modal/container path), pointed at the stood-up
|
|
336
|
+
servicedb. Only sidecar images the image store owns are provisionable in container mode;
|
|
337
|
+
any other (or unset) pgweb/db-mcp is skipped + logged."""
|
|
338
|
+
if instance is None:
|
|
339
|
+
raise ValueError(
|
|
340
|
+
"LocalPostgresStateProvider.sidecar_specs requires an instance — the acquired "
|
|
341
|
+
"store whose host the sidecars connect to."
|
|
342
|
+
)
|
|
343
|
+
cfg = self.service_db_config
|
|
344
|
+
db_host = instance.metadata["host"]
|
|
345
|
+
specs: list[ContainerSpec] = []
|
|
346
|
+
if self._in_image_store(cfg.db_web_image):
|
|
347
|
+
pgweb_url = self._pg_url(db_host, scheme="postgres", sslmode="disable")
|
|
348
|
+
specs.append(ContainerSpec(
|
|
349
|
+
name=PGWEB_SERVICE_NAME, image=cfg.db_web_image, port=DB_WEB_PORT,
|
|
350
|
+
# PGWEB_LOCK_SESSION locks pgweb to the single PGWEB_DATABASE_URL
|
|
351
|
+
# connection and hides its Connect/Disconnect UI. Contributors were
|
|
352
|
+
# able to click Disconnect, which tore down pgweb's single shared
|
|
353
|
+
# session — breaking both the Raw DB view AND the hub's changelog
|
|
354
|
+
# export (it queries the same pgweb `/api/query`), so Save & Next
|
|
355
|
+
# 500'd. Locking the session removes the button and the failure.
|
|
356
|
+
env={"PGWEB_DATABASE_URL": pgweb_url, "PGWEB_LOCK_SESSION": "true"},
|
|
357
|
+
))
|
|
358
|
+
elif cfg.db_web_image:
|
|
359
|
+
logger.warning(f"pgweb image {cfg.db_web_image} is not in the image store; skipping pgweb provisioning")
|
|
360
|
+
if self._in_image_store(cfg.db_mcp_image):
|
|
361
|
+
db_mcp_uri = self._pg_url(db_host, scheme="postgresql")
|
|
362
|
+
specs.append(ContainerSpec(
|
|
363
|
+
name=DB_MCP_SERVICE_NAME, image=cfg.db_mcp_image, port=DB_MCP_CONTAINER_PORT,
|
|
364
|
+
env={"DATABASE_URI": db_mcp_uri},
|
|
365
|
+
command=["--transport=streamable-http", "--streamable-http-host=0.0.0.0", "--access-mode=unrestricted"],
|
|
366
|
+
))
|
|
367
|
+
elif cfg.db_mcp_image:
|
|
368
|
+
logger.warning(f"db-mcp image {cfg.db_mcp_image} is not in the image store; skipping db-mcp provisioning")
|
|
369
|
+
return specs
|
|
370
|
+
|
|
371
|
+
async def install_changelog_triggers(
|
|
372
|
+
self,
|
|
373
|
+
environment_name: str,
|
|
374
|
+
*,
|
|
375
|
+
instance: EnvStateInstance | None = None,
|
|
376
|
+
store_exec: "Callable[[list[str]], Awaitable[tuple[int, str, str]]] | None" = None,
|
|
377
|
+
) -> None:
|
|
378
|
+
"""Run ``SELECT _install_changelog_triggers('<schema>')`` via ``psql`` inside the store
|
|
379
|
+
sandbox (the local store is unreachable from the deploy host, so the gateway injects
|
|
380
|
+
``store_exec`` — a 'run this argv against the store' capability)
|
|
381
|
+
"""
|
|
382
|
+
if store_exec is None:
|
|
383
|
+
raise ValueError("LocalPostgresStateProvider.install_changelog_triggers requires store_exec")
|
|
384
|
+
argv = [
|
|
385
|
+
"psql", "-U", DB_USER, "-d", DB_NAME,
|
|
386
|
+
"-c", f"SELECT _install_changelog_triggers('{environment_name}')",
|
|
387
|
+
]
|
|
388
|
+
exit_code, _out, err = await store_exec(argv)
|
|
389
|
+
if exit_code != 0:
|
|
390
|
+
raise RuntimeError(f"Changelog trigger install failed for '{environment_name}': {err[-500:]}")
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
"""Store for ``EnvStateInstance`` records (collection ``env_state_instances``)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
import random
|
|
7
|
+
import string
|
|
8
|
+
from datetime import datetime, timedelta, timezone
|
|
9
|
+
from typing import Optional
|
|
10
|
+
|
|
11
|
+
from agent_env.providers.env_state.env_state_provider import EnvStateInstance, TS_FMT
|
|
12
|
+
from agent_env.store.base import NotFoundError
|
|
13
|
+
from agent_env.config import get_config
|
|
14
|
+
from agent_env.store.document_store import Filter, UpdateSpec
|
|
15
|
+
|
|
16
|
+
logger = logging.getLogger(__name__)
|
|
17
|
+
|
|
18
|
+
ENV_STATE_INSTANCES_COLLECTION = "env_state_instances"
|
|
19
|
+
_TS_FMT = TS_FMT
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class EnvStateInstanceStore:
|
|
23
|
+
def __init__(self) -> None:
|
|
24
|
+
self._indexed = None
|
|
25
|
+
|
|
26
|
+
@property
|
|
27
|
+
def _doc_store(self):
|
|
28
|
+
# Resolved per call: a cached store outlives reset_config(), so a process that
|
|
29
|
+
# re-pointed would read the new config and write the old backend.
|
|
30
|
+
store = get_config().get_document_store()
|
|
31
|
+
if self._indexed is not store:
|
|
32
|
+
store.ensure_index(
|
|
33
|
+
ENV_STATE_INSTANCES_COLLECTION, ["instance_id"], unique=True
|
|
34
|
+
)
|
|
35
|
+
self._indexed = store
|
|
36
|
+
return store
|
|
37
|
+
|
|
38
|
+
def create_instance(self, instance: EnvStateInstance, ttl_seconds: int) -> EnvStateInstance:
|
|
39
|
+
now = datetime.now(timezone.utc)
|
|
40
|
+
if not instance.instance_id:
|
|
41
|
+
suffix = "".join(random.choices(string.ascii_lowercase + string.digits, k=8))
|
|
42
|
+
instance.instance_id = f"esi-{suffix}"
|
|
43
|
+
instance.created_at_utc = now.strftime(_TS_FMT)
|
|
44
|
+
instance.expires_at_utc = (now + timedelta(seconds=ttl_seconds)).strftime(_TS_FMT)
|
|
45
|
+
self._doc_store.insert(ENV_STATE_INSTANCES_COLLECTION, instance.to_dict())
|
|
46
|
+
return instance
|
|
47
|
+
|
|
48
|
+
def get(self, instance_id: str) -> EnvStateInstance:
|
|
49
|
+
doc = self._doc_store.find_one(
|
|
50
|
+
ENV_STATE_INSTANCES_COLLECTION, Filter.of(instance_id=instance_id)
|
|
51
|
+
)
|
|
52
|
+
if not doc:
|
|
53
|
+
raise NotFoundError(f"EnvStateInstance '{instance_id}' not found")
|
|
54
|
+
return EnvStateInstance.from_dict(doc)
|
|
55
|
+
|
|
56
|
+
def set_expired_now(self, instance_id: str) -> None:
|
|
57
|
+
"""Retire by pulling ``expires_at_utc`` forward to now (RETIRED ⟺ expires <= now)."""
|
|
58
|
+
now = datetime.now(timezone.utc).strftime(_TS_FMT)
|
|
59
|
+
self._doc_store.update(
|
|
60
|
+
ENV_STATE_INSTANCES_COLLECTION,
|
|
61
|
+
Filter.of(instance_id=instance_id),
|
|
62
|
+
UpdateSpec(set={"expires_at_utc": now}),
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
def set_metadata(self, instance_id: str, metadata: dict) -> None:
|
|
66
|
+
self._doc_store.update(
|
|
67
|
+
ENV_STATE_INSTANCES_COLLECTION,
|
|
68
|
+
Filter.of(instance_id=instance_id),
|
|
69
|
+
UpdateSpec(set={"metadata": metadata}),
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
_store: Optional[EnvStateInstanceStore] = None
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def get_env_state_instance_store() -> EnvStateInstanceStore:
|
|
77
|
+
global _store
|
|
78
|
+
if _store is None:
|
|
79
|
+
_store = EnvStateInstanceStore()
|
|
80
|
+
return _store
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def set_env_state_instance_store(store: EnvStateInstanceStore) -> None:
|
|
84
|
+
global _store
|
|
85
|
+
_store = store
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def reset_env_state_instance_store() -> None:
|
|
89
|
+
global _store
|
|
90
|
+
_store = None
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def register_env_state_instance(instance: EnvStateInstance, ttl_seconds: int) -> EnvStateInstance:
|
|
94
|
+
try:
|
|
95
|
+
return get_env_state_instance_store().create_instance(instance, ttl_seconds)
|
|
96
|
+
except Exception:
|
|
97
|
+
logger.warning("Failed to persist env state instance %s", instance.instance_id, exc_info=True)
|
|
98
|
+
return instance
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def retire_env_state_instance(instance_id: str) -> None:
|
|
102
|
+
try:
|
|
103
|
+
get_env_state_instance_store().set_expired_now(instance_id)
|
|
104
|
+
except Exception:
|
|
105
|
+
logger.warning("Failed to retire env state instance %s", instance_id, exc_info=True)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def update_env_state_instance_metadata(instance_id: str, metadata: dict) -> None:
|
|
109
|
+
try:
|
|
110
|
+
get_env_state_instance_store().set_metadata(instance_id, metadata)
|
|
111
|
+
except Exception:
|
|
112
|
+
logger.warning("Failed to update metadata for env state instance %s", instance_id, exc_info=True)
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"""Sandbox providers: the compute an environment or agent runs on."""
|
|
2
|
+
|
|
3
|
+
from agent_env.providers.sandbox_providers.sandbox import Sandbox, VmSandbox
|
|
4
|
+
from agent_env.providers.sandbox_providers.sandbox_provider import (
|
|
5
|
+
SANDBOX_MODE_CONTAINER, SANDBOX_MODE_VM,
|
|
6
|
+
SandboxProvider,
|
|
7
|
+
build_sandbox_provider,
|
|
8
|
+
get_sandbox_provider, set_sandbox_provider, reset_sandbox_provider,
|
|
9
|
+
get_env_sandbox_provider, set_env_sandbox_provider, reset_env_sandbox_provider,
|
|
10
|
+
get_agent_sandbox_provider, set_agent_sandbox_provider, reset_agent_sandbox_provider,
|
|
11
|
+
)
|
|
12
|
+
from agent_env.providers.sandbox_providers.chained_sandbox_provider import ChainedSandboxProvider
|
|
13
|
+
from agent_env.providers.sandbox_providers.local_sandbox import LocalSandbox, LocalSandboxProvider
|
|
14
|
+
from agent_env.providers.sandbox_providers.modal_sandbox import ModalSandbox, ModalSandboxProvider
|
|
15
|
+
from agent_env.providers.sandbox_providers.modal_vm_sandbox import ModalVmSandbox, ModalVmSandboxProvider
|
|
16
|
+
from agent_env.providers.sandbox_providers.e2b import E2BSandbox, E2BSandboxProvider
|
|
17
|
+
|
|
18
|
+
__all__ = [
|
|
19
|
+
"ChainedSandboxProvider", "Sandbox", "VmSandbox",
|
|
20
|
+
"SANDBOX_MODE_CONTAINER", "SANDBOX_MODE_VM",
|
|
21
|
+
"SandboxProvider", "LocalSandbox", "LocalSandboxProvider",
|
|
22
|
+
"ModalSandbox", "ModalSandboxProvider",
|
|
23
|
+
"ModalVmSandbox", "ModalVmSandboxProvider",
|
|
24
|
+
"E2BSandbox", "E2BSandboxProvider",
|
|
25
|
+
"build_sandbox_provider",
|
|
26
|
+
"get_sandbox_provider", "set_sandbox_provider", "reset_sandbox_provider",
|
|
27
|
+
"get_env_sandbox_provider", "set_env_sandbox_provider", "reset_env_sandbox_provider",
|
|
28
|
+
"get_agent_sandbox_provider", "set_agent_sandbox_provider", "reset_agent_sandbox_provider",
|
|
29
|
+
]
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import logging
|
|
5
|
+
|
|
6
|
+
from agent_env.attribution import Attribution
|
|
7
|
+
from agent_env.providers.sandbox_providers.sandbox import NetworkPolicy, NetworkPolicyUnsupportedError, Sandbox
|
|
8
|
+
from agent_env.providers.sandbox_providers.sandbox_provider import SandboxProvider
|
|
9
|
+
|
|
10
|
+
logger = logging.getLogger(__name__)
|
|
11
|
+
|
|
12
|
+
_PROVISION_DEADLINE_SECONDS = 180
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class ChainedSandboxProvider(SandboxProvider):
|
|
16
|
+
def __init__(self, providers: list[SandboxProvider]):
|
|
17
|
+
if not providers:
|
|
18
|
+
raise ValueError("ChainedSandboxProvider requires at least one provider")
|
|
19
|
+
self._providers = providers
|
|
20
|
+
|
|
21
|
+
@staticmethod
|
|
22
|
+
def filter_sandbox_providers(
|
|
23
|
+
providers: list[SandboxProvider], policy: NetworkPolicy | None
|
|
24
|
+
) -> list[SandboxProvider]:
|
|
25
|
+
"""``providers`` that can enforce ``policy``, so an incapable one is never called."""
|
|
26
|
+
if policy is None or not policy.restricts_egress:
|
|
27
|
+
return providers
|
|
28
|
+
eligible: list[SandboxProvider] = []
|
|
29
|
+
for p in providers:
|
|
30
|
+
if p.supports_network_policy(policy):
|
|
31
|
+
eligible.append(p)
|
|
32
|
+
else:
|
|
33
|
+
log = logger.warning if p is providers[0] else logger.info
|
|
34
|
+
log(f"sandbox_provider_skipped provider={type(p).__name__} mode={policy.mode.value}")
|
|
35
|
+
if not eligible:
|
|
36
|
+
raise NetworkPolicyUnsupportedError(
|
|
37
|
+
f"No sandbox backend can enforce network policy mode {policy.mode.value!r} "
|
|
38
|
+
f"(providers: {[type(p).__name__ for p in providers]})"
|
|
39
|
+
)
|
|
40
|
+
return eligible
|
|
41
|
+
|
|
42
|
+
def supports_network_policy(self, policy: NetworkPolicy) -> bool:
|
|
43
|
+
return any(p.supports_network_policy(policy) for p in self._providers)
|
|
44
|
+
|
|
45
|
+
async def create_sandbox(
|
|
46
|
+
self,
|
|
47
|
+
*,
|
|
48
|
+
attribution: Attribution | None = None,
|
|
49
|
+
**kwargs,
|
|
50
|
+
) -> Sandbox:
|
|
51
|
+
sandbox_providers = self.filter_sandbox_providers(self._providers, kwargs.get("network_policy"))
|
|
52
|
+
errors: list[tuple[str, Exception]] = []
|
|
53
|
+
for p in sandbox_providers:
|
|
54
|
+
name = type(p).__name__
|
|
55
|
+
try:
|
|
56
|
+
async with asyncio.timeout(_PROVISION_DEADLINE_SECONDS):
|
|
57
|
+
sandbox = await p.create_sandbox(attribution=attribution, **kwargs)
|
|
58
|
+
except Exception as e:
|
|
59
|
+
logger.warning(f"{name}.create_sandbox failed: {e}; trying next provider")
|
|
60
|
+
errors.append((name, e))
|
|
61
|
+
continue
|
|
62
|
+
logger.info(
|
|
63
|
+
f"chain_provider_attempt provider={name} status=success sandbox_type={sandbox.type} "
|
|
64
|
+
f"network_policy={sandbox.network_policy.mode.value if sandbox.network_policy else 'unknown'}"
|
|
65
|
+
)
|
|
66
|
+
return sandbox
|
|
67
|
+
detail = "; ".join(f"{n}: {e!r}" for n, e in errors)
|
|
68
|
+
raise RuntimeError(f"All {len(sandbox_providers)} providers failed: {detail}")
|
|
69
|
+
|
|
70
|
+
async def get_sandbox(self, sandbox_id: str) -> Sandbox:
|
|
71
|
+
errors: list[tuple[str, Exception]] = []
|
|
72
|
+
for p in self._providers:
|
|
73
|
+
name = type(p).__name__
|
|
74
|
+
try:
|
|
75
|
+
return await p.get_sandbox(sandbox_id)
|
|
76
|
+
except NotImplementedError:
|
|
77
|
+
continue
|
|
78
|
+
except Exception as e:
|
|
79
|
+
logger.warning(
|
|
80
|
+
f"{name}.get_sandbox({sandbox_id}) failed: {e}; trying next provider"
|
|
81
|
+
)
|
|
82
|
+
errors.append((name, e))
|
|
83
|
+
detail = "; ".join(f"{n}: {e!r}" for n, e in errors)
|
|
84
|
+
raise RuntimeError(
|
|
85
|
+
f"All {len(self._providers)} providers failed get_sandbox({sandbox_id}): {detail}"
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
async def close(self) -> None:
|
|
89
|
+
for p in self._providers:
|
|
90
|
+
try:
|
|
91
|
+
await p.close()
|
|
92
|
+
except Exception as e:
|
|
93
|
+
logger.warning(f"close() failed on {type(p).__name__}: {e}")
|