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,308 @@
|
|
|
1
|
+
"""Verify filesystem-side rubric criteria against a live sandbox.
|
|
2
|
+
|
|
3
|
+
Handles the four "probe" criterion types from the MM universal-rubric format:
|
|
4
|
+
- probe_file_exists — every path in `paths` exists at <base_dir>/<path>
|
|
5
|
+
- probe_dir_exists — same, but checks they're directories
|
|
6
|
+
- probe_file_contains — first path's contents match `expected` as a regex (re.search)
|
|
7
|
+
- bash_cmd_succeeds — `bash -c <bash_cmd>` with cwd=<base_dir> exits 0
|
|
8
|
+
|
|
9
|
+
Other criterion types in the input list are silently skipped (counted in
|
|
10
|
+
results but excluded from the aggregator) so one criterion set can be split
|
|
11
|
+
across this step and a response-side verifier (e.g. `rubrics_verifier`).
|
|
12
|
+
|
|
13
|
+
Criteria use the same shape as `RubricsVerifierTaskStep.criteria` — a list of
|
|
14
|
+
dicts with a `criterion` (text), optional `weight` (defaults 1.0), and the
|
|
15
|
+
per-type fields documented above. Result rows merge `{**criterion, **outcome}`
|
|
16
|
+
so every input field flows through to the verification output.
|
|
17
|
+
|
|
18
|
+
The sandbox is a deployed agent's (`agent_name`, the default; on a VM the probes
|
|
19
|
+
run inside its container) or one a `deploy_sandbox` step created (`sandbox_name`;
|
|
20
|
+
the probes run directly on it).
|
|
21
|
+
"""
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
import asyncio
|
|
25
|
+
import logging
|
|
26
|
+
import re
|
|
27
|
+
import shlex
|
|
28
|
+
import uuid
|
|
29
|
+
from typing import ClassVar, Optional
|
|
30
|
+
|
|
31
|
+
from agent_env.providers.sandbox_providers.sandbox_provider import (
|
|
32
|
+
SANDBOX_MODE_VM,
|
|
33
|
+
build_sandbox_provider,
|
|
34
|
+
get_agent_sandbox_provider,
|
|
35
|
+
get_sandbox_provider,
|
|
36
|
+
)
|
|
37
|
+
from agent_env.task_step.context import TaskStepContext
|
|
38
|
+
from agent_env.task_step.task_step import TaskStep, TaskStepDependency
|
|
39
|
+
from agent_env.task_step.task_steps.verifiers.scoring import ScoreAggregator, aggregate_score
|
|
40
|
+
|
|
41
|
+
logger = logging.getLogger(__name__)
|
|
42
|
+
|
|
43
|
+
_HANDLED_TYPES = {
|
|
44
|
+
"probe_file_exists",
|
|
45
|
+
"probe_dir_exists",
|
|
46
|
+
"probe_file_contains",
|
|
47
|
+
"bash_cmd_succeeds",
|
|
48
|
+
}
|
|
49
|
+
_DEFAULT_BASE_DIR = "/app"
|
|
50
|
+
_DEFAULT_SHELL_TIMEOUT_S = 120
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _outcome(passed: bool, justification: str) -> dict:
|
|
54
|
+
return {"score": 1.0 if passed else 0.0, "passed": passed, "justification": justification}
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class VerifySandboxTaskStep(TaskStep):
|
|
58
|
+
type: ClassVar[str] = "verify_sandbox"
|
|
59
|
+
entity_refs = ()
|
|
60
|
+
|
|
61
|
+
def __init__(
|
|
62
|
+
self,
|
|
63
|
+
id: str,
|
|
64
|
+
version: Optional[int],
|
|
65
|
+
criteria: Optional[list[dict]] = None,
|
|
66
|
+
agent_name: Optional[str] = None,
|
|
67
|
+
sandbox_name: Optional[str] = None,
|
|
68
|
+
base_dir: str = _DEFAULT_BASE_DIR,
|
|
69
|
+
shell_timeout_seconds: int = _DEFAULT_SHELL_TIMEOUT_S,
|
|
70
|
+
score_aggregator: Optional[ScoreAggregator] = None,
|
|
71
|
+
verifier_id: Optional[str] = None,
|
|
72
|
+
depends_on: Optional[list[TaskStepDependency]] = None,
|
|
73
|
+
fail_task_on_error: bool = True,
|
|
74
|
+
):
|
|
75
|
+
# A blank sandbox_name counts as unset, like a blank agent_name: forms and TOML can't send null.
|
|
76
|
+
if isinstance(sandbox_name, str) and not sandbox_name.strip():
|
|
77
|
+
sandbox_name = None
|
|
78
|
+
# A defaulted agent_name is tolerated: every step serialized before `sandbox_name` carries one.
|
|
79
|
+
if sandbox_name is not None and agent_name and agent_name != TaskStep.DEFAULT_AGENT_NAME:
|
|
80
|
+
raise ValueError("verify_sandbox: set either `agent_name` or `sandbox_name`, not both")
|
|
81
|
+
super().__init__(id, version, depends_on=depends_on, fail_task_on_error=fail_task_on_error)
|
|
82
|
+
self.criteria = list(criteria or [])
|
|
83
|
+
self.sandbox_name = sandbox_name
|
|
84
|
+
self.agent_name = None if sandbox_name is not None else agent_name or TaskStep.DEFAULT_AGENT_NAME
|
|
85
|
+
self.base_dir = base_dir
|
|
86
|
+
self.shell_timeout_seconds = shell_timeout_seconds
|
|
87
|
+
if isinstance(score_aggregator, str):
|
|
88
|
+
score_aggregator = ScoreAggregator(score_aggregator)
|
|
89
|
+
self.score_aggregator = score_aggregator or ScoreAggregator.ALL_PASS
|
|
90
|
+
self.verifier_id = verifier_id or uuid.uuid4().hex
|
|
91
|
+
|
|
92
|
+
def to_dict(self) -> dict:
|
|
93
|
+
base = super().to_dict()
|
|
94
|
+
base["criteria"] = self.criteria
|
|
95
|
+
base["agent_name"] = self.agent_name
|
|
96
|
+
if self.sandbox_name is not None:
|
|
97
|
+
base["sandbox_name"] = self.sandbox_name
|
|
98
|
+
base["base_dir"] = self.base_dir
|
|
99
|
+
base["shell_timeout_seconds"] = self.shell_timeout_seconds
|
|
100
|
+
base["score_aggregator"] = self.score_aggregator.value
|
|
101
|
+
base["verifier_id"] = self.verifier_id
|
|
102
|
+
return base
|
|
103
|
+
|
|
104
|
+
@classmethod
|
|
105
|
+
def from_dict(cls, data: dict) -> "VerifySandboxTaskStep":
|
|
106
|
+
raw_agg = data.get("score_aggregator")
|
|
107
|
+
return cls(
|
|
108
|
+
**cls._base_from_dict(data),
|
|
109
|
+
criteria=data.get("criteria"),
|
|
110
|
+
agent_name=data.get("agent_name"),
|
|
111
|
+
sandbox_name=data.get("sandbox_name"),
|
|
112
|
+
base_dir=data.get("base_dir", _DEFAULT_BASE_DIR),
|
|
113
|
+
shell_timeout_seconds=data.get("shell_timeout_seconds", _DEFAULT_SHELL_TIMEOUT_S),
|
|
114
|
+
score_aggregator=ScoreAggregator(raw_agg) if raw_agg else None,
|
|
115
|
+
verifier_id=data.get("verifier_id"),
|
|
116
|
+
)
|
|
117
|
+
|
|
118
|
+
async def execute(self, context: TaskStepContext) -> TaskStepContext:
|
|
119
|
+
on_agent = self.sandbox_name is None
|
|
120
|
+
sandbox = await (self._agent_sandbox(context) if on_agent else self._deployed_sandbox(context))
|
|
121
|
+
logger.info(f"Connected to sandbox {sandbox.sandbox_id} (mode={sandbox.mode})")
|
|
122
|
+
container = (
|
|
123
|
+
await self._discover_container(sandbox)
|
|
124
|
+
if on_agent and sandbox.mode == SANDBOX_MODE_VM
|
|
125
|
+
else None
|
|
126
|
+
)
|
|
127
|
+
if container:
|
|
128
|
+
logger.info(f"Using agent container: {container}")
|
|
129
|
+
|
|
130
|
+
results: list[dict] = []
|
|
131
|
+
for idx, criterion in enumerate(self.criteria):
|
|
132
|
+
rtype = criterion.get("type")
|
|
133
|
+
if rtype not in _HANDLED_TYPES:
|
|
134
|
+
results.append({
|
|
135
|
+
**criterion,
|
|
136
|
+
"criterion_index": idx,
|
|
137
|
+
"skipped": True,
|
|
138
|
+
"justification": f"type {rtype!r} not handled by verify_sandbox",
|
|
139
|
+
})
|
|
140
|
+
continue
|
|
141
|
+
|
|
142
|
+
try:
|
|
143
|
+
outcome = await self._eval_criterion(sandbox, container, criterion)
|
|
144
|
+
except TimeoutError as e:
|
|
145
|
+
outcome = _outcome(False, str(e))
|
|
146
|
+
except Exception as e:
|
|
147
|
+
logger.warning(f"criterion #{idx} ({rtype}) evaluator raised: {e}")
|
|
148
|
+
outcome = _outcome(False, f"evaluator error: {e!s}"[:300])
|
|
149
|
+
|
|
150
|
+
results.append({
|
|
151
|
+
**criterion,
|
|
152
|
+
"criterion_index": idx,
|
|
153
|
+
"score": float(outcome["score"]),
|
|
154
|
+
"result": bool(outcome["passed"]),
|
|
155
|
+
"justification": outcome["justification"],
|
|
156
|
+
"skipped": False,
|
|
157
|
+
})
|
|
158
|
+
|
|
159
|
+
# Aggregate over only the rows we actually evaluated.
|
|
160
|
+
non_skipped = [r for r in results if not r.get("skipped")]
|
|
161
|
+
score = aggregate_score(non_skipped, self.score_aggregator)
|
|
162
|
+
|
|
163
|
+
if "verifications" not in context.metadata:
|
|
164
|
+
context.metadata["verifications"] = {}
|
|
165
|
+
context.metadata["verifications"][self.verifier_id] = {
|
|
166
|
+
"results": results,
|
|
167
|
+
"score": score,
|
|
168
|
+
}
|
|
169
|
+
logger.info(
|
|
170
|
+
f"Verification '{self.verifier_id}': "
|
|
171
|
+
f"{len(non_skipped)}/{len(self.criteria)} criteria evaluated, score={score}"
|
|
172
|
+
)
|
|
173
|
+
return context
|
|
174
|
+
|
|
175
|
+
async def _agent_sandbox(self, context: TaskStepContext):
|
|
176
|
+
agent = next(
|
|
177
|
+
(a for a in context.deployed_agents if a.agent_name == self.agent_name),
|
|
178
|
+
None,
|
|
179
|
+
)
|
|
180
|
+
if agent is None:
|
|
181
|
+
raise RuntimeError(f"Agent '{self.agent_name}' not found in context.deployed_agents")
|
|
182
|
+
if not agent.sandbox_id:
|
|
183
|
+
raise RuntimeError(f"Agent '{self.agent_name}' has no sandbox_id")
|
|
184
|
+
provider = (
|
|
185
|
+
build_sandbox_provider(agent.sandbox_type)
|
|
186
|
+
if agent.sandbox_type
|
|
187
|
+
else get_agent_sandbox_provider()
|
|
188
|
+
)
|
|
189
|
+
return await provider.get_sandbox(agent.sandbox_id)
|
|
190
|
+
|
|
191
|
+
async def _deployed_sandbox(self, context: TaskStepContext):
|
|
192
|
+
deployed = next(
|
|
193
|
+
(s for s in context.deployed_sandboxes if s.sandbox_name == self.sandbox_name),
|
|
194
|
+
None,
|
|
195
|
+
)
|
|
196
|
+
if deployed is None:
|
|
197
|
+
raise RuntimeError(
|
|
198
|
+
f"Sandbox '{self.sandbox_name}' not found in context.deployed_sandboxes "
|
|
199
|
+
f"(deployed: {[s.sandbox_name for s in context.deployed_sandboxes]})"
|
|
200
|
+
)
|
|
201
|
+
provider = (
|
|
202
|
+
build_sandbox_provider(deployed.sandbox_type)
|
|
203
|
+
if deployed.sandbox_type
|
|
204
|
+
else get_sandbox_provider()
|
|
205
|
+
)
|
|
206
|
+
return await provider.get_sandbox(deployed.sandbox_id)
|
|
207
|
+
|
|
208
|
+
async def _eval_criterion(self, sandbox, container: Optional[str], criterion: dict) -> dict:
|
|
209
|
+
rtype = criterion["type"]
|
|
210
|
+
if rtype == "probe_file_exists":
|
|
211
|
+
return await self._eval_paths_exist(sandbox, container, criterion.get("paths") or [], "-e")
|
|
212
|
+
if rtype == "probe_dir_exists":
|
|
213
|
+
return await self._eval_paths_exist(sandbox, container, criterion.get("paths") or [], "-d")
|
|
214
|
+
if rtype == "probe_file_contains":
|
|
215
|
+
paths = criterion.get("paths") or []
|
|
216
|
+
needle = criterion.get("expected") or criterion.get("value") or ""
|
|
217
|
+
return await self._eval_file_contains(
|
|
218
|
+
sandbox, container, paths[0] if paths else "", needle,
|
|
219
|
+
)
|
|
220
|
+
if rtype == "bash_cmd_succeeds":
|
|
221
|
+
return await self._eval_shell(sandbox, container, criterion.get("bash_cmd") or "")
|
|
222
|
+
raise RuntimeError(f"unhandled criterion type {rtype}")
|
|
223
|
+
|
|
224
|
+
@staticmethod
|
|
225
|
+
def _probe_args(sandbox, container: Optional[str], cmd: tuple[str, ...]) -> tuple[str, ...]:
|
|
226
|
+
if container is not None:
|
|
227
|
+
return ("sudo", "docker", "exec", container, *cmd)
|
|
228
|
+
if sandbox.mode == SANDBOX_MODE_VM:
|
|
229
|
+
return ("sudo", *cmd)
|
|
230
|
+
return cmd
|
|
231
|
+
|
|
232
|
+
def _resolve_path(self, path: str) -> str:
|
|
233
|
+
return path if path.startswith("/") else f"{self.base_dir.rstrip('/')}/{path}"
|
|
234
|
+
|
|
235
|
+
async def _exec(self, sandbox, args: tuple[str, ...], doing: str = "") -> tuple[int, str, str]:
|
|
236
|
+
"""Wrap exec_with_output with the per-rubric shell timeout."""
|
|
237
|
+
try:
|
|
238
|
+
return await asyncio.wait_for(sandbox.exec_with_output(*args), timeout=self.shell_timeout_seconds)
|
|
239
|
+
except TimeoutError:
|
|
240
|
+
what = f"timed out {doing}" if doing else "timed out"
|
|
241
|
+
raise TimeoutError(f"{what} after {self.shell_timeout_seconds}s") from None
|
|
242
|
+
|
|
243
|
+
async def _eval_paths_exist(
|
|
244
|
+
self, sandbox, container: Optional[str], paths: list[str], test_flag: str,
|
|
245
|
+
) -> dict:
|
|
246
|
+
if not paths:
|
|
247
|
+
return _outcome(False, "no paths specified")
|
|
248
|
+
missing: list[str] = []
|
|
249
|
+
for p in paths:
|
|
250
|
+
args = self._probe_args(sandbox, container, ("test", test_flag, self._resolve_path(p)))
|
|
251
|
+
exit_code, _, _ = await self._exec(sandbox, args, doing=f"checking {p}")
|
|
252
|
+
if exit_code != 0:
|
|
253
|
+
missing.append(p)
|
|
254
|
+
if missing:
|
|
255
|
+
return _outcome(False, f"Missing: {missing}")
|
|
256
|
+
return _outcome(True, "All paths exist")
|
|
257
|
+
|
|
258
|
+
async def _eval_file_contains(
|
|
259
|
+
self, sandbox, container: Optional[str], path: str, needle: str,
|
|
260
|
+
) -> dict:
|
|
261
|
+
if not path:
|
|
262
|
+
return _outcome(False, "no path")
|
|
263
|
+
args = self._probe_args(sandbox, container, ("cat", self._resolve_path(path)))
|
|
264
|
+
exit_code, stdout, stderr = await self._exec(sandbox, args, doing=f"reading {path}")
|
|
265
|
+
if exit_code != 0:
|
|
266
|
+
return _outcome(False, f"could not read {path}: {stderr[:100]}")
|
|
267
|
+
try:
|
|
268
|
+
found = bool(re.search(needle, stdout))
|
|
269
|
+
except re.error as e:
|
|
270
|
+
return _outcome(False, f"invalid regex pattern {needle!r}: {e}")
|
|
271
|
+
return _outcome(found, ("contains" if found else "does not contain") + f" {needle!r}")
|
|
272
|
+
|
|
273
|
+
async def _eval_shell(
|
|
274
|
+
self, sandbox, container: Optional[str], bash_cmd: str,
|
|
275
|
+
) -> dict:
|
|
276
|
+
if not bash_cmd:
|
|
277
|
+
return _outcome(False, "no bash_cmd")
|
|
278
|
+
if container is not None:
|
|
279
|
+
args = (
|
|
280
|
+
"sudo", "docker", "exec", "-w", self.base_dir, container,
|
|
281
|
+
"bash", "-c", bash_cmd,
|
|
282
|
+
)
|
|
283
|
+
else:
|
|
284
|
+
args = self._probe_args(
|
|
285
|
+
sandbox, None, ("bash", "-c", f"cd {shlex.quote(self.base_dir)} && ({bash_cmd}\n)"),
|
|
286
|
+
)
|
|
287
|
+
exit_code, _, stderr = await self._exec(sandbox, args)
|
|
288
|
+
return _outcome(exit_code == 0, f"exit={exit_code}; stderr={stderr[:200]}")
|
|
289
|
+
|
|
290
|
+
async def _discover_container(self, sandbox) -> str:
|
|
291
|
+
"""Find the agent container on a VM sandbox. Mirrors collect_artifacts._discover_container."""
|
|
292
|
+
exit_code, stdout, stderr = await sandbox.exec_with_output(
|
|
293
|
+
"sudo", "docker", "ps", "--format", "{{.Names}}",
|
|
294
|
+
)
|
|
295
|
+
if exit_code != 0:
|
|
296
|
+
raise RuntimeError(f"Failed to list containers: {stderr[:300]}")
|
|
297
|
+
running = [n.strip() for n in stdout.splitlines() if n.strip()]
|
|
298
|
+
if sandbox.container_name in running:
|
|
299
|
+
return sandbox.container_name
|
|
300
|
+
fallback = [n for n in running if n.startswith("a2a-agent-")]
|
|
301
|
+
if fallback:
|
|
302
|
+
if len(fallback) > 1:
|
|
303
|
+
logger.warning(f"Multiple a2a-agent-* containers found; using first: {fallback}")
|
|
304
|
+
return fallback[0]
|
|
305
|
+
raise RuntimeError(
|
|
306
|
+
f"No agent container found on the VM (looked for 'agent-api' or 'a2a-agent-*'). "
|
|
307
|
+
f"Running containers: {running}."
|
|
308
|
+
)
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"""Blocking work handed to a worker thread and not abandoned halfway when its caller is cancelled."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import functools
|
|
7
|
+
import logging
|
|
8
|
+
import threading
|
|
9
|
+
from collections.abc import Callable
|
|
10
|
+
from typing import Optional, TypeVar
|
|
11
|
+
|
|
12
|
+
logger = logging.getLogger(__name__)
|
|
13
|
+
|
|
14
|
+
T = TypeVar("T")
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
async def finish_on_thread(
|
|
18
|
+
work: Callable[[], T], what: str, *, if_never_run: Optional[Callable[[], None]] = None
|
|
19
|
+
) -> T:
|
|
20
|
+
"""Run ``work`` on a worker thread and return its result. Cancelling the caller raises at once,
|
|
21
|
+
as for ``asyncio.to_thread``, but does not stop ``work``: it runs to its end, so whatever it
|
|
22
|
+
owns (a temp file it uploads, say) is released by it and not removed under it, and its outcome
|
|
23
|
+
is logged. ``if_never_run`` releases what ``work`` would have, if the loop shuts down before
|
|
24
|
+
a thread takes it."""
|
|
25
|
+
claim = threading.Lock()
|
|
26
|
+
|
|
27
|
+
def claimed() -> T:
|
|
28
|
+
if not claim.acquire(blocking=False):
|
|
29
|
+
raise asyncio.CancelledError()
|
|
30
|
+
return work()
|
|
31
|
+
|
|
32
|
+
job = asyncio.ensure_future(asyncio.to_thread(claimed))
|
|
33
|
+
job.add_done_callback(functools.partial(_if_the_loop_shut_down, what, claim, if_never_run))
|
|
34
|
+
try:
|
|
35
|
+
return await asyncio.shield(job)
|
|
36
|
+
except asyncio.CancelledError:
|
|
37
|
+
job.add_done_callback(functools.partial(_log_outcome, what))
|
|
38
|
+
raise
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _if_the_loop_shut_down(
|
|
42
|
+
what: str, claim: threading.Lock, release: Optional[Callable[[], None]], job: asyncio.Future
|
|
43
|
+
) -> None:
|
|
44
|
+
"""A loop that shuts down cancels the job whether or not a thread has taken ``work``."""
|
|
45
|
+
if not job.cancelled():
|
|
46
|
+
return
|
|
47
|
+
if claim.acquire(blocking=False):
|
|
48
|
+
logger.warning("%s did not run: its caller was cancelled and the event loop closed", what)
|
|
49
|
+
if release is not None:
|
|
50
|
+
release()
|
|
51
|
+
else:
|
|
52
|
+
logger.warning("%s was still running when the event loop closed; its thread runs it to its end", what)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _log_outcome(what: str, job: asyncio.Future) -> None:
|
|
56
|
+
if job.cancelled():
|
|
57
|
+
return
|
|
58
|
+
if job.exception() is not None:
|
|
59
|
+
logger.warning("%s failed after its caller was cancelled: %s", what, job.exception())
|
|
60
|
+
else:
|
|
61
|
+
logger.info("%s finished after its caller was cancelled", what)
|
|
File without changes
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
"""Derive an env name from ``@environment_card(name=...)`` declarations (import-light: the hub imports this)."""
|
|
2
|
+
|
|
3
|
+
import ast
|
|
4
|
+
import posixpath
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
import httpx
|
|
8
|
+
|
|
9
|
+
def card_name_from_source(dockerfile: str, context: str | None) -> str | None:
|
|
10
|
+
"""Derive the env name by statically reading `@environment_card(name="...")` from the
|
|
11
|
+
server's source — the Dockerfile's own directory (where the server's source lives),
|
|
12
|
+
falling back to the build context. Nothing is built or run.
|
|
13
|
+
|
|
14
|
+
Returns the single declared card name, or None when the source declares none, uses a
|
|
15
|
+
non-literal name, or is ambiguous (several distinct names) — the caller then requires
|
|
16
|
+
an explicit --environment-name.
|
|
17
|
+
"""
|
|
18
|
+
names = _scan_environment_card_names(Path(dockerfile).resolve().parent)
|
|
19
|
+
if not names and context:
|
|
20
|
+
names = _scan_environment_card_names(Path(context).resolve())
|
|
21
|
+
return names[0] if len(names) == 1 else None
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def card_name_from_github(
|
|
25
|
+
dockerfile_github_url: str, context_github_url: str | None = None, *, github_token: str | None = None
|
|
26
|
+
) -> str | None:
|
|
27
|
+
"""The GitHub analogue of `card_name_from_source`: fetch the `.py` files in the Dockerfile's
|
|
28
|
+
GitHub directory (Contents API, authenticated with ``github_token`` when one is given) and read the single
|
|
29
|
+
`@environment_card(name="...")`. Any failure (bad URL, API/auth error, none, or ambiguous)
|
|
30
|
+
returns None so the caller falls back to requiring --environment-name.
|
|
31
|
+
"""
|
|
32
|
+
try:
|
|
33
|
+
from agent_env.artifact.artifacts.docker_image import DockerImageArtifact
|
|
34
|
+
|
|
35
|
+
parts = DockerImageArtifact._parse_github_url(dockerfile_github_url)
|
|
36
|
+
if not parts.path:
|
|
37
|
+
return None
|
|
38
|
+
headers = {"Accept": "application/vnd.github+json"}
|
|
39
|
+
if github_token:
|
|
40
|
+
headers["Authorization"] = f"Bearer {github_token}"
|
|
41
|
+
with httpx.Client(timeout=20, headers=headers, follow_redirects=True) as client:
|
|
42
|
+
names = _github_card_names(client, parts.owner, parts.repo, parts.ref, posixpath.dirname(parts.path))
|
|
43
|
+
if not names and context_github_url:
|
|
44
|
+
cparts = DockerImageArtifact._parse_github_url(context_github_url)
|
|
45
|
+
if cparts.path is not None:
|
|
46
|
+
names = _github_card_names(client, cparts.owner, cparts.repo, cparts.ref, cparts.path)
|
|
47
|
+
return names[0] if len(names) == 1 else None
|
|
48
|
+
except Exception:
|
|
49
|
+
return None
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _github_card_names(client: httpx.Client, owner: str, repo: str, ref: str | None, directory: str) -> list[str]:
|
|
53
|
+
ref_q = f"?ref={ref}" if ref else ""
|
|
54
|
+
resp = client.get(f"https://api.github.com/repos/{owner}/{repo}/contents/{directory}{ref_q}")
|
|
55
|
+
resp.raise_for_status()
|
|
56
|
+
entries = resp.json()
|
|
57
|
+
if not isinstance(entries, list):
|
|
58
|
+
return []
|
|
59
|
+
found: set[str] = set()
|
|
60
|
+
for entry in entries:
|
|
61
|
+
name = entry.get("name") or ""
|
|
62
|
+
if entry.get("type") == "dir":
|
|
63
|
+
found |= set(_github_card_names(client, owner, repo, ref, entry["path"]))
|
|
64
|
+
elif entry.get("type") == "file" and name.endswith(".py") and "test" not in name:
|
|
65
|
+
download_url = entry.get("download_url")
|
|
66
|
+
if download_url:
|
|
67
|
+
found |= _card_names_in_source(client.get(download_url).text)
|
|
68
|
+
return sorted(found)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _scan_environment_card_names(root: Path) -> list[str]:
|
|
72
|
+
found: set[str] = set()
|
|
73
|
+
for py in root.rglob("*.py"):
|
|
74
|
+
try:
|
|
75
|
+
text = py.read_text(encoding="utf-8")
|
|
76
|
+
except (OSError, UnicodeDecodeError):
|
|
77
|
+
continue
|
|
78
|
+
found |= _card_names_in_source(text)
|
|
79
|
+
return sorted(found)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _card_names_in_source(text: str) -> set[str]:
|
|
83
|
+
if "environment_card" not in text:
|
|
84
|
+
return set()
|
|
85
|
+
try:
|
|
86
|
+
tree = ast.parse(text)
|
|
87
|
+
except SyntaxError:
|
|
88
|
+
return set()
|
|
89
|
+
found: set[str] = set()
|
|
90
|
+
for node in ast.walk(tree):
|
|
91
|
+
if isinstance(node, ast.ClassDef):
|
|
92
|
+
for decorator in node.decorator_list:
|
|
93
|
+
if name := _environment_card_name(decorator):
|
|
94
|
+
found.add(name)
|
|
95
|
+
return found
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _environment_card_name(decorator: ast.expr) -> str | None:
|
|
99
|
+
if not isinstance(decorator, ast.Call):
|
|
100
|
+
return None
|
|
101
|
+
func = decorator.func
|
|
102
|
+
fname = func.id if isinstance(func, ast.Name) else func.attr if isinstance(func, ast.Attribute) else None
|
|
103
|
+
if fname != "environment_card":
|
|
104
|
+
return None
|
|
105
|
+
for kw in decorator.keywords:
|
|
106
|
+
if kw.arg == "name" and isinstance(kw.value, ast.Constant) and isinstance(kw.value.value, str):
|
|
107
|
+
return kw.value.value
|
|
108
|
+
return None
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
"""Deprecation shims for the service_* -> environment_* rename.
|
|
2
|
+
|
|
3
|
+
Two things make this less trivial than ``warnings.warn``:
|
|
4
|
+
|
|
5
|
+
1. ``DeprecationWarning`` is invisible in production. CPython's default filters are
|
|
6
|
+
``default::DeprecationWarning:__main__`` then ``ignore``, and nothing in agent_env is ever
|
|
7
|
+
``__main__`` under the ``agent-env`` console script. So the countable channel is a structured
|
|
8
|
+
log line, not the warning — the worker's JSON root handler promotes ``extra=`` keys to Datadog
|
|
9
|
+
facets, which is what the removal gate reads. The warning is emitted too, for interactive
|
|
10
|
+
users and pytest's ``-W error``.
|
|
11
|
+
|
|
12
|
+
2. The alias must preserve OBJECT IDENTITY. A subclass alias would break ``isinstance`` against the
|
|
13
|
+
canonical class at ~20 sites in this repo plus the hub backend's universe_snapshot filters, where
|
|
14
|
+
the failure is an empty list rather than an exception. Hence PEP-562 module ``__getattr__``:
|
|
15
|
+
the only mechanism giving identity, a warning hook, and a counter simultaneously.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import logging
|
|
21
|
+
import warnings
|
|
22
|
+
from typing import Any, Callable
|
|
23
|
+
|
|
24
|
+
logger = logging.getLogger(__name__)
|
|
25
|
+
|
|
26
|
+
_DEPRECATION_EVENT = "agent_env_deprecated_symbol"
|
|
27
|
+
|
|
28
|
+
# Fired symbols, so a hot import path costs one log line per process rather than one per call.
|
|
29
|
+
# Also what the tests reset between cases; see reset_deprecation_state.
|
|
30
|
+
_fired: set[str] = set()
|
|
31
|
+
_counts: dict[str, int] = {}
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def warn_deprecated(old: str, new: str, *, kind: str = "symbol", stacklevel: int = 3) -> None:
|
|
35
|
+
"""Record one use of a deprecated name. At most one warning per symbol per process.
|
|
36
|
+
|
|
37
|
+
``stacklevel`` 3 fits a module ``__getattr__`` shim; a helper called directly by the
|
|
38
|
+
deprecated boundary is one frame deeper and passes 4 so the warning names the caller."""
|
|
39
|
+
_counts[old] = _counts.get(old, 0) + 1
|
|
40
|
+
if old in _fired:
|
|
41
|
+
return
|
|
42
|
+
_fired.add(old)
|
|
43
|
+
message = f"{old} is deprecated and will be removed in a future release; use {new}"
|
|
44
|
+
warnings.warn(message, DeprecationWarning, stacklevel=stacklevel)
|
|
45
|
+
logger.warning(
|
|
46
|
+
message,
|
|
47
|
+
extra={"event": _DEPRECATION_EVENT, "deprecated_symbol": old, "replacement": new, "kind": kind},
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def deprecated_names(mapping: dict[str, Any], *, kind: str = "symbol") -> Callable[[str], Any]:
|
|
52
|
+
"""Build a module ``__getattr__`` serving ``{old_name: canonical_object}`` with a warning.
|
|
53
|
+
|
|
54
|
+
Returns the canonical object itself, so ``OldName is NewName`` holds and isinstance,
|
|
55
|
+
pydantic discriminated deserialization and ``mock.patch(..., spec=)`` all keep working.
|
|
56
|
+
"""
|
|
57
|
+
replacements = {old: getattr(obj, "__name__", str(obj)) for old, obj in mapping.items()}
|
|
58
|
+
|
|
59
|
+
def __getattr__(name: str) -> Any:
|
|
60
|
+
if name in mapping:
|
|
61
|
+
warn_deprecated(name, replacements[name], kind=kind)
|
|
62
|
+
return mapping[name]
|
|
63
|
+
raise AttributeError(f"module has no attribute {name!r}")
|
|
64
|
+
|
|
65
|
+
return __getattr__
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def deprecated_alias(canonical: Callable, old_qualname: str) -> Callable:
|
|
69
|
+
"""A delegating alias for a renamed method or function.
|
|
70
|
+
|
|
71
|
+
Must produce a REAL attribute rather than a ``__getattr__`` fallback, because
|
|
72
|
+
``cli/env/multi.py:107,149`` gate on ``hasattr(env, "load_environment_universe_artifact")``
|
|
73
|
+
and print a "not supported" message on a miss — so a half-present alias degrades to a
|
|
74
|
+
silent no-op instead of an AttributeError.
|
|
75
|
+
"""
|
|
76
|
+
import functools
|
|
77
|
+
import inspect
|
|
78
|
+
|
|
79
|
+
new_name = canonical.__name__
|
|
80
|
+
old_short = old_qualname.rsplit(".", 1)[-1]
|
|
81
|
+
|
|
82
|
+
if inspect.iscoroutinefunction(canonical):
|
|
83
|
+
@functools.wraps(canonical)
|
|
84
|
+
async def _alias(*args: Any, **kwargs: Any) -> Any:
|
|
85
|
+
warn_deprecated(old_qualname, new_name, kind="method")
|
|
86
|
+
return await canonical(*args, **kwargs)
|
|
87
|
+
else:
|
|
88
|
+
@functools.wraps(canonical)
|
|
89
|
+
def _alias(*args: Any, **kwargs: Any) -> Any:
|
|
90
|
+
warn_deprecated(old_qualname, new_name, kind="method")
|
|
91
|
+
return canonical(*args, **kwargs)
|
|
92
|
+
|
|
93
|
+
_alias.__name__ = old_short
|
|
94
|
+
_alias.__qualname__ = old_qualname
|
|
95
|
+
_alias.__doc__ = f"Deprecated alias for :meth:`{new_name}`. Scheduled for removal."
|
|
96
|
+
return _alias
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def deprecation_counts() -> dict[str, int]:
|
|
100
|
+
"""Per-symbol hit counts for this process. The removal gate reads the Datadog facet, not this."""
|
|
101
|
+
return dict(_counts)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def reset_deprecation_state() -> None:
|
|
105
|
+
"""Test hook. pytest's monkeypatch materializes a shimmed name into the module ``__dict__``
|
|
106
|
+
on undo, permanently disabling ``__getattr__`` for that name in the worker — so suites that
|
|
107
|
+
patch a deprecated alias must also pop it. See tst/unit/conftest.py."""
|
|
108
|
+
_fired.clear()
|
|
109
|
+
_counts.clear()
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"""Build a Docker image on this machine, the one way every put command and bundle writer does it."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import subprocess
|
|
6
|
+
from collections.abc import Mapping
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
DEFAULT_BUILD_PLATFORM = "linux/amd64" # the remote sandbox VMs
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class DockerBuildError(RuntimeError):
|
|
13
|
+
"""A local ``docker build`` that failed or couldn't start; the message carries docker's output."""
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def build_image(dockerfile: Path, context: Path, tag: str, *, platform: str | None,
|
|
17
|
+
build_args: Mapping[str, str] | None = None) -> None:
|
|
18
|
+
"""Build ``context`` with ``dockerfile`` into the local image ``tag``, for ``platform``, or for this host's
|
|
19
|
+
platform when it's None or empty. Raises DockerBuildError, with the build's output, when it fails."""
|
|
20
|
+
argv = ["docker", "build", *(["--platform", platform] if platform else [])]
|
|
21
|
+
for name, value in (build_args or {}).items():
|
|
22
|
+
argv += ["--build-arg", f"{name}={value}"]
|
|
23
|
+
argv += ["-f", str(dockerfile), "-t", tag, str(context)]
|
|
24
|
+
try:
|
|
25
|
+
result = subprocess.run(argv, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, errors="replace")
|
|
26
|
+
except FileNotFoundError as e:
|
|
27
|
+
raise DockerBuildError(f"docker build of {tag} failed: docker is not on PATH") from e
|
|
28
|
+
if result.returncode != 0:
|
|
29
|
+
raise DockerBuildError(f"docker build of {tag} failed (exit {result.returncode}):\n{result.stdout.rstrip()}")
|