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,198 @@
|
|
|
1
|
+
"""Backend-agnostic object store abstraction over write-once keyed blobs."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import io
|
|
6
|
+
from abc import ABC, abstractmethod
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from datetime import datetime
|
|
9
|
+
from typing import BinaryIO
|
|
10
|
+
|
|
11
|
+
from agentenv_protocol.transfers import (
|
|
12
|
+
HttpGetGrant,
|
|
13
|
+
HttpPostPolicyGrant,
|
|
14
|
+
HttpPutGrant,
|
|
15
|
+
)
|
|
16
|
+
|
|
17
|
+
DEFAULT_CONTENT_TYPE = "application/octet-stream"
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass(frozen=True)
|
|
21
|
+
class UploadPolicy:
|
|
22
|
+
"""A signed multipart POST that uploads any object under one prefix, and when it stops working."""
|
|
23
|
+
write: HttpPostPolicyGrant
|
|
24
|
+
expires_at: datetime
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass(frozen=True)
|
|
28
|
+
class ObjectMetadata:
|
|
29
|
+
"""Metadata of a stored object. ``content_encoding`` is how the stored bytes are encoded (such
|
|
30
|
+
as ``gzip``); reads return the bytes as stored, so ``size`` counts the encoded bytes."""
|
|
31
|
+
content_type: str | None = None
|
|
32
|
+
size: int | None = None
|
|
33
|
+
last_modified: datetime | None = None
|
|
34
|
+
content_encoding: str | None = None
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class ObjectStore(ABC):
|
|
38
|
+
"""Object store interface. Objects are addressed by a logical ``key``.
|
|
39
|
+
|
|
40
|
+
Write ops return an ``object_url`` — an opaque, backend-specific locator
|
|
41
|
+
(persisted on documents) that read ops accept back; ``object_url(key)``
|
|
42
|
+
reproduces it without writing. A read of a missing object raises ObjectNotFoundError.
|
|
43
|
+
"""
|
|
44
|
+
|
|
45
|
+
# Whether this store can serve the three issue_* grant methods; callers check this, not
|
|
46
|
+
# the NotImplementedError the defaults raise.
|
|
47
|
+
supports_transfer_grants: bool = False
|
|
48
|
+
# The largest object one upload through a grant can create, where the provider caps it.
|
|
49
|
+
max_single_upload_bytes: int | None = None
|
|
50
|
+
|
|
51
|
+
@classmethod
|
|
52
|
+
def from_config(cls, **config) -> ObjectStore:
|
|
53
|
+
"""Construct from a resolved config table; backends that build a client override this."""
|
|
54
|
+
return cls(**config)
|
|
55
|
+
|
|
56
|
+
@abstractmethod
|
|
57
|
+
def put(
|
|
58
|
+
self,
|
|
59
|
+
key: str,
|
|
60
|
+
data: bytes,
|
|
61
|
+
content_type: str = DEFAULT_CONTENT_TYPE,
|
|
62
|
+
allow_overwrite: bool = False,
|
|
63
|
+
) -> str:
|
|
64
|
+
"""Write ``data`` at ``key`` and return its object_url; raises ObjectAlreadyExistsError unless allow_overwrite."""
|
|
65
|
+
|
|
66
|
+
@abstractmethod
|
|
67
|
+
def put_file(
|
|
68
|
+
self, key: str, file_path: str, content_type: str = DEFAULT_CONTENT_TYPE
|
|
69
|
+
) -> str:
|
|
70
|
+
"""Write-once upload of a local file at ``key`` and return its object_url."""
|
|
71
|
+
|
|
72
|
+
@abstractmethod
|
|
73
|
+
def put_file_at(
|
|
74
|
+
self, object_url: str, file_path: str, content_type: str = DEFAULT_CONTENT_TYPE
|
|
75
|
+
) -> str:
|
|
76
|
+
"""Write-once upload of a local file to an explicit object_url (any location)."""
|
|
77
|
+
|
|
78
|
+
@abstractmethod
|
|
79
|
+
def get(self, object_url: str) -> bytes:
|
|
80
|
+
"""Read the object at an object_url previously returned by put/put_file."""
|
|
81
|
+
|
|
82
|
+
def exists(self, key: str) -> bool:
|
|
83
|
+
"""Whether an object exists at ``key`` (derived from get_object_metadata)."""
|
|
84
|
+
return self.get_object_metadata(key) is not None
|
|
85
|
+
|
|
86
|
+
@abstractmethod
|
|
87
|
+
def get_object_metadata(self, key: str) -> ObjectMetadata | None:
|
|
88
|
+
"""Metadata (content_type, size, last_modified, content_encoding) for the object at
|
|
89
|
+
``key``, or None if it does not exist. Unpersisted fields come back None."""
|
|
90
|
+
|
|
91
|
+
@abstractmethod
|
|
92
|
+
def get_object_metadata_at(self, object_url: str) -> ObjectMetadata | None:
|
|
93
|
+
"""Metadata for the object at an explicit object_url (any location), or None if absent."""
|
|
94
|
+
|
|
95
|
+
@abstractmethod
|
|
96
|
+
def list(self, prefix: str) -> list[str]:
|
|
97
|
+
"""Logical keys under ``prefix`` (store-relative; excludes directory markers)."""
|
|
98
|
+
|
|
99
|
+
@abstractmethod
|
|
100
|
+
def list_at(self, url_prefix: str) -> list[str]:
|
|
101
|
+
"""Object_urls under an explicit url_prefix (any location; excludes directory markers)."""
|
|
102
|
+
|
|
103
|
+
@abstractmethod
|
|
104
|
+
def object_url(self, key: str) -> str:
|
|
105
|
+
"""The object_url ``put(key)`` would return, without writing."""
|
|
106
|
+
|
|
107
|
+
@abstractmethod
|
|
108
|
+
def get_object_key(self, object_url: str) -> str:
|
|
109
|
+
"""The logical key ``object_url`` addresses — inverse of ``object_url(key)``.
|
|
110
|
+
Only valid for object_urls in this store (raises ValueError otherwise)."""
|
|
111
|
+
|
|
112
|
+
def owns(self, object_url: str) -> bool:
|
|
113
|
+
"""Whether ``object_url`` is one of this store's own urls (what ``object_url(key)`` can
|
|
114
|
+
return), so callers need not read its scheme; the explicit-url reads may reach further."""
|
|
115
|
+
try:
|
|
116
|
+
self.get_object_key(object_url)
|
|
117
|
+
except ValueError:
|
|
118
|
+
return False
|
|
119
|
+
return True
|
|
120
|
+
|
|
121
|
+
@abstractmethod
|
|
122
|
+
def download_to_file(self, object_url: str, dest_path: str) -> None:
|
|
123
|
+
"""Stream the object at an object_url to a local path, creating parent dirs."""
|
|
124
|
+
|
|
125
|
+
def open(self, object_url: str) -> BinaryIO:
|
|
126
|
+
"""The object at an object_url as a readable binary stream. The default reads it whole;
|
|
127
|
+
a backend that can stream overrides this."""
|
|
128
|
+
return io.BytesIO(self.get(object_url))
|
|
129
|
+
|
|
130
|
+
def read(self, key: str) -> bytes:
|
|
131
|
+
"""Read by key — convenience for the list→read flow (``get(object_url(key))``)."""
|
|
132
|
+
return self.get(self.object_url(key))
|
|
133
|
+
|
|
134
|
+
def signed_get_url(self, object_url: str, expires_in: int = 3600) -> str | None:
|
|
135
|
+
"""A URL a remote party (e.g. a sandbox VM) can GET this object from directly,
|
|
136
|
+
or None if the backend can't produce one (e.g. local filesystem)."""
|
|
137
|
+
return None
|
|
138
|
+
|
|
139
|
+
def signed_put_url(self, object_url: str, expires_in: int = 3600) -> str | None:
|
|
140
|
+
"""A URL a remote party can PUT (upload) this object to directly,
|
|
141
|
+
or None if the backend can't produce one (e.g. local filesystem)."""
|
|
142
|
+
return None
|
|
143
|
+
|
|
144
|
+
def signed_post(
|
|
145
|
+
self, url_prefix: str, *, expires_in: int = 3600, max_bytes: int | None = None
|
|
146
|
+
) -> dict | None:
|
|
147
|
+
"""Credentials letting a remote party upload objects it names itself, anywhere
|
|
148
|
+
under ``url_prefix``. None if the backend can't produce them.
|
|
149
|
+
|
|
150
|
+
Prefix-scoped so the uploader owns its file layout — the caller bounds where
|
|
151
|
+
it may write, not what it may call things. That is also why the grant is a
|
|
152
|
+
dict and not a url: a signed url covers one key, since the key is part of
|
|
153
|
+
what is signed, so a prefix needs a policy the uploader submits as form
|
|
154
|
+
fields. Pass the whole value on, not just ``url``.
|
|
155
|
+
"""
|
|
156
|
+
return None
|
|
157
|
+
|
|
158
|
+
def shared_credentials_env(self) -> dict[str, str]:
|
|
159
|
+
"""Environment variables handing credentials to the agents and env services agent-env
|
|
160
|
+
deploys, so they can use this store directly. None by default; a deployment that wants
|
|
161
|
+
it overrides this, and the workloads get whatever scope those credentials carry."""
|
|
162
|
+
return {}
|
|
163
|
+
|
|
164
|
+
def issue_read_grant(
|
|
165
|
+
self, object_url: str, *, expires_in: int = 3600
|
|
166
|
+
) -> HttpGetGrant:
|
|
167
|
+
"""An HTTPS GET grant for the existing object at ``object_url``. ``expires_at`` is at most
|
|
168
|
+
``expires_in`` away, and earlier if the store's signing credentials expire first; raise
|
|
169
|
+
GrantUnavailableError for an ``expires_in`` beyond what the store can sign."""
|
|
170
|
+
raise NotImplementedError(
|
|
171
|
+
f"{type(self).__name__} cannot issue remote object-transfer grants"
|
|
172
|
+
)
|
|
173
|
+
|
|
174
|
+
def issue_write_grant(
|
|
175
|
+
self,
|
|
176
|
+
object_url: str,
|
|
177
|
+
*,
|
|
178
|
+
media_type: str,
|
|
179
|
+
max_bytes: int,
|
|
180
|
+
expires_in: int = 3600,
|
|
181
|
+
) -> HttpPutGrant:
|
|
182
|
+
"""An HTTPS PUT grant for one object at ``object_url``, signed for ``media_type`` and
|
|
183
|
+
bounded to ``max_bytes`` where the provider can enforce that; expiry as for a read grant."""
|
|
184
|
+
raise NotImplementedError(
|
|
185
|
+
f"{type(self).__name__} cannot issue remote object-transfer grants"
|
|
186
|
+
)
|
|
187
|
+
|
|
188
|
+
def issue_upload_policy(
|
|
189
|
+
self, prefix_url: str, *, max_object_bytes: int, expires_in: int
|
|
190
|
+
) -> UploadPolicy:
|
|
191
|
+
"""A multipart POST policy for uploads of at most ``max_object_bytes`` each to any key
|
|
192
|
+
below ``prefix_url``. It is handed over once for a long capture, so it must last all of
|
|
193
|
+
``expires_in``: raise GrantUnavailableError when it might not, judged by the kind of
|
|
194
|
+
credentials that sign it rather than by how long they have left. Object counts and total
|
|
195
|
+
size are the uploader's to enforce."""
|
|
196
|
+
raise NotImplementedError(
|
|
197
|
+
f"{type(self).__name__} cannot issue remote object-transfer grants"
|
|
198
|
+
)
|
|
@@ -0,0 +1,354 @@
|
|
|
1
|
+
"""S3 implementation of the ObjectStore interface."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import contextlib
|
|
6
|
+
import logging
|
|
7
|
+
import os
|
|
8
|
+
from collections.abc import Iterator
|
|
9
|
+
from datetime import UTC, datetime, timedelta
|
|
10
|
+
from typing import BinaryIO, NamedTuple
|
|
11
|
+
|
|
12
|
+
import boto3
|
|
13
|
+
from agentenv_protocol.transfers import (
|
|
14
|
+
HttpGetGrant,
|
|
15
|
+
HttpPostPolicyGrant,
|
|
16
|
+
HttpPutGrant,
|
|
17
|
+
)
|
|
18
|
+
from boto3.s3.transfer import TransferConfig
|
|
19
|
+
from botocore.config import Config as BotocoreConfig
|
|
20
|
+
from botocore.exceptions import ClientError
|
|
21
|
+
|
|
22
|
+
from agent_env.store.base import GrantUnavailableError, ObjectAlreadyExistsError, ObjectNotFoundError
|
|
23
|
+
from agent_env.store.object_store.object_store import (
|
|
24
|
+
DEFAULT_CONTENT_TYPE,
|
|
25
|
+
ObjectMetadata,
|
|
26
|
+
ObjectStore,
|
|
27
|
+
UploadPolicy,
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
logger = logging.getLogger(__name__)
|
|
31
|
+
|
|
32
|
+
_MAX_SIGV4_EXPIRY_SECONDS = 7 * 24 * 60 * 60
|
|
33
|
+
# GET answers NoSuchKey; HEAD (and download_file, which starts with one) answers a bare 404.
|
|
34
|
+
_MISSING_CODES = frozenset({"404", "NoSuchKey", "NotFound"})
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class _SigningCredentials(NamedTuple):
|
|
38
|
+
expiry: datetime | None
|
|
39
|
+
temporary: bool
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
# Steps call the store from the default executor's threads, of which there are up to 32
|
|
43
|
+
# (min(32, cpus + 4)); botocore's default pool of 10 would drop and reopen connections past that.
|
|
44
|
+
_MAX_POOL_CONNECTIONS = 32
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class S3ObjectStore(ObjectStore):
|
|
48
|
+
"""ObjectStore backed by an S3 bucket (injected client, config-free)."""
|
|
49
|
+
|
|
50
|
+
supports_transfer_grants = True
|
|
51
|
+
max_single_upload_bytes = 5 * 1024 * 1024 * 1024 # one S3 PUT
|
|
52
|
+
|
|
53
|
+
def __init__(
|
|
54
|
+
self, client, bucket: str, *, region: str | None = None, share_credentials: bool = False
|
|
55
|
+
) -> None:
|
|
56
|
+
if not isinstance(share_credentials, bool):
|
|
57
|
+
raise ValueError(f"share_credentials must be true or false, got {share_credentials!r}")
|
|
58
|
+
self._s3 = client
|
|
59
|
+
self._bucket = bucket
|
|
60
|
+
self._region = region
|
|
61
|
+
self._share_credentials = share_credentials
|
|
62
|
+
endpoint = getattr(getattr(client, "meta", None), "endpoint_url", None)
|
|
63
|
+
# Grants are HTTPS URLs, so a plain-HTTP endpoint (a local S3 emulator) issues none.
|
|
64
|
+
if isinstance(endpoint, str) and not endpoint.startswith("https://"):
|
|
65
|
+
self.supports_transfer_grants = False
|
|
66
|
+
|
|
67
|
+
@classmethod
|
|
68
|
+
def from_config(
|
|
69
|
+
cls, *, bucket: str, region: str | None = None, share_credentials: bool = False
|
|
70
|
+
) -> S3ObjectStore:
|
|
71
|
+
"""Build an adaptive-retry boto3 S3 client for ``bucket``."""
|
|
72
|
+
kwargs = {
|
|
73
|
+
"config": BotocoreConfig(
|
|
74
|
+
signature_version="s3v4",
|
|
75
|
+
retries={"max_attempts": 10, "mode": "adaptive"},
|
|
76
|
+
max_pool_connections=_MAX_POOL_CONNECTIONS,
|
|
77
|
+
)
|
|
78
|
+
}
|
|
79
|
+
if region:
|
|
80
|
+
kwargs["region_name"] = region
|
|
81
|
+
return cls(boto3.client("s3", **kwargs), bucket, region=region, share_credentials=share_credentials)
|
|
82
|
+
|
|
83
|
+
@property
|
|
84
|
+
def bucket(self) -> str:
|
|
85
|
+
"""The bucket this store reads and writes, for callers that mint raw s3:// URLs."""
|
|
86
|
+
return self._bucket
|
|
87
|
+
|
|
88
|
+
@property
|
|
89
|
+
def region(self) -> str | None:
|
|
90
|
+
"""The configured region, else the client's effective one (AWS default chain)."""
|
|
91
|
+
return self._region or self._s3.meta.region_name
|
|
92
|
+
|
|
93
|
+
def put(
|
|
94
|
+
self,
|
|
95
|
+
key: str,
|
|
96
|
+
data: bytes,
|
|
97
|
+
content_type: str = DEFAULT_CONTENT_TYPE,
|
|
98
|
+
allow_overwrite: bool = False,
|
|
99
|
+
) -> str:
|
|
100
|
+
logger.info(f"Uploading {len(data)} bytes to s3://{self._bucket}/{key}")
|
|
101
|
+
kwargs = dict(Body=data, Bucket=self._bucket, Key=key, ContentType=content_type)
|
|
102
|
+
if not allow_overwrite:
|
|
103
|
+
kwargs["IfNoneMatch"] = "*"
|
|
104
|
+
try:
|
|
105
|
+
self._s3.put_object(**kwargs)
|
|
106
|
+
except ClientError as e:
|
|
107
|
+
if e.response["Error"]["Code"] == "PreconditionFailed":
|
|
108
|
+
raise ObjectAlreadyExistsError(f"Object already exists at s3://{self._bucket}/{key}.") from e
|
|
109
|
+
raise
|
|
110
|
+
return self.object_url(key)
|
|
111
|
+
|
|
112
|
+
def put_file(self, key: str, file_path: str, content_type: str = DEFAULT_CONTENT_TYPE) -> str:
|
|
113
|
+
return self._put_file(self._bucket, key, file_path, content_type)
|
|
114
|
+
|
|
115
|
+
def put_file_at(self, object_url: str, file_path: str, content_type: str = DEFAULT_CONTENT_TYPE) -> str:
|
|
116
|
+
return self._put_file(*self._split(object_url), file_path, content_type)
|
|
117
|
+
|
|
118
|
+
def get(self, object_url: str) -> bytes:
|
|
119
|
+
bucket, key = self._split(object_url)
|
|
120
|
+
logger.info(f"Downloading from s3://{bucket}/{key}")
|
|
121
|
+
with _missing_as_not_found(bucket, key):
|
|
122
|
+
data = self._s3.get_object(Bucket=bucket, Key=key)["Body"].read()
|
|
123
|
+
logger.info(f"Downloaded {len(data)} bytes")
|
|
124
|
+
return data
|
|
125
|
+
|
|
126
|
+
def download_to_file(self, object_url: str, dest_path: str) -> None:
|
|
127
|
+
bucket, key = self._split(object_url)
|
|
128
|
+
logger.info(f"Streaming s3://{bucket}/{key} to {dest_path}")
|
|
129
|
+
os.makedirs(os.path.dirname(dest_path) or ".", exist_ok=True)
|
|
130
|
+
with _missing_as_not_found(bucket, key):
|
|
131
|
+
self._s3.download_file(bucket, key, dest_path)
|
|
132
|
+
|
|
133
|
+
def open(self, object_url: str) -> BinaryIO:
|
|
134
|
+
bucket, key = self._split(object_url)
|
|
135
|
+
with _missing_as_not_found(bucket, key):
|
|
136
|
+
return self._s3.get_object(Bucket=bucket, Key=key)["Body"]
|
|
137
|
+
|
|
138
|
+
def get_object_metadata(self, key: str) -> ObjectMetadata | None:
|
|
139
|
+
return self._head(self._bucket, key)
|
|
140
|
+
|
|
141
|
+
def get_object_metadata_at(self, object_url: str) -> ObjectMetadata | None:
|
|
142
|
+
return self._head(*self._split(object_url))
|
|
143
|
+
|
|
144
|
+
def list(self, prefix: str) -> list[str]:
|
|
145
|
+
return self._list_keys(self._bucket, prefix)
|
|
146
|
+
|
|
147
|
+
def list_at(self, url_prefix: str) -> list[str]:
|
|
148
|
+
bucket, prefix = self._split(url_prefix)
|
|
149
|
+
return [self._url(bucket, key) for key in self._list_keys(bucket, prefix)]
|
|
150
|
+
|
|
151
|
+
def object_url(self, key: str) -> str:
|
|
152
|
+
return self._url(self._bucket, key)
|
|
153
|
+
|
|
154
|
+
def get_object_key(self, object_url: str) -> str:
|
|
155
|
+
bucket, key = self._split(object_url)
|
|
156
|
+
if not object_url.startswith("s3://") or bucket != self._bucket:
|
|
157
|
+
raise ValueError(f"{object_url!r} is not an object in s3://{self._bucket}.")
|
|
158
|
+
return key
|
|
159
|
+
|
|
160
|
+
def signed_get_url(self, object_url: str, expires_in: int = 3600) -> str | None:
|
|
161
|
+
return self._signed_url("get_object", object_url, expires_in)
|
|
162
|
+
|
|
163
|
+
def signed_put_url(self, object_url: str, expires_in: int = 3600) -> str | None:
|
|
164
|
+
return self._signed_url("put_object", object_url, expires_in)
|
|
165
|
+
|
|
166
|
+
def issue_read_grant(
|
|
167
|
+
self, object_url: str, *, expires_in: int = 3600
|
|
168
|
+
) -> HttpGetGrant:
|
|
169
|
+
return HttpGetGrant(
|
|
170
|
+
kind="http-get",
|
|
171
|
+
url=self._signed_url("get_object", object_url, expires_in),
|
|
172
|
+
expires_at=self._grant_expiry(expires_in),
|
|
173
|
+
)
|
|
174
|
+
|
|
175
|
+
def issue_write_grant(
|
|
176
|
+
self,
|
|
177
|
+
object_url: str,
|
|
178
|
+
*,
|
|
179
|
+
media_type: str,
|
|
180
|
+
max_bytes: int,
|
|
181
|
+
expires_in: int = 3600,
|
|
182
|
+
) -> HttpPutGrant:
|
|
183
|
+
# A presigned S3 PUT cannot bound the upload size, so the uploader enforces max_bytes.
|
|
184
|
+
return HttpPutGrant(
|
|
185
|
+
kind="http-put",
|
|
186
|
+
url=self._signed_url(
|
|
187
|
+
"put_object", object_url, expires_in, params={"ContentType": media_type}
|
|
188
|
+
),
|
|
189
|
+
expires_at=self._grant_expiry(expires_in),
|
|
190
|
+
headers={"Content-Type": media_type},
|
|
191
|
+
)
|
|
192
|
+
|
|
193
|
+
def issue_upload_policy(
|
|
194
|
+
self, prefix_url: str, *, max_object_bytes: int, expires_in: int
|
|
195
|
+
) -> UploadPolicy:
|
|
196
|
+
self._check_sigv4_expiry(expires_in)
|
|
197
|
+
self._require_long_term_credentials(expires_in)
|
|
198
|
+
post = self.signed_post(
|
|
199
|
+
prefix_url.rstrip("/") + "/", expires_in=expires_in, max_bytes=max_object_bytes
|
|
200
|
+
)
|
|
201
|
+
return UploadPolicy(
|
|
202
|
+
write=HttpPostPolicyGrant(
|
|
203
|
+
kind="http-post-policy",
|
|
204
|
+
url=post["url"],
|
|
205
|
+
fields=post["fields"],
|
|
206
|
+
path_field="key",
|
|
207
|
+
file_field="file",
|
|
208
|
+
),
|
|
209
|
+
expires_at=datetime.now(UTC) + timedelta(seconds=expires_in),
|
|
210
|
+
)
|
|
211
|
+
|
|
212
|
+
def signed_post(
|
|
213
|
+
self, url_prefix: str, *, expires_in: int = 3600, max_bytes: int | None = None
|
|
214
|
+
) -> dict | None:
|
|
215
|
+
bucket, prefix = self._split(url_prefix)
|
|
216
|
+
conditions: list = [["starts-with", "$key", prefix]]
|
|
217
|
+
if max_bytes is not None:
|
|
218
|
+
conditions.append(["content-length-range", 0, max_bytes])
|
|
219
|
+
# POST policies are default-deny on extra form fields: without this the
|
|
220
|
+
# uploader's Content-Type 403s and objects store as binary/octet-stream.
|
|
221
|
+
conditions.append(["starts-with", "$Content-Type", ""])
|
|
222
|
+
return self._s3.generate_presigned_post(
|
|
223
|
+
Bucket=bucket,
|
|
224
|
+
Key=f"{prefix}${{filename}}", # substituted by the uploader
|
|
225
|
+
Conditions=conditions,
|
|
226
|
+
ExpiresIn=expires_in,
|
|
227
|
+
)
|
|
228
|
+
|
|
229
|
+
def shared_credentials_env(self) -> dict[str, str]:
|
|
230
|
+
"""The AWS default-chain credentials, frozen now, when ``share_credentials`` is set."""
|
|
231
|
+
creds = boto3.Session().get_credentials() if self._share_credentials else None
|
|
232
|
+
if creds is None:
|
|
233
|
+
return {}
|
|
234
|
+
frozen = creds.get_frozen_credentials()
|
|
235
|
+
env = {"AWS_ACCESS_KEY_ID": frozen.access_key, "AWS_SECRET_ACCESS_KEY": frozen.secret_key}
|
|
236
|
+
if frozen.token:
|
|
237
|
+
env["AWS_SESSION_TOKEN"] = frozen.token
|
|
238
|
+
if self.region:
|
|
239
|
+
env["AWS_DEFAULT_REGION"] = self.region
|
|
240
|
+
return env
|
|
241
|
+
|
|
242
|
+
def _put_file(self, bucket: str, key: str, file_path: str, content_type: str) -> str:
|
|
243
|
+
logger.info(f"Uploading {os.path.getsize(file_path) / 1024**3:.2f} GB from {file_path} to s3://{bucket}/{key}")
|
|
244
|
+
if self._head(bucket, key) is not None:
|
|
245
|
+
raise ObjectAlreadyExistsError(f"Object already exists at s3://{bucket}/{key}.")
|
|
246
|
+
config = TransferConfig(multipart_threshold=25 * 1024**2, multipart_chunksize=25 * 1024**2, max_concurrency=3)
|
|
247
|
+
self._s3.upload_file(file_path, bucket, key, ExtraArgs={"ContentType": content_type}, Config=config)
|
|
248
|
+
return self._url(bucket, key)
|
|
249
|
+
|
|
250
|
+
def _head(self, bucket: str, key: str) -> ObjectMetadata | None:
|
|
251
|
+
try:
|
|
252
|
+
head = self._s3.head_object(Bucket=bucket, Key=key)
|
|
253
|
+
except ClientError as e:
|
|
254
|
+
if e.response["Error"]["Code"] in _MISSING_CODES:
|
|
255
|
+
return None
|
|
256
|
+
raise
|
|
257
|
+
return ObjectMetadata(
|
|
258
|
+
content_type=head.get("ContentType"),
|
|
259
|
+
size=head.get("ContentLength"),
|
|
260
|
+
last_modified=head.get("LastModified"),
|
|
261
|
+
content_encoding=head.get("ContentEncoding"),
|
|
262
|
+
)
|
|
263
|
+
|
|
264
|
+
def _list_keys(self, bucket: str, prefix: str) -> list[str]:
|
|
265
|
+
keys: list[str] = []
|
|
266
|
+
for page in self._s3.get_paginator("list_objects_v2").paginate(Bucket=bucket, Prefix=prefix):
|
|
267
|
+
for obj in page.get("Contents", []) or []:
|
|
268
|
+
if not obj["Key"].endswith("/"):
|
|
269
|
+
keys.append(obj["Key"])
|
|
270
|
+
return keys
|
|
271
|
+
|
|
272
|
+
def _signed_url(
|
|
273
|
+
self, op: str, object_url: str, expires_in: int, *, params: dict | None = None
|
|
274
|
+
) -> str:
|
|
275
|
+
bucket, key = self._split(object_url)
|
|
276
|
+
return self._s3.generate_presigned_url(
|
|
277
|
+
op, Params={"Bucket": bucket, "Key": key, **(params or {})}, ExpiresIn=expires_in
|
|
278
|
+
)
|
|
279
|
+
|
|
280
|
+
def _grant_expiry(self, expires_in: int) -> datetime:
|
|
281
|
+
"""When an exact-object grant just signed stops working: after ``expires_in``, or when
|
|
282
|
+
the temporary credentials that signed it expire, if sooner. Read after signing, which
|
|
283
|
+
may have refreshed them."""
|
|
284
|
+
self._check_sigv4_expiry(expires_in)
|
|
285
|
+
requested = datetime.now(UTC) + timedelta(seconds=expires_in)
|
|
286
|
+
signing = self._signing_credentials()
|
|
287
|
+
if signing is None or signing.expiry is None or signing.expiry >= requested:
|
|
288
|
+
return requested
|
|
289
|
+
return signing.expiry
|
|
290
|
+
|
|
291
|
+
def _require_long_term_credentials(self, expires_in: int) -> None:
|
|
292
|
+
"""Refuse a grant that must last all of ``expires_in`` unless long-term credentials
|
|
293
|
+
sign it: temporary ones would end it at a moment set by their age, so the same request
|
|
294
|
+
would pass or fail by chance."""
|
|
295
|
+
signing = self._signing_credentials()
|
|
296
|
+
if signing is None:
|
|
297
|
+
raise GrantUnavailableError(
|
|
298
|
+
"the S3 client's signing credentials cannot be inspected; a namespace grant "
|
|
299
|
+
"needs credentials known to be long-term"
|
|
300
|
+
)
|
|
301
|
+
if signing.temporary:
|
|
302
|
+
lifetime = (
|
|
303
|
+
f"expire at {signing.expiry.isoformat(timespec='seconds')}"
|
|
304
|
+
if signing.expiry is not None
|
|
305
|
+
else "carry a session token"
|
|
306
|
+
)
|
|
307
|
+
raise GrantUnavailableError(
|
|
308
|
+
f"the S3 signing credentials are temporary (they {lifetime}); a {expires_in}s "
|
|
309
|
+
"namespace grant needs long-term credentials, which do not expire during a capture"
|
|
310
|
+
)
|
|
311
|
+
|
|
312
|
+
def _signing_credentials(self) -> _SigningCredentials | None:
|
|
313
|
+
"""The credentials that sign this client's requests. botocore has no public accessor,
|
|
314
|
+
so this reads its request signer's private attributes; None when the client does not
|
|
315
|
+
expose them."""
|
|
316
|
+
signer = getattr(self._s3, "_request_signer", None)
|
|
317
|
+
credentials = getattr(signer, "_credentials", None)
|
|
318
|
+
if credentials is None:
|
|
319
|
+
return None
|
|
320
|
+
expiry = getattr(credentials, "_expiry_time", None)
|
|
321
|
+
if expiry is not None:
|
|
322
|
+
expiry = (expiry if expiry.tzinfo else expiry.replace(tzinfo=UTC)).astimezone(UTC)
|
|
323
|
+
return _SigningCredentials(
|
|
324
|
+
expiry=expiry,
|
|
325
|
+
temporary=expiry is not None or bool(getattr(credentials, "token", None)),
|
|
326
|
+
)
|
|
327
|
+
|
|
328
|
+
@staticmethod
|
|
329
|
+
def _check_sigv4_expiry(expires_in: int) -> None:
|
|
330
|
+
if expires_in > _MAX_SIGV4_EXPIRY_SECONDS:
|
|
331
|
+
raise GrantUnavailableError(
|
|
332
|
+
f"S3 SigV4 grants last at most {_MAX_SIGV4_EXPIRY_SECONDS}s; "
|
|
333
|
+
f"{expires_in}s was requested"
|
|
334
|
+
)
|
|
335
|
+
|
|
336
|
+
@staticmethod
|
|
337
|
+
def _url(bucket: str, key: str) -> str:
|
|
338
|
+
return f"s3://{bucket}/{key}"
|
|
339
|
+
|
|
340
|
+
@staticmethod
|
|
341
|
+
def _split(object_url: str) -> tuple[str, str]:
|
|
342
|
+
# Not urlparse: it would end the key at a "#" or "?", which S3 keys may contain.
|
|
343
|
+
bucket, _, key = object_url.removeprefix("s3://").partition("/")
|
|
344
|
+
return bucket, key.lstrip("/")
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
@contextlib.contextmanager
|
|
348
|
+
def _missing_as_not_found(bucket: str, key: str) -> Iterator[None]:
|
|
349
|
+
try:
|
|
350
|
+
yield
|
|
351
|
+
except ClientError as e:
|
|
352
|
+
if e.response["Error"]["Code"] in _MISSING_CODES:
|
|
353
|
+
raise ObjectNotFoundError(f"No object at s3://{bucket}/{key}.") from e
|
|
354
|
+
raise
|
agent_env/store/query.py
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
"""Base query builder for AgentEnv stores."""
|
|
2
|
+
|
|
3
|
+
from abc import ABC, abstractmethod
|
|
4
|
+
from typing import Generic, Optional, Self, TypeVar
|
|
5
|
+
|
|
6
|
+
from agent_env.store.document_store.document_store import (
|
|
7
|
+
Eq,
|
|
8
|
+
Filter,
|
|
9
|
+
Gte,
|
|
10
|
+
In,
|
|
11
|
+
Lte,
|
|
12
|
+
Predicate,
|
|
13
|
+
Sort,
|
|
14
|
+
)
|
|
15
|
+
|
|
16
|
+
T = TypeVar("T")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class QueryBuilder(Generic[T], ABC):
|
|
20
|
+
"""Base query builder with common operations. Immutable - each method returns a new instance.
|
|
21
|
+
|
|
22
|
+
Example:
|
|
23
|
+
results = (
|
|
24
|
+
Artifact.query()
|
|
25
|
+
.type("docker_image")
|
|
26
|
+
.sort("version", descending=True)
|
|
27
|
+
.limit(10)
|
|
28
|
+
.execute()
|
|
29
|
+
)
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
def __init__(self) -> None:
|
|
33
|
+
self._filters: dict = {}
|
|
34
|
+
self._sort_field: Optional[str] = None
|
|
35
|
+
self._sort_desc: bool = True
|
|
36
|
+
self._limit_value: Optional[int] = None
|
|
37
|
+
self._offset_value: Optional[int] = None
|
|
38
|
+
|
|
39
|
+
def _clone(self) -> Self:
|
|
40
|
+
clone = self.__class__()
|
|
41
|
+
clone._filters = self._filters.copy()
|
|
42
|
+
clone._sort_field = self._sort_field
|
|
43
|
+
clone._sort_desc = self._sort_desc
|
|
44
|
+
clone._limit_value = self._limit_value
|
|
45
|
+
clone._offset_value = self._offset_value
|
|
46
|
+
return clone
|
|
47
|
+
|
|
48
|
+
def _add_filter(self, key: str, value) -> Self:
|
|
49
|
+
clone = self._clone()
|
|
50
|
+
clone._filters[key] = value
|
|
51
|
+
return clone
|
|
52
|
+
|
|
53
|
+
def id(self, id: str) -> Self:
|
|
54
|
+
return self._add_filter("id", id)
|
|
55
|
+
|
|
56
|
+
def version(self, version: int) -> Self:
|
|
57
|
+
return self._add_filter("version", version)
|
|
58
|
+
|
|
59
|
+
def version_gte(self, version: int) -> Self:
|
|
60
|
+
return self._add_filter("version_gte", version)
|
|
61
|
+
|
|
62
|
+
def version_lte(self, version: int) -> Self:
|
|
63
|
+
return self._add_filter("version_lte", version)
|
|
64
|
+
|
|
65
|
+
def sort(self, field: str, descending: bool = True) -> Self:
|
|
66
|
+
clone = self._clone()
|
|
67
|
+
clone._sort_field = field
|
|
68
|
+
clone._sort_desc = descending
|
|
69
|
+
return clone
|
|
70
|
+
|
|
71
|
+
def limit(self, n: int) -> Self:
|
|
72
|
+
clone = self._clone()
|
|
73
|
+
clone._limit_value = n
|
|
74
|
+
return clone
|
|
75
|
+
|
|
76
|
+
def offset(self, n: int) -> Self:
|
|
77
|
+
clone = self._clone()
|
|
78
|
+
clone._offset_value = n
|
|
79
|
+
return clone
|
|
80
|
+
|
|
81
|
+
def latest(self) -> Self:
|
|
82
|
+
return self.sort("version", descending=True).limit(1)
|
|
83
|
+
|
|
84
|
+
def first(self) -> Optional[T]:
|
|
85
|
+
results = self.limit(1).execute()
|
|
86
|
+
return results[0] if results else None
|
|
87
|
+
|
|
88
|
+
def count(self) -> int:
|
|
89
|
+
return self._execute_count()
|
|
90
|
+
|
|
91
|
+
@abstractmethod
|
|
92
|
+
def execute(self) -> list[T]:
|
|
93
|
+
pass
|
|
94
|
+
|
|
95
|
+
@abstractmethod
|
|
96
|
+
def _execute_count(self) -> int:
|
|
97
|
+
pass
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
_SUFFIX_PREDICATES = {"_gte": Gte, "_lte": Lte, "_in": In}
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def to_document_query(qb: "QueryBuilder") -> tuple[Filter, Optional[Sort]]:
|
|
104
|
+
"""Compile a QueryBuilder's suffix-encoded filters + sort into a Filter/Sort."""
|
|
105
|
+
conditions: dict[str, list[Predicate]] = {}
|
|
106
|
+
for key, value in qb._filters.items():
|
|
107
|
+
suffix = next((s for s in _SUFFIX_PREDICATES if key.endswith(s)), None)
|
|
108
|
+
field = key.removesuffix(suffix) if suffix else key
|
|
109
|
+
pred = _SUFFIX_PREDICATES.get(suffix, Eq)
|
|
110
|
+
conditions.setdefault(field, []).append(pred(value))
|
|
111
|
+
sort = Sort.by(qb._sort_field, descending=qb._sort_desc) if qb._sort_field else None
|
|
112
|
+
return Filter(conditions), sort
|