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,461 @@
|
|
|
1
|
+
"""Run a Python script in a deployed sandbox and store its JSON result.
|
|
2
|
+
|
|
3
|
+
The script defines ``run(input) -> JSON``, where ``input = {"args", "results"}``.
|
|
4
|
+
The result is stored at ``context.metadata["script_results"][result_id]``.
|
|
5
|
+
|
|
6
|
+
``script_artifact_id`` is either a single-file ``FileArtifact`` or a
|
|
7
|
+
``FileArtifactUniverse`` whose ``.py`` members are staged side by side so the entry
|
|
8
|
+
file can import its siblings; non-``.py`` members are skipped. ``script_file`` names
|
|
9
|
+
the entry, defaulting to the sole ``.py`` member or to ``run.py``.
|
|
10
|
+
|
|
11
|
+
Target: with ``env_id`` set, the script runs on that env's VM host (no agent, no
|
|
12
|
+
LLM key); otherwise it runs inside the agent container (``agent_name``), where it
|
|
13
|
+
can see the agent's workspace.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import asyncio
|
|
19
|
+
import json
|
|
20
|
+
import logging
|
|
21
|
+
import os
|
|
22
|
+
import shlex
|
|
23
|
+
from dataclasses import dataclass
|
|
24
|
+
from pathlib import Path, PurePosixPath
|
|
25
|
+
from typing import Any, ClassVar, Optional, Protocol
|
|
26
|
+
|
|
27
|
+
from agent_env.artifact import Artifact, FileArtifact
|
|
28
|
+
from agent_env.artifact.artifacts.file_artifact_universe import FileArtifactUniverse
|
|
29
|
+
from agent_env.env.env import require_sandbox
|
|
30
|
+
from agent_env.task_step.context import TaskStepContext
|
|
31
|
+
from agent_env.entity_refs import EntityRef
|
|
32
|
+
from agent_env.task_step.task_step import TaskStep, TaskStepDependency
|
|
33
|
+
|
|
34
|
+
logger = logging.getLogger(__name__)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
_RUN_DIR = "/tmp/agent_env_run_code"
|
|
38
|
+
|
|
39
|
+
# The bootstrap we run in the sandbox: `python3 runner.py <run_dir> <entrypoint> <script_file>`.
|
|
40
|
+
_RUNNER_SOURCE = (Path(__file__).parent / "run_code_runner.py").read_text(encoding="utf-8")
|
|
41
|
+
|
|
42
|
+
# A universe member with one of these names would shadow run_code's own staging files.
|
|
43
|
+
_RESERVED_MEMBERS = frozenset({"runner.py", "input.json", "output.json"})
|
|
44
|
+
|
|
45
|
+
# Where a single-file FileArtifact is always staged, regardless of its own filename.
|
|
46
|
+
_STAGED_SCRIPT = "script.py"
|
|
47
|
+
|
|
48
|
+
class RunCodeValidationError(ValueError):
|
|
49
|
+
"""Bad step config or malformed/oversized script output."""
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class RunCodeExecutionError(Exception):
|
|
53
|
+
"""Script crashed, timed out, or otherwise failed to run."""
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class RunCodeTaskStep(TaskStep):
|
|
57
|
+
type: ClassVar[str] = "run_code"
|
|
58
|
+
entity_refs = (
|
|
59
|
+
EntityRef.artifact("script_artifact_id", version_field="script_artifact_version"),
|
|
60
|
+
EntityRef.env("env_id"),
|
|
61
|
+
)
|
|
62
|
+
DEFAULT_ENTRYPOINT: ClassVar[str] = "run"
|
|
63
|
+
DEFAULT_TIMEOUT_SECONDS: ClassVar[int] = 600
|
|
64
|
+
MAX_OUTPUT_BYTES: ClassVar[int] = 50 * 1024 * 1024
|
|
65
|
+
MAX_SCRIPT_BYTES: ClassVar[int] = 5 * 1024 * 1024 # total .py bytes staged from a universe
|
|
66
|
+
# Not an __init__ default (script_file defaults to None) — the universe entry
|
|
67
|
+
# chosen when several .py members exist.
|
|
68
|
+
ENTRY_WHEN_AMBIGUOUS: ClassVar[str] = "run.py"
|
|
69
|
+
_TIMEOUT_EXIT_CODE: ClassVar[int] = 124 # `timeout` coreutil convention
|
|
70
|
+
_STDERR_TRUNCATE: ClassVar[int] = 1000 # max stderr chars surfaced in errors
|
|
71
|
+
# A collect_artifacts universe can hold hundreds of non-.py members; name a few.
|
|
72
|
+
_SKIPPED_MEMBERS_LOGGED: ClassVar[int] = 10
|
|
73
|
+
|
|
74
|
+
# from_dict forwards these as-is; __init__ owns per-field defaulting.
|
|
75
|
+
_SERIALIZED_FIELDS: ClassVar[tuple[str, ...]] = (
|
|
76
|
+
"script_artifact_id",
|
|
77
|
+
"script_artifact_version",
|
|
78
|
+
"script_file",
|
|
79
|
+
"entrypoint",
|
|
80
|
+
"args",
|
|
81
|
+
"result_id",
|
|
82
|
+
"timeout_seconds",
|
|
83
|
+
"env_id",
|
|
84
|
+
"agent_name",
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
def __init__(
|
|
88
|
+
self,
|
|
89
|
+
id: str,
|
|
90
|
+
version: Optional[int],
|
|
91
|
+
# --- step-specific fields ---
|
|
92
|
+
script_artifact_id: str,
|
|
93
|
+
entrypoint: str = DEFAULT_ENTRYPOINT,
|
|
94
|
+
script_artifact_version: Optional[int] = None,
|
|
95
|
+
script_file: Optional[str] = None,
|
|
96
|
+
args: Optional[dict] = None,
|
|
97
|
+
result_id: Optional[str] = None,
|
|
98
|
+
timeout_seconds: Optional[int] = None,
|
|
99
|
+
env_id: Optional[str] = None,
|
|
100
|
+
agent_name: Optional[str] = None,
|
|
101
|
+
# --- base TaskStep params ---
|
|
102
|
+
depends_on: Optional[list[TaskStepDependency]] = None,
|
|
103
|
+
fail_task_on_error: bool = True,
|
|
104
|
+
):
|
|
105
|
+
super().__init__(id, version, depends_on=depends_on, fail_task_on_error=fail_task_on_error)
|
|
106
|
+
self.script_artifact_id = script_artifact_id
|
|
107
|
+
self.script_artifact_version = script_artifact_version
|
|
108
|
+
# Universe-only; rejected at resolve time for a single-file FileArtifact.
|
|
109
|
+
self.script_file = script_file
|
|
110
|
+
self.entrypoint = entrypoint or self.DEFAULT_ENTRYPOINT
|
|
111
|
+
self.args = args or {}
|
|
112
|
+
self.result_id = result_id or id
|
|
113
|
+
self.timeout_seconds = timeout_seconds or self.DEFAULT_TIMEOUT_SECONDS
|
|
114
|
+
# `env_id` set → host mode (no agent); otherwise agent mode via `agent_name`.
|
|
115
|
+
self.env_id = env_id
|
|
116
|
+
self.agent_name = agent_name or self.DEFAULT_AGENT_NAME
|
|
117
|
+
|
|
118
|
+
def to_dict(self) -> dict:
|
|
119
|
+
base = super().to_dict()
|
|
120
|
+
base.update({f: getattr(self, f) for f in self._SERIALIZED_FIELDS})
|
|
121
|
+
return base
|
|
122
|
+
|
|
123
|
+
@classmethod
|
|
124
|
+
def from_dict(cls, data: dict) -> "RunCodeTaskStep":
|
|
125
|
+
return cls(
|
|
126
|
+
**cls._base_from_dict(data),
|
|
127
|
+
**{f: data[f] for f in cls._SERIALIZED_FIELDS if f in data},
|
|
128
|
+
)
|
|
129
|
+
|
|
130
|
+
def preflight(self) -> list[str]:
|
|
131
|
+
"""Config problems detectable without a sandbox; resolves documents, never content."""
|
|
132
|
+
from agent_env.store.base import NotFoundError
|
|
133
|
+
|
|
134
|
+
# Infra failures (expired creds, unreachable store) are not config problems: propagate.
|
|
135
|
+
try:
|
|
136
|
+
self._resolve_script_artifact()
|
|
137
|
+
except RunCodeValidationError as exc:
|
|
138
|
+
return [str(exc)]
|
|
139
|
+
except NotFoundError:
|
|
140
|
+
return [
|
|
141
|
+
f"run_code '{self.id}': script_artifact '{self.script_artifact_id}' "
|
|
142
|
+
f"(version {self.script_artifact_version or 'latest'}) does not exist"
|
|
143
|
+
]
|
|
144
|
+
return []
|
|
145
|
+
|
|
146
|
+
async def execute(self, context: TaskStepContext) -> TaskStepContext:
|
|
147
|
+
script_file, files = await asyncio.to_thread(self._load_script)
|
|
148
|
+
target = await self._resolve_target(context)
|
|
149
|
+
run_dir = f"{_RUN_DIR}/{self.id}"
|
|
150
|
+
|
|
151
|
+
await self._stage(target, run_dir, files, self._build_input(context))
|
|
152
|
+
await self._run(target, run_dir, script_file)
|
|
153
|
+
result = await self._read_output(target, run_dir)
|
|
154
|
+
|
|
155
|
+
context.metadata.setdefault("script_results", {})[self.result_id] = result
|
|
156
|
+
logger.info(
|
|
157
|
+
"run_code '%s' completed (result_id=%s, target=%s)",
|
|
158
|
+
self.id, self.result_id, "host" if self.env_id else "agent",
|
|
159
|
+
)
|
|
160
|
+
return context
|
|
161
|
+
|
|
162
|
+
# --- execution phases ---
|
|
163
|
+
|
|
164
|
+
def _resolve_script_artifact(self) -> tuple[str, Any]:
|
|
165
|
+
"""Resolve to ``(entry_filename, artifact)``; reads documents only, never content."""
|
|
166
|
+
artifact = Artifact.get(self.script_artifact_id, self.script_artifact_version)
|
|
167
|
+
if isinstance(artifact, FileArtifact):
|
|
168
|
+
if self.script_file:
|
|
169
|
+
raise self._validation_error(
|
|
170
|
+
f"script_file '{self.script_file}' is set but "
|
|
171
|
+
f"'{self.script_artifact_id}' is a single-file FileArtifact; drop "
|
|
172
|
+
f"script_file or point at a FileArtifactUniverse"
|
|
173
|
+
)
|
|
174
|
+
# Never the artifact's filename: a non-.py suffix breaks importlib, and
|
|
175
|
+
# runner.py would be overwritten by the bootstrap.
|
|
176
|
+
return (_STAGED_SCRIPT, artifact)
|
|
177
|
+
if isinstance(artifact, FileArtifactUniverse):
|
|
178
|
+
return (self._pick_entry(_member_names(artifact)), artifact)
|
|
179
|
+
raise self._validation_error(
|
|
180
|
+
f"script_artifact '{self.script_artifact_id}' must be a FileArtifact or "
|
|
181
|
+
f"FileArtifactUniverse, got {type(artifact).__name__}"
|
|
182
|
+
)
|
|
183
|
+
|
|
184
|
+
def _pick_entry(self, members: list[str]) -> str:
|
|
185
|
+
py = self._validated_py_members(members)
|
|
186
|
+
if self.script_file:
|
|
187
|
+
if not self.script_file.endswith(".py"):
|
|
188
|
+
raise self._validation_error(
|
|
189
|
+
f"script_file '{self.script_file}' must be a .py file"
|
|
190
|
+
)
|
|
191
|
+
if self.script_file not in py:
|
|
192
|
+
raise self._validation_error(
|
|
193
|
+
f"script_file '{self.script_file}' is not a .py member of "
|
|
194
|
+
f"'{self.script_artifact_id}'; .py members: {py}"
|
|
195
|
+
)
|
|
196
|
+
return self.script_file
|
|
197
|
+
if not py:
|
|
198
|
+
raise self._validation_error(
|
|
199
|
+
f"script_artifact '{self.script_artifact_id}' has no .py member; "
|
|
200
|
+
f"members: {sorted(members)}"
|
|
201
|
+
)
|
|
202
|
+
if len(py) == 1:
|
|
203
|
+
return py[0]
|
|
204
|
+
# Universe members can be nested paths, so match the entry by basename.
|
|
205
|
+
default = [n for n in py if os.path.basename(n) == self.ENTRY_WHEN_AMBIGUOUS]
|
|
206
|
+
if len(default) == 1:
|
|
207
|
+
return default[0]
|
|
208
|
+
# Two different reasons, and they need different wording: "no single 'run.py'" reads as
|
|
209
|
+
# "there is no run.py" when in fact there are several, sending the author to look for a file
|
|
210
|
+
# that is not missing. The hub's selector already distinguishes these.
|
|
211
|
+
if default:
|
|
212
|
+
raise self._validation_error(
|
|
213
|
+
f"script_artifact '{self.script_artifact_id}' has {len(default)} files named "
|
|
214
|
+
f"'{self.ENTRY_WHEN_AMBIGUOUS}' ({default}), so the default entry is ambiguous; "
|
|
215
|
+
f"set script_file to one of {py}"
|
|
216
|
+
)
|
|
217
|
+
raise self._validation_error(
|
|
218
|
+
f"script_artifact '{self.script_artifact_id}' has {len(py)} .py members "
|
|
219
|
+
f"and no '{self.ENTRY_WHEN_AMBIGUOUS}'; set script_file to one of {py}"
|
|
220
|
+
)
|
|
221
|
+
|
|
222
|
+
def _validated_py_members(self, members: list[str]) -> list[str]:
|
|
223
|
+
"""Reject an unstageable member set; return its sorted ``.py`` members."""
|
|
224
|
+
if not members:
|
|
225
|
+
raise self._validation_error(
|
|
226
|
+
f"script_artifact '{self.script_artifact_id}' is an empty FileArtifactUniverse"
|
|
227
|
+
)
|
|
228
|
+
# Member names are unvalidated on write and can come from agent output; we stage as root.
|
|
229
|
+
unsafe = sorted(n for n in members if not _is_safe_member(n))
|
|
230
|
+
if unsafe:
|
|
231
|
+
raise self._validation_error(
|
|
232
|
+
f"script_artifact '{self.script_artifact_id}' has member name(s) {unsafe} "
|
|
233
|
+
f"that are absolute or escape the staging directory"
|
|
234
|
+
)
|
|
235
|
+
py = sorted(n for n in members if n.endswith(".py"))
|
|
236
|
+
clash = sorted(set(py) & _RESERVED_MEMBERS)
|
|
237
|
+
if clash:
|
|
238
|
+
raise self._validation_error(
|
|
239
|
+
f"script_artifact '{self.script_artifact_id}' has member(s) {clash} "
|
|
240
|
+
f"that would shadow run_code's staging files; rename them"
|
|
241
|
+
)
|
|
242
|
+
return py
|
|
243
|
+
|
|
244
|
+
def _load_script(self) -> tuple[str, dict[str, bytes]]:
|
|
245
|
+
"""Resolve the artifact and load only its ``.py`` members: ``(entry, {name: bytes})``."""
|
|
246
|
+
script_file, artifact = self._resolve_script_artifact()
|
|
247
|
+
if isinstance(artifact, FileArtifact):
|
|
248
|
+
return (script_file, {script_file: artifact.load()})
|
|
249
|
+
|
|
250
|
+
# .py only: these universes are often collect_artifacts output, uncapped and binary.
|
|
251
|
+
members = artifact.get_file_artifacts()
|
|
252
|
+
py = {name: fa for name, fa in members.items() if name.endswith(".py")}
|
|
253
|
+
if script_file not in py:
|
|
254
|
+
# Unreachable unless the universe doc's refs and ids disagree.
|
|
255
|
+
raise self._validation_error(
|
|
256
|
+
f"entry '{script_file}' is missing from the resolved members of "
|
|
257
|
+
f"'{self.script_artifact_id}' ({sorted(members)})"
|
|
258
|
+
)
|
|
259
|
+
files = {name: fa.load() for name, fa in py.items()}
|
|
260
|
+
total = sum(len(b) for b in files.values())
|
|
261
|
+
if total > self.MAX_SCRIPT_BYTES:
|
|
262
|
+
raise self._validation_error(
|
|
263
|
+
f"script_artifact '{self.script_artifact_id}' .py members total "
|
|
264
|
+
f"{total} bytes, over the {self.MAX_SCRIPT_BYTES}-byte staging cap"
|
|
265
|
+
)
|
|
266
|
+
skipped = sorted(set(members) - set(py))
|
|
267
|
+
if skipped:
|
|
268
|
+
logger.info(
|
|
269
|
+
"run_code '%s': staging %d .py member(s); skipped %d non-.py member(s): %s",
|
|
270
|
+
self.id, len(files), len(skipped), skipped[:self._SKIPPED_MEMBERS_LOGGED],
|
|
271
|
+
)
|
|
272
|
+
return (script_file, files)
|
|
273
|
+
|
|
274
|
+
def _build_input(self, context: TaskStepContext) -> dict:
|
|
275
|
+
"""Build the {args, results} input passed to the script."""
|
|
276
|
+
return {
|
|
277
|
+
"args": self.args,
|
|
278
|
+
"results": context.metadata.get("script_results", {}),
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
async def _resolve_target(self, context: TaskStepContext) -> _ExecTarget:
|
|
282
|
+
"""Pick where the script runs: the env's VM host or the agent container."""
|
|
283
|
+
if self.env_id is not None:
|
|
284
|
+
return await self._host_target(context)
|
|
285
|
+
return await self._agent_target(context)
|
|
286
|
+
|
|
287
|
+
async def _stage(
|
|
288
|
+
self, target: _ExecTarget, run_dir: str, files: dict[str, bytes], script_input: dict
|
|
289
|
+
) -> None:
|
|
290
|
+
"""Clear the run dir, then write the script files, the input, and the runner.
|
|
291
|
+
|
|
292
|
+
Sandboxes are reused across reruns and retries: a stale output.json would be
|
|
293
|
+
read back as this run's result, and a stale sibling module would satisfy an import.
|
|
294
|
+
"""
|
|
295
|
+
await target.reset_dir(run_dir)
|
|
296
|
+
for name, content in files.items():
|
|
297
|
+
await target.write_file(f"{run_dir}/{name}", content.decode("utf-8"))
|
|
298
|
+
await target.write_file(f"{run_dir}/input.json", json.dumps(script_input))
|
|
299
|
+
await target.write_file(f"{run_dir}/runner.py", _RUNNER_SOURCE)
|
|
300
|
+
|
|
301
|
+
async def _run(self, target: _ExecTarget, run_dir: str, script_file: str) -> None:
|
|
302
|
+
"""Run the script under a timeout."""
|
|
303
|
+
exit_code, _stdout, stderr = await target.run(
|
|
304
|
+
"timeout", str(self.timeout_seconds),
|
|
305
|
+
"python3", f"{run_dir}/runner.py", run_dir, self.entrypoint, script_file,
|
|
306
|
+
)
|
|
307
|
+
if exit_code == 0:
|
|
308
|
+
return
|
|
309
|
+
reason = (
|
|
310
|
+
f"timed out after {self.timeout_seconds}s"
|
|
311
|
+
if exit_code == self._TIMEOUT_EXIT_CODE
|
|
312
|
+
else f"exited {exit_code}: {stderr[:self._STDERR_TRUNCATE]}"
|
|
313
|
+
)
|
|
314
|
+
raise self._exec_error(reason)
|
|
315
|
+
|
|
316
|
+
async def _read_output(self, target: _ExecTarget, run_dir: str) -> Any:
|
|
317
|
+
"""Read and parse the script's JSON result, enforcing the size cap."""
|
|
318
|
+
# Check the byte size before reading any content: a complete,
|
|
319
|
+
# runner-written file is always valid UTF-8 JSON, so an over-cap result is
|
|
320
|
+
# rejected here rather than slurped into the worker — and we never decode a
|
|
321
|
+
# truncated file (which would crash strict UTF-8 decode mid-codepoint).
|
|
322
|
+
path = f"{run_dir}/output.json"
|
|
323
|
+
exit_code, size_out, stderr = await target.run("wc", "-c", path)
|
|
324
|
+
if exit_code != 0:
|
|
325
|
+
raise self._exec_error(f"wrote no result file: {stderr[:self._STDERR_TRUNCATE]}")
|
|
326
|
+
if int(size_out.split()[0]) > self.MAX_OUTPUT_BYTES:
|
|
327
|
+
raise self._validation_error(
|
|
328
|
+
f"result exceeds {self.MAX_OUTPUT_BYTES}-byte cap"
|
|
329
|
+
)
|
|
330
|
+
exit_code, stdout, stderr = await target.run("cat", path)
|
|
331
|
+
if exit_code != 0:
|
|
332
|
+
raise self._exec_error(f"could not read result file: {stderr[:self._STDERR_TRUNCATE]}")
|
|
333
|
+
try:
|
|
334
|
+
return json.loads(stdout)
|
|
335
|
+
except json.JSONDecodeError as exc:
|
|
336
|
+
raise self._validation_error(f"result is not valid JSON: {exc}") from exc
|
|
337
|
+
|
|
338
|
+
# --- run targets ---
|
|
339
|
+
|
|
340
|
+
async def _host_target(self, context: TaskStepContext) -> _ExecTarget:
|
|
341
|
+
from agent_env.providers.sandbox_providers.sandbox_provider import (
|
|
342
|
+
build_sandbox_provider,
|
|
343
|
+
get_env_sandbox_provider,
|
|
344
|
+
)
|
|
345
|
+
|
|
346
|
+
deployed = next(
|
|
347
|
+
(d for d in context.deployed_envs if d.env_id == self.env_id), None
|
|
348
|
+
)
|
|
349
|
+
if deployed is not None:
|
|
350
|
+
deployed = require_sandbox(deployed, "run_code on the env's host")
|
|
351
|
+
if deployed is None or not deployed.sandbox_id:
|
|
352
|
+
raise RuntimeError(
|
|
353
|
+
f"Env '{self.env_id}' not found in context.deployed_envs "
|
|
354
|
+
"(or missing sandbox_id)"
|
|
355
|
+
)
|
|
356
|
+
# env sandbox provider, honoring a custom sandbox_type
|
|
357
|
+
provider = (
|
|
358
|
+
build_sandbox_provider(deployed.sandbox_type)
|
|
359
|
+
if deployed.sandbox_type
|
|
360
|
+
else get_env_sandbox_provider()
|
|
361
|
+
)
|
|
362
|
+
sandbox = await provider.get_sandbox(deployed.sandbox_id)
|
|
363
|
+
return _HostTarget(sandbox)
|
|
364
|
+
|
|
365
|
+
async def _agent_target(self, context: TaskStepContext) -> _ExecTarget:
|
|
366
|
+
# Runs inside the agent container. VM mode needs `sudo docker exec -u 0`:
|
|
367
|
+
# docker on the host needs sudo, and -u 0 reads the root-owned copied files.
|
|
368
|
+
from agent_env.providers.sandbox_providers.sandbox_provider import (
|
|
369
|
+
SANDBOX_MODE_VM,
|
|
370
|
+
build_sandbox_provider,
|
|
371
|
+
get_agent_sandbox_provider,
|
|
372
|
+
)
|
|
373
|
+
|
|
374
|
+
agent = next(
|
|
375
|
+
(a for a in context.deployed_agents if a.agent_name == self.agent_name), None
|
|
376
|
+
)
|
|
377
|
+
if agent is None or not agent.sandbox_id:
|
|
378
|
+
raise RuntimeError(
|
|
379
|
+
f"Agent '{self.agent_name}' not found in context.deployed_agents "
|
|
380
|
+
"(or missing sandbox_id)"
|
|
381
|
+
)
|
|
382
|
+
provider = build_sandbox_provider(agent.sandbox_type) if agent.sandbox_type else get_agent_sandbox_provider()
|
|
383
|
+
sandbox = await provider.get_sandbox(agent.sandbox_id)
|
|
384
|
+
if agent.on_host:
|
|
385
|
+
# A host-installed agent has no container: stage and run on the VM host, as root.
|
|
386
|
+
return _HostTarget(sandbox)
|
|
387
|
+
prefix = (
|
|
388
|
+
("sudo", "docker", "exec", "-u", "0", sandbox.container_name)
|
|
389
|
+
if sandbox.mode == SANDBOX_MODE_VM
|
|
390
|
+
else ()
|
|
391
|
+
)
|
|
392
|
+
return _AgentTarget(sandbox, prefix)
|
|
393
|
+
|
|
394
|
+
# --- errors ---
|
|
395
|
+
|
|
396
|
+
def _exec_error(self, msg: str) -> RunCodeExecutionError:
|
|
397
|
+
return RunCodeExecutionError(f"run_code '{self.id}': {msg}")
|
|
398
|
+
|
|
399
|
+
def _validation_error(self, msg: str) -> RunCodeValidationError:
|
|
400
|
+
return RunCodeValidationError(f"run_code '{self.id}': {msg}")
|
|
401
|
+
|
|
402
|
+
|
|
403
|
+
# --- module helpers ---
|
|
404
|
+
|
|
405
|
+
|
|
406
|
+
def _member_names(universe: Any) -> list[str]:
|
|
407
|
+
"""Member names in get_file_artifacts' precedence, so preflight sees what execute stages."""
|
|
408
|
+
if universe.file_artifact_refs:
|
|
409
|
+
return list(universe.file_artifact_refs)
|
|
410
|
+
return list(universe.file_artifact_ids or {})
|
|
411
|
+
|
|
412
|
+
|
|
413
|
+
def _is_safe_member(name: str) -> bool:
|
|
414
|
+
"""True when `name` stays inside the staging dir as a relative path."""
|
|
415
|
+
if not name or name.startswith(("/", "~")):
|
|
416
|
+
return False
|
|
417
|
+
return ".." not in PurePosixPath(name).parts
|
|
418
|
+
|
|
419
|
+
|
|
420
|
+
class _ExecTarget(Protocol):
|
|
421
|
+
async def reset_dir(self, path: str) -> None: ...
|
|
422
|
+
async def write_file(self, path: str, content: str) -> None: ...
|
|
423
|
+
async def run(self, *command: str) -> tuple[int, str, str]: ...
|
|
424
|
+
|
|
425
|
+
|
|
426
|
+
@dataclass
|
|
427
|
+
class _HostTarget:
|
|
428
|
+
"""Runs the script on the env's VM host (no agent)."""
|
|
429
|
+
|
|
430
|
+
sandbox: Any
|
|
431
|
+
|
|
432
|
+
async def reset_dir(self, path: str) -> None:
|
|
433
|
+
await self.sandbox.exec_script(
|
|
434
|
+
f"rm -rf {shlex.quote(path)} && mkdir -p {shlex.quote(path)}"
|
|
435
|
+
)
|
|
436
|
+
|
|
437
|
+
async def write_file(self, path: str, content: str) -> None:
|
|
438
|
+
await self.sandbox.write_host_file(content.encode("utf-8"), path)
|
|
439
|
+
|
|
440
|
+
async def run(self, *command: str) -> tuple[int, str, str]:
|
|
441
|
+
# Files are written as root, so run as root too.
|
|
442
|
+
return await self.sandbox.exec_with_output("sudo", *command)
|
|
443
|
+
|
|
444
|
+
|
|
445
|
+
@dataclass
|
|
446
|
+
class _AgentTarget:
|
|
447
|
+
"""Runs the script inside the agent container."""
|
|
448
|
+
|
|
449
|
+
sandbox: Any
|
|
450
|
+
prefix: tuple[str, ...]
|
|
451
|
+
|
|
452
|
+
async def reset_dir(self, path: str) -> None:
|
|
453
|
+
await self.run("rm", "-rf", path)
|
|
454
|
+
await self.run("mkdir", "-p", path)
|
|
455
|
+
|
|
456
|
+
async def write_file(self, path: str, content: str) -> None:
|
|
457
|
+
# write_file_from_text takes (content, path); we expose (path, content).
|
|
458
|
+
await self.sandbox.write_file_from_text(content, path)
|
|
459
|
+
|
|
460
|
+
async def run(self, *command: str) -> tuple[int, str, str]:
|
|
461
|
+
return await self.sandbox.exec_with_output(*self.prefix, *command)
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
"""Bootstrap that run_code writes into the sandbox and runs.
|
|
2
|
+
|
|
3
|
+
Imports the entry script, calls its entrypoint with the JSON input, and writes the
|
|
4
|
+
JSON result. Reads `run_dir`, `entrypoint` and `script_file` from argv.
|
|
5
|
+
|
|
6
|
+
Both the entry script's own directory and `run_dir` go on sys.path, so a multi-file
|
|
7
|
+
artifact can import its siblings whether it is laid out flat or under a subdirectory.
|
|
8
|
+
Stdlib only — it runs in the sandbox, which may not have agent_env installed.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
import importlib.machinery
|
|
12
|
+
import importlib.util
|
|
13
|
+
import json
|
|
14
|
+
import os
|
|
15
|
+
import sys
|
|
16
|
+
|
|
17
|
+
run_dir, entrypoint, script_file = sys.argv[1], sys.argv[2], sys.argv[3]
|
|
18
|
+
|
|
19
|
+
script_path = os.path.join(run_dir, script_file)
|
|
20
|
+
# The entry's own directory first: a nested entry (`src/run.py`) imports siblings by
|
|
21
|
+
# bare name (`import helpers`), which run_dir alone does not resolve. dict.fromkeys
|
|
22
|
+
# collapses the two for a flat layout, where they are the same directory.
|
|
23
|
+
sys.path[:0] = list(dict.fromkeys([os.path.dirname(script_path), run_dir]))
|
|
24
|
+
|
|
25
|
+
# `from .helpers import value` needs the entry to belong to a package, which loading it
|
|
26
|
+
# from a file path alone does not give it. The package is bound to a name we own rather
|
|
27
|
+
# than to the staged directory's own name: importing `os.run` for a member `os/run.py`
|
|
28
|
+
# would find the runner's own already-imported `os` and fail, and a member directory is
|
|
29
|
+
# under no obligation to be a legal module name in the first place.
|
|
30
|
+
_MODULE, _PACKAGE = "agent_env_user_script", "agent_env_user_pkg"
|
|
31
|
+
if os.path.dirname(script_file):
|
|
32
|
+
pkg_dir = os.path.dirname(script_path)
|
|
33
|
+
pkg_spec = importlib.machinery.ModuleSpec(_PACKAGE, None, is_package=True)
|
|
34
|
+
pkg_spec.submodule_search_locations = [pkg_dir]
|
|
35
|
+
sys.modules[_PACKAGE] = importlib.util.module_from_spec(pkg_spec)
|
|
36
|
+
name = f"{_PACKAGE}.{os.path.basename(script_file)[: -len('.py')]}"
|
|
37
|
+
else:
|
|
38
|
+
name = _MODULE
|
|
39
|
+
|
|
40
|
+
spec = importlib.util.spec_from_file_location(name, script_path)
|
|
41
|
+
mod = importlib.util.module_from_spec(spec)
|
|
42
|
+
# Registered before exec so the entry can also be reached as a sibling's import target.
|
|
43
|
+
sys.modules[name] = mod
|
|
44
|
+
spec.loader.exec_module(mod)
|
|
45
|
+
|
|
46
|
+
with open(f"{run_dir}/input.json") as f:
|
|
47
|
+
_input = json.load(f)
|
|
48
|
+
|
|
49
|
+
_result = getattr(mod, entrypoint)(_input)
|
|
50
|
+
|
|
51
|
+
with open(f"{run_dir}/output.json", "w") as f:
|
|
52
|
+
json.dump(_result, f)
|