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,500 @@
|
|
|
1
|
+
"""Modal sandbox provider — runs agent containers as Modal sandboxes."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import base64
|
|
7
|
+
import contextlib
|
|
8
|
+
import hashlib
|
|
9
|
+
import logging
|
|
10
|
+
import os
|
|
11
|
+
import re
|
|
12
|
+
import shlex
|
|
13
|
+
from typing import AsyncIterator, ClassVar, Optional
|
|
14
|
+
|
|
15
|
+
import httpx
|
|
16
|
+
import modal
|
|
17
|
+
|
|
18
|
+
from agent_env.attribution import PIPELINE_STEP_KEY, RUN_ID_KEY, Attribution
|
|
19
|
+
from agent_env.config import get_config
|
|
20
|
+
from agent_env.providers.sandbox_providers.sandbox import NetworkMode, NetworkPolicy, Sandbox
|
|
21
|
+
from agent_env.providers.sandbox_providers.sandbox_provider import (
|
|
22
|
+
SANDBOX_MODE_CONTAINER,
|
|
23
|
+
SandboxProvider,
|
|
24
|
+
apply_default_attribution,
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
logger = logging.getLogger(__name__)
|
|
28
|
+
|
|
29
|
+
DEFAULT_APP_NAME = "agent-env"
|
|
30
|
+
# Lets a dedicated service (e.g. the sandbox proxy service) attribute its Modal apps under its own
|
|
31
|
+
# base name instead of the shared default. Resolved per-construction, so it's read
|
|
32
|
+
# from the env at deploy time, not import time.
|
|
33
|
+
MODAL_APP_NAME_ENV_VAR = "AGENT_ENV_MODAL_APP_NAME"
|
|
34
|
+
|
|
35
|
+
# Public: out-of-tree Modal providers (a GPU one, for instance) import it too.
|
|
36
|
+
ECR_READER_SECRET_KEYS = ["AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", "AWS_REGION"]
|
|
37
|
+
|
|
38
|
+
_MODAL_TAG_MAX_LEN = 63
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _resolve_app_base_name(app_name: Optional[str]) -> str:
|
|
42
|
+
return app_name or os.getenv(MODAL_APP_NAME_ENV_VAR) or DEFAULT_APP_NAME
|
|
43
|
+
|
|
44
|
+
_I6PN_RESOLVE_CMD = "getent ahostsv6 i6pn.modal.local 2>/dev/null | awk 'NR==1 {print $1}'"
|
|
45
|
+
# 8 MB chunks of raw bytes — base64 inflates to ~10.7 MB, comfortably under
|
|
46
|
+
# Modal's TASK_COMMAND_ROUTER_MAX_BUFFER_SIZE (16 MB) per write. Keep non-final
|
|
47
|
+
# chunks divisible by 3 so concatenated base64 has padding only at EOF (mid-stream
|
|
48
|
+
# '=' would make `base64 -d` truncate the file).
|
|
49
|
+
_STDIN_CHUNK_BYTES = 8 * 1024 * 1024 - ((8 * 1024 * 1024) % 3)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _tunnel_url(t) -> str:
|
|
53
|
+
return f"https://{t.host}" + (f":{t.port}" if t.port != 443 else "")
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _modal_network_kwargs(policy: NetworkPolicy) -> dict:
|
|
57
|
+
"""``policy`` as Modal ``_experimental_create`` kwargs.
|
|
58
|
+
|
|
59
|
+
ALLOW_ALL contributes nothing: passing ``outbound_domain_allowlist`` at all flips Modal
|
|
60
|
+
OPEN -> ALLOWLIST and drops raw-IP egress, even for ``["*"]``.
|
|
61
|
+
"""
|
|
62
|
+
if policy.mode is NetworkMode.ALLOW_ALL:
|
|
63
|
+
return {}
|
|
64
|
+
return {
|
|
65
|
+
"outbound_domain_allowlist": list(policy.allow_hosts),
|
|
66
|
+
"outbound_cidr_allowlist": list(policy.allow_cidrs),
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _fmt_exc(e: BaseException) -> str:
|
|
71
|
+
type_name = f"{type(e).__module__}.{type(e).__qualname__}"
|
|
72
|
+
msg = str(e).strip()
|
|
73
|
+
return f"{type_name}: {msg}" if msg else type_name
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
async def _resolve_i6pn_address(sb: modal.Sandbox) -> Optional[str]:
|
|
77
|
+
try:
|
|
78
|
+
p = await sb.exec.aio("sh", "-c", _I6PN_RESOLVE_CMD)
|
|
79
|
+
raw = await p.stdout.read.aio()
|
|
80
|
+
out = raw.decode().strip() if isinstance(raw, (bytes, bytearray)) else str(raw).strip()
|
|
81
|
+
rc = await p.wait.aio()
|
|
82
|
+
if rc == 0 and out and ":" in out:
|
|
83
|
+
return out
|
|
84
|
+
logger.warning(f"i6pn address resolution returned rc={rc} stdout={out!r}")
|
|
85
|
+
except Exception as e:
|
|
86
|
+
logger.warning(f"i6pn address resolution failed: {type(e).__name__}: {e}")
|
|
87
|
+
return None
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
class _ModalStreamAdapter:
|
|
91
|
+
def __init__(self, stream):
|
|
92
|
+
self._stream = stream
|
|
93
|
+
|
|
94
|
+
async def read(self) -> bytes:
|
|
95
|
+
return await self._stream.read.aio()
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
class _ModalProcessAdapter:
|
|
99
|
+
def __init__(self, process):
|
|
100
|
+
self._process = process
|
|
101
|
+
self.stdout = _ModalStreamAdapter(process.stdout)
|
|
102
|
+
self.stderr = _ModalStreamAdapter(process.stderr)
|
|
103
|
+
|
|
104
|
+
async def wait(self) -> int:
|
|
105
|
+
return await self._process.wait.aio()
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
class ModalSandbox(Sandbox):
|
|
109
|
+
type = "modal"
|
|
110
|
+
|
|
111
|
+
def __init__(self, sb: modal.Sandbox, tunnel_urls: dict[int, str], i6pn_address: Optional[str] = None,
|
|
112
|
+
network_policy: NetworkPolicy | None = None):
|
|
113
|
+
self._sb = sb
|
|
114
|
+
self.sandbox_id = sb.object_id
|
|
115
|
+
self.tunnel_urls = tunnel_urls
|
|
116
|
+
self.i6pn_address = i6pn_address
|
|
117
|
+
self.vnc_url = None
|
|
118
|
+
self.mode = SANDBOX_MODE_CONTAINER
|
|
119
|
+
self.network_policy = network_policy
|
|
120
|
+
|
|
121
|
+
async def terminate(self) -> None:
|
|
122
|
+
await self._sb.terminate.aio()
|
|
123
|
+
|
|
124
|
+
async def exec(self, *command: str):
|
|
125
|
+
process = await self._sb.exec.aio(*command, text=False)
|
|
126
|
+
return _ModalProcessAdapter(process)
|
|
127
|
+
|
|
128
|
+
async def _write_stream_via_exec(
|
|
129
|
+
self, stream: AsyncIterator[bytes], destination_path: str,
|
|
130
|
+
) -> None:
|
|
131
|
+
# V2 has no filesystem API and our container images don't reliably ship curl —
|
|
132
|
+
# bytes flow through `base64 -d` over exec stdin instead.
|
|
133
|
+
parent = "/".join(destination_path.split("/")[:-1])
|
|
134
|
+
mkdir = f"mkdir -p {shlex.quote(parent)} && " if parent else ""
|
|
135
|
+
cmd = f"{mkdir}base64 -d > {shlex.quote(destination_path)}"
|
|
136
|
+
proc = await self._sb.exec.aio("sh", "-c", cmd, text=False)
|
|
137
|
+
buf = bytearray()
|
|
138
|
+
async for chunk in stream:
|
|
139
|
+
buf.extend(chunk)
|
|
140
|
+
while len(buf) >= _STDIN_CHUNK_BYTES:
|
|
141
|
+
proc.stdin.write(base64.b64encode(bytes(buf[:_STDIN_CHUNK_BYTES])))
|
|
142
|
+
del buf[:_STDIN_CHUNK_BYTES]
|
|
143
|
+
await proc.stdin.drain.aio()
|
|
144
|
+
if buf:
|
|
145
|
+
proc.stdin.write(base64.b64encode(bytes(buf)))
|
|
146
|
+
await proc.stdin.drain.aio()
|
|
147
|
+
proc.stdin.write_eof()
|
|
148
|
+
await proc.stdin.drain.aio()
|
|
149
|
+
rc = await proc.wait.aio()
|
|
150
|
+
if rc != 0:
|
|
151
|
+
stderr = await proc.stderr.read.aio()
|
|
152
|
+
raise RuntimeError(f"write to {destination_path} failed (exit={rc}): {stderr!r}")
|
|
153
|
+
|
|
154
|
+
async def write_file_from_s3(self, s3_url: str, destination_path: str) -> None:
|
|
155
|
+
body = await asyncio.to_thread(get_config().get_object_store().open, s3_url)
|
|
156
|
+
with contextlib.closing(body):
|
|
157
|
+
|
|
158
|
+
async def _aiter() -> AsyncIterator[bytes]:
|
|
159
|
+
while chunk := await asyncio.to_thread(body.read, _STDIN_CHUNK_BYTES):
|
|
160
|
+
yield chunk
|
|
161
|
+
|
|
162
|
+
await self._write_stream_via_exec(_aiter(), destination_path)
|
|
163
|
+
|
|
164
|
+
async def write_file_from_text(self, content: str, destination_path: str) -> None:
|
|
165
|
+
async def _aiter() -> AsyncIterator[bytes]:
|
|
166
|
+
yield content.encode()
|
|
167
|
+
|
|
168
|
+
await self._write_stream_via_exec(_aiter(), destination_path)
|
|
169
|
+
|
|
170
|
+
async def write_file_from_url(self, url: str, destination_path: str) -> None:
|
|
171
|
+
async with httpx.AsyncClient(follow_redirects=True, timeout=120) as client:
|
|
172
|
+
async with client.stream("GET", url) as r:
|
|
173
|
+
r.raise_for_status()
|
|
174
|
+
await self._write_stream_via_exec(
|
|
175
|
+
r.aiter_bytes(_STDIN_CHUNK_BYTES), destination_path,
|
|
176
|
+
)
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
class ModalSandboxProvider(SandboxProvider):
|
|
180
|
+
EGRESS_HOSTS: ClassVar[tuple[str, ...]] = ("*.modal.host", "*.w.modal.host")
|
|
181
|
+
# Sandbox class this provider produces. A subclass or instance registered under a different
|
|
182
|
+
# ``[sandbox.providers.<name>]`` key can set it to a ``ModalSandbox`` subclass whose
|
|
183
|
+
# ``type`` equals that name — the registry's type-guard requires the produced
|
|
184
|
+
# sandbox's ``.type`` to match the config key.
|
|
185
|
+
_sandbox_cls: type[ModalSandbox] = ModalSandbox
|
|
186
|
+
|
|
187
|
+
@classmethod
|
|
188
|
+
def supports_network_policy(cls, policy: NetworkPolicy) -> bool:
|
|
189
|
+
return True
|
|
190
|
+
|
|
191
|
+
def __init__(
|
|
192
|
+
self,
|
|
193
|
+
app_name: Optional[str] = None,
|
|
194
|
+
gpu: Optional[str] = None,
|
|
195
|
+
ecr_pull_secret_name: Optional[str] = None,
|
|
196
|
+
):
|
|
197
|
+
self._app_name = _resolve_app_base_name(app_name)
|
|
198
|
+
self._ecr_pull_secret_name = ecr_pull_secret_name
|
|
199
|
+
self._client: Optional[modal.Client] = None
|
|
200
|
+
# Optional Modal GPU spec (e.g. "H100", "A100", "H100:2"). When set, create_container
|
|
201
|
+
# provisions the sandbox with the V1 ``modal.Sandbox.create`` factory (which accepts
|
|
202
|
+
# ``gpu=`` + docker-in-gVisor) instead of the V2 ``_experimental_create``, which
|
|
203
|
+
# cannot attach a GPU. V1 has no ``i6pn``, so a GPU sandbox has no private-IPv6
|
|
204
|
+
# east-west networking (fine for a single sandbox; not for an i6pn mesh).
|
|
205
|
+
self._gpu = gpu
|
|
206
|
+
# One Modal App per attribution scope (keyed by project_id), looked up on demand.
|
|
207
|
+
# Billing aggregates per App and the dashboard is browsable by App name, so a
|
|
208
|
+
# scope-named, scope-tagged App is what makes cost both attributable and findable.
|
|
209
|
+
self._apps: dict[str, modal.App] = {}
|
|
210
|
+
|
|
211
|
+
async def _get_client(self) -> modal.Client:
|
|
212
|
+
if self._client is None:
|
|
213
|
+
from agent_env.config import get_config
|
|
214
|
+
token_id, token_secret = get_config().get_modal_credentials()
|
|
215
|
+
self._client = await modal.Client.from_credentials.aio(token_id, token_secret)
|
|
216
|
+
return self._client
|
|
217
|
+
|
|
218
|
+
async def _get_app(self, app_name: str, app_tags: Optional[dict[str, str]] = None) -> modal.App:
|
|
219
|
+
app = self._apps.get(app_name)
|
|
220
|
+
if app is None:
|
|
221
|
+
client = await self._get_client()
|
|
222
|
+
app = await modal.App.lookup.aio(app_name, create_if_missing=True, client=client)
|
|
223
|
+
if app_tags:
|
|
224
|
+
# App tags are the dimension Modal's billing report breaks down by; set them
|
|
225
|
+
# once per app (cached below) rather than on every sandbox.
|
|
226
|
+
try:
|
|
227
|
+
await app.set_tags.aio(app_tags)
|
|
228
|
+
except Exception as e:
|
|
229
|
+
logger.warning(f"Failed to set tags on Modal app {app_name}: {type(e).__name__}: {e}")
|
|
230
|
+
self._apps[app_name] = app
|
|
231
|
+
return app
|
|
232
|
+
|
|
233
|
+
async def create_container(
|
|
234
|
+
self,
|
|
235
|
+
*,
|
|
236
|
+
image_name: str,
|
|
237
|
+
port: int,
|
|
238
|
+
env: dict[str, str],
|
|
239
|
+
# Modal's minimum; cpu is a burstable reservation here, not a cap.
|
|
240
|
+
cpu: float = 0.125,
|
|
241
|
+
memory: int = 8192,
|
|
242
|
+
disk_size_gb: float = 10,
|
|
243
|
+
timeout: int = 3600 * 2,
|
|
244
|
+
attribution: Optional[Attribution] = None,
|
|
245
|
+
priority: Optional[int] = None,
|
|
246
|
+
network_policy: Optional[NetworkPolicy] = None,
|
|
247
|
+
command: list[str] | None = None,
|
|
248
|
+
i6pn: bool = False,
|
|
249
|
+
region: Optional[str] = None,
|
|
250
|
+
expose_externally: bool = True,
|
|
251
|
+
vnc_port: Optional[int] = None,
|
|
252
|
+
) -> Sandbox:
|
|
253
|
+
from agent_env.config import get_config
|
|
254
|
+
|
|
255
|
+
effective = self.effective_network_policy(network_policy)
|
|
256
|
+
attribution = dict(attribution or {})
|
|
257
|
+
|
|
258
|
+
# Place the sandbox under a per-project App: Modal billing aggregates cost per App and
|
|
259
|
+
# the dashboard is browsable by App name, so a scope-named, scope-tagged App is what
|
|
260
|
+
# makes cost both attributable and findable. We attribute at the App level only —
|
|
261
|
+
# sandbox-level tags don't show up in billing.
|
|
262
|
+
app_tags = _build_cost_attribution_tags(attribution)
|
|
263
|
+
app_name = _app_name_for_project(self._app_name, app_tags.get("project_id"))
|
|
264
|
+
app = await self._get_app(app_name, app_tags)
|
|
265
|
+
# Not in billing (see above); makes sandboxes filterable by the step that deployed them.
|
|
266
|
+
sandbox_tags = _build_sandbox_tags(attribution)
|
|
267
|
+
|
|
268
|
+
image_store = get_config().get_image_store_at(image_name)
|
|
269
|
+
from agent_env.store.image_store import (
|
|
270
|
+
EcrCredentials,
|
|
271
|
+
OciRegistryImageStore,
|
|
272
|
+
registry_host_from_ref,
|
|
273
|
+
)
|
|
274
|
+
|
|
275
|
+
uses_ecr_pull_secret = (
|
|
276
|
+
self._ecr_pull_secret_name is not None
|
|
277
|
+
and isinstance(image_store, OciRegistryImageStore)
|
|
278
|
+
and isinstance(image_store.credentials, EcrCredentials)
|
|
279
|
+
and registry_host_from_ref(image_name) == image_store.registry_host
|
|
280
|
+
)
|
|
281
|
+
auth = None if uses_ecr_pull_secret else await asyncio.to_thread(image_store.auth, image_name)
|
|
282
|
+
if uses_ecr_pull_secret:
|
|
283
|
+
image = modal.Image.from_aws_ecr(image_name, secret=modal.Secret.from_name(
|
|
284
|
+
self._ecr_pull_secret_name, required_keys=ECR_READER_SECRET_KEYS))
|
|
285
|
+
elif auth is not None:
|
|
286
|
+
image = modal.Image.from_registry(image_name, secret=modal.Secret.from_dict({
|
|
287
|
+
"REGISTRY_USERNAME": auth.username,
|
|
288
|
+
"REGISTRY_PASSWORD": auth.password,
|
|
289
|
+
}))
|
|
290
|
+
else:
|
|
291
|
+
image = modal.Image.from_registry(image_name)
|
|
292
|
+
|
|
293
|
+
logger.info(
|
|
294
|
+
f"Creating Modal sandbox from image {image_name} "
|
|
295
|
+
f"(app={app_name}, tags={app_tags}, sandbox_tags={sandbox_tags}, port={port}, "
|
|
296
|
+
f"cpu={cpu}, memory={memory}MB, "
|
|
297
|
+
f"gpu={self._gpu}, i6pn={i6pn}, region={region}, expose_externally={expose_externally})"
|
|
298
|
+
)
|
|
299
|
+
client = await self._get_client()
|
|
300
|
+
ports = [port] if vnc_port is None else [port, vnc_port]
|
|
301
|
+
port_kwargs = {"encrypted_ports": ports} if expose_externally else {}
|
|
302
|
+
|
|
303
|
+
call_context = (
|
|
304
|
+
f"image={image_name} port={port} cpu={cpu} memory={memory}MB "
|
|
305
|
+
f"app={app_name} region={region} i6pn={i6pn}"
|
|
306
|
+
)
|
|
307
|
+
|
|
308
|
+
# GPU sandboxes need the V1 ``Sandbox.create`` factory: the V2
|
|
309
|
+
# ``_experimental_create`` has no ``gpu`` parameter and cannot attach one. V1 in
|
|
310
|
+
# turn has no ``i6pn``, so reject that combination up front — before a billed
|
|
311
|
+
# sandbox exists — rather than silently returning one whose i6pn_address is None
|
|
312
|
+
# and failing downstream (e.g. the gateway's "service-db has no i6pn address").
|
|
313
|
+
if self._gpu and i6pn:
|
|
314
|
+
raise ValueError(
|
|
315
|
+
"i6pn is unavailable on GPU sandboxes: the GPU-capable factory "
|
|
316
|
+
"(modal.Sandbox.create) has no i6pn parameter."
|
|
317
|
+
)
|
|
318
|
+
|
|
319
|
+
# ``i6pn`` is threaded per-factory below (V2 only); everything else is shared.
|
|
320
|
+
create_kwargs = dict(
|
|
321
|
+
app=app, image=image, cpu=cpu, memory=memory, timeout=timeout,
|
|
322
|
+
env=env or {}, client=client, **port_kwargs,
|
|
323
|
+
tags=sandbox_tags or None,
|
|
324
|
+
readiness_probe=modal.Probe.with_exec("true"),
|
|
325
|
+
**_modal_network_kwargs(effective),
|
|
326
|
+
)
|
|
327
|
+
if region is not None:
|
|
328
|
+
create_kwargs["region"] = region
|
|
329
|
+
|
|
330
|
+
try:
|
|
331
|
+
if self._gpu:
|
|
332
|
+
sb = await modal.Sandbox.create.aio(
|
|
333
|
+
*(command or []),
|
|
334
|
+
gpu=self._gpu,
|
|
335
|
+
experimental_options={"enable_docker_in_gvisor": True},
|
|
336
|
+
**create_kwargs,
|
|
337
|
+
)
|
|
338
|
+
else:
|
|
339
|
+
sb = await modal.Sandbox._experimental_create.aio(
|
|
340
|
+
*(command or []), i6pn=i6pn, **create_kwargs
|
|
341
|
+
)
|
|
342
|
+
except Exception as e:
|
|
343
|
+
raise RuntimeError(
|
|
344
|
+
f"Modal sandbox create failed [{_fmt_exc(e)}]: {call_context}"
|
|
345
|
+
) from e
|
|
346
|
+
|
|
347
|
+
try:
|
|
348
|
+
await sb.wait_until_ready.aio(timeout=150)
|
|
349
|
+
if expose_externally:
|
|
350
|
+
tunnels = await sb.tunnels.aio()
|
|
351
|
+
tunnel_urls = {p: _tunnel_url(t) for p, t in tunnels.items()}
|
|
352
|
+
if port not in tunnel_urls:
|
|
353
|
+
raise RuntimeError(f"No Modal tunnel for port {port}; got {list(tunnel_urls)}")
|
|
354
|
+
else:
|
|
355
|
+
tunnel_urls = {}
|
|
356
|
+
i6pn_address = await _resolve_i6pn_address(sb) if i6pn else None
|
|
357
|
+
endpoint = tunnel_urls.get(port, "i6pn-only" if i6pn_address else "no-tunnel")
|
|
358
|
+
logger.info(
|
|
359
|
+
f"Modal sandbox ready: {sb.object_id} ({endpoint})"
|
|
360
|
+
+ (f" i6pn={i6pn_address}" if i6pn_address else "")
|
|
361
|
+
)
|
|
362
|
+
await _log_sandbox_started(
|
|
363
|
+
sb, app_name=app_name, sandbox_tags=sandbox_tags,
|
|
364
|
+
cpu=cpu, memory=memory, gpu=self._gpu,
|
|
365
|
+
)
|
|
366
|
+
sandbox = self._sandbox_cls(
|
|
367
|
+
sb,
|
|
368
|
+
tunnel_urls,
|
|
369
|
+
i6pn_address=i6pn_address,
|
|
370
|
+
network_policy=effective,
|
|
371
|
+
)
|
|
372
|
+
if vnc_port in tunnel_urls:
|
|
373
|
+
sandbox.vnc_url = f"{tunnel_urls[vnc_port]}/vnc.html"
|
|
374
|
+
logger.info(f"Modal sandbox vnc_url: {sandbox.vnc_url}")
|
|
375
|
+
return sandbox
|
|
376
|
+
except Exception as e:
|
|
377
|
+
try:
|
|
378
|
+
await sb.terminate.aio()
|
|
379
|
+
except Exception:
|
|
380
|
+
pass
|
|
381
|
+
raise RuntimeError(
|
|
382
|
+
f"Modal sandbox post-create failed [{_fmt_exc(e)}]: "
|
|
383
|
+
f"sb_id={sb.object_id} {call_context}"
|
|
384
|
+
) from e
|
|
385
|
+
|
|
386
|
+
async def create_sandbox(
|
|
387
|
+
self, *, image_name: str, port: int, env: dict[str, str],
|
|
388
|
+
cpu: float = 0.125, memory: int = 8192, disk_size_gb: float = 10, timeout: int = 3600 * 2,
|
|
389
|
+
attribution: Optional[Attribution] = None,
|
|
390
|
+
priority: Optional[int] = None,
|
|
391
|
+
network_policy: Optional[NetworkPolicy] = None,
|
|
392
|
+
) -> Sandbox:
|
|
393
|
+
return await self.create_container(
|
|
394
|
+
image_name=image_name, port=port, env=env,
|
|
395
|
+
cpu=cpu, memory=memory, disk_size_gb=disk_size_gb, timeout=timeout,
|
|
396
|
+
attribution=attribution,
|
|
397
|
+
priority=priority, network_policy=network_policy,
|
|
398
|
+
)
|
|
399
|
+
|
|
400
|
+
async def get_sandbox(self, sandbox_id: str) -> Sandbox:
|
|
401
|
+
client = await self._get_client()
|
|
402
|
+
sb = await modal.Sandbox.from_id.aio(sandbox_id, client=client)
|
|
403
|
+
tunnels = await sb.tunnels.aio()
|
|
404
|
+
tunnel_urls = {p: _tunnel_url(t) for p, t in tunnels.items()}
|
|
405
|
+
i6pn_address = await _resolve_i6pn_address(sb)
|
|
406
|
+
return self._sandbox_cls(sb, tunnel_urls, i6pn_address=i6pn_address)
|
|
407
|
+
|
|
408
|
+
|
|
409
|
+
def _app_name_for_project(base: str, project_id: Optional[str]) -> str:
|
|
410
|
+
"""Map a project_id to a stable Modal App name for per-project cost attribution.
|
|
411
|
+
|
|
412
|
+
The app name is what shows up (and is searchable) in the Modal dashboard, so it encodes
|
|
413
|
+
the project. Names are sanitized to ``[a-zA-Z0-9._-]``, kept under Modal's 64-char limit,
|
|
414
|
+
and not double-prefixed when ``project_id`` already starts with ``base``. Falls back to
|
|
415
|
+
``base`` when no project_id is available.
|
|
416
|
+
"""
|
|
417
|
+
if not project_id:
|
|
418
|
+
return base
|
|
419
|
+
slug = re.sub(r"[^a-zA-Z0-9._-]", "-", project_id).strip("-") or base
|
|
420
|
+
name = slug if (slug == base or slug.startswith(f"{base}-")) else f"{base}-{slug}"
|
|
421
|
+
if len(name) > 64:
|
|
422
|
+
logger.warning(
|
|
423
|
+
f"Modal app name for project_id={project_id!r} exceeds 64 chars; truncating to "
|
|
424
|
+
f"{name[:64]!r}. Distinct project_ids that share this prefix will be cost-attributed "
|
|
425
|
+
f"together."
|
|
426
|
+
)
|
|
427
|
+
name = name[:64]
|
|
428
|
+
return name
|
|
429
|
+
|
|
430
|
+
|
|
431
|
+
def _build_cost_attribution_tags(attribution: Attribution) -> dict[str, str]:
|
|
432
|
+
"""Build the Modal App tag set used for cost attribution.
|
|
433
|
+
|
|
434
|
+
Unset dimensions fall back to config.toml ``[sandbox.attribution]``; a dimension with
|
|
435
|
+
no value anywhere is omitted rather than emitted as a null tag. Returns a flat
|
|
436
|
+
``dict[str, str]`` for ``modal.App.set_tags``. (priority is a scheduling concern,
|
|
437
|
+
not attribution, so it is not included here.)
|
|
438
|
+
"""
|
|
439
|
+
resolved = apply_default_attribution(attribution)
|
|
440
|
+
return {
|
|
441
|
+
name: resolved[name]
|
|
442
|
+
for name in ("product", "customer", "team", "project_id")
|
|
443
|
+
if resolved.get(name) is not None
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
|
|
447
|
+
def _build_sandbox_tags(attribution: Attribution) -> dict[str, str]:
|
|
448
|
+
"""Build the Modal Sandbox tag set: ``pipeline_step`` and ``run_id``, each when set.
|
|
449
|
+
|
|
450
|
+
Modal rejects the whole create on an invalid tag, so values are sanitized to
|
|
451
|
+
``[a-zA-Z0-9._-]``; past Modal's 63-char limit a value keeps a prefix plus a hash of the
|
|
452
|
+
full value, so steps of a long-named task still get distinct tags.
|
|
453
|
+
"""
|
|
454
|
+
return {
|
|
455
|
+
key: _modal_tag_value(attribution[key])
|
|
456
|
+
for key in (PIPELINE_STEP_KEY, RUN_ID_KEY)
|
|
457
|
+
if attribution.get(key)
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
|
|
461
|
+
SANDBOX_STARTED_EVENT = "agent_env.modal_sandbox_started"
|
|
462
|
+
|
|
463
|
+
|
|
464
|
+
async def _log_sandbox_started(
|
|
465
|
+
sb, *, app_name: str, sandbox_tags: dict[str, str],
|
|
466
|
+
cpu: float, memory: int, gpu: Optional[str],
|
|
467
|
+
) -> None:
|
|
468
|
+
"""Log one structured line mapping Modal's container id to the sandbox and its tags.
|
|
469
|
+
|
|
470
|
+
Modal's Datadog metrics carry only ``container_id`` (the ``ta-`` task id), not sandbox tags, so
|
|
471
|
+
this line is the join key from a container's usage to its run and pipeline step. Never raises:
|
|
472
|
+
the task id comes from a private Modal method.
|
|
473
|
+
"""
|
|
474
|
+
try:
|
|
475
|
+
container_id = await sb._get_task_id.aio()
|
|
476
|
+
except Exception as e:
|
|
477
|
+
logger.warning(f"Could not read the Modal container id of {sb.object_id}: {type(e).__name__}: {e}")
|
|
478
|
+
container_id = None
|
|
479
|
+
logger.info(
|
|
480
|
+
f"Modal sandbox started: sandbox_id={sb.object_id} container_id={container_id} "
|
|
481
|
+
f"app={app_name} tags={sandbox_tags}",
|
|
482
|
+
extra={
|
|
483
|
+
"event": SANDBOX_STARTED_EVENT,
|
|
484
|
+
"modal_sandbox_id": sb.object_id,
|
|
485
|
+
"modal_container_id": container_id,
|
|
486
|
+
"modal_app_name": app_name,
|
|
487
|
+
**sandbox_tags,
|
|
488
|
+
"cpu": cpu,
|
|
489
|
+
"memory_mb": memory,
|
|
490
|
+
"gpu": gpu,
|
|
491
|
+
},
|
|
492
|
+
)
|
|
493
|
+
|
|
494
|
+
|
|
495
|
+
def _modal_tag_value(value: str) -> str:
|
|
496
|
+
slug = re.sub(r"[^a-zA-Z0-9._-]", "-", value)
|
|
497
|
+
if len(slug) > _MODAL_TAG_MAX_LEN:
|
|
498
|
+
digest = hashlib.sha256(value.encode()).hexdigest()[:8]
|
|
499
|
+
slug = f"{slug[:_MODAL_TAG_MAX_LEN - len(digest) - 1]}-{digest}"
|
|
500
|
+
return slug
|