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,576 @@
|
|
|
1
|
+
"""How agent-env was installed, and the commands that add or remove a package there.
|
|
2
|
+
|
|
3
|
+
agent-env never installs anything itself: it builds the command for the installer that owns its
|
|
4
|
+
environment, so that installer's next rebuild (`uv tool upgrade`, `uv sync`, `pipx reinstall`)
|
|
5
|
+
keeps the change. Nothing here runs a command.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import json
|
|
9
|
+
import os
|
|
10
|
+
import re
|
|
11
|
+
import shlex
|
|
12
|
+
import shutil
|
|
13
|
+
import tomllib
|
|
14
|
+
from dataclasses import dataclass, replace
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
from typing import Callable, Optional
|
|
17
|
+
from urllib.parse import parse_qs, unquote, urlparse
|
|
18
|
+
|
|
19
|
+
UV_TOOL = "uv tool"
|
|
20
|
+
PIPX = "pipx"
|
|
21
|
+
UV_PROJECT = "uv project"
|
|
22
|
+
VIRTUALENV = "virtualenv"
|
|
23
|
+
SYSTEM = "system Python"
|
|
24
|
+
POETRY = "Poetry project"
|
|
25
|
+
PDM = "PDM project"
|
|
26
|
+
HATCH = "Hatch environment"
|
|
27
|
+
|
|
28
|
+
# The installers `--installer` can force, by the value it takes.
|
|
29
|
+
FORCEABLE = {"uv-tool": UV_TOOL, "pipx": PIPX, "uv-project": UV_PROJECT, "pip": VIRTUALENV}
|
|
30
|
+
# agent-env itself, the protocol package it pins exactly, and the command's own name, which a spec may
|
|
31
|
+
# use for agent-env; `plugin add` and `remove` never change them.
|
|
32
|
+
CORE = ("agentenv-framework", "agentenv-framework-protocol", "agentenv-protocol", "agent-env")
|
|
33
|
+
|
|
34
|
+
_NAME = re.compile(r"[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?")
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class InstallerError(Exception):
|
|
38
|
+
"""This change cannot go through the environment's installer; the message says what to do."""
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@dataclass(frozen=True)
|
|
42
|
+
class Environment:
|
|
43
|
+
"""Where agent-env is installed, and which installer owns it."""
|
|
44
|
+
|
|
45
|
+
kind: str
|
|
46
|
+
location: Path # the tool or pipx venv, the project root, or the venv itself
|
|
47
|
+
prefix: Path
|
|
48
|
+
python: Path
|
|
49
|
+
has_pip: bool = True
|
|
50
|
+
refusal: Optional[str] = None # set when agent-env must not change this environment
|
|
51
|
+
# A uv workspace whose root has no [project]: the member that declares agent-env, and its directory.
|
|
52
|
+
member: Optional[tuple[str, Path]] = None
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@dataclass(frozen=True)
|
|
56
|
+
class Plan:
|
|
57
|
+
"""What `plugin add` or `plugin remove` runs, in order, or only prints for the user to run."""
|
|
58
|
+
|
|
59
|
+
environment: Environment
|
|
60
|
+
commands: tuple[tuple[str, ...], ...]
|
|
61
|
+
runs: bool = True
|
|
62
|
+
cwd: Optional[Path] = None
|
|
63
|
+
note: Optional[str] = None
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def normalize(name: str) -> str:
|
|
67
|
+
return re.sub(r"[-_.]+", "-", name).lower()
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def requirement_name(spec: str) -> Optional[str]:
|
|
71
|
+
"""The distribution a requirement names: from ``name`` or ``name @ url``, else from a wheel
|
|
72
|
+
or sdist file name. None for a directory or a VCS spec, whose name only a build tells."""
|
|
73
|
+
head = spec.split("@", 1)[0].strip() if "@" in spec else spec
|
|
74
|
+
if not any(c in head for c in "/\\") and not head.endswith((".whl", ".tar.gz", ".zip")):
|
|
75
|
+
match = _NAME.match(head)
|
|
76
|
+
return normalize(match.group(0)) if match else None
|
|
77
|
+
filename = unquote(urlparse(spec).path if "://" in spec else spec).rstrip("/").rsplit("/", 1)[-1]
|
|
78
|
+
if filename.endswith(".whl"):
|
|
79
|
+
return normalize(filename.split("-", 1)[0])
|
|
80
|
+
for suffix in (".tar.gz", ".zip"):
|
|
81
|
+
if filename.endswith(suffix) and "-" in filename:
|
|
82
|
+
return normalize(filename[: -len(suffix)].rsplit("-", 1)[0])
|
|
83
|
+
return None
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def detect(prefix: Path, base_prefix: Path, python: Path, *, has_pip: bool = True,
|
|
87
|
+
project_environment: Optional[str] = None, cwd: Optional[Path] = None) -> Environment:
|
|
88
|
+
"""The installer that owns the environment at ``prefix``. ``project_environment`` is
|
|
89
|
+
UV_PROJECT_ENVIRONMENT, which puts a uv project's environment outside its `.venv`; the project
|
|
90
|
+
is then the one uv finds from ``cwd``."""
|
|
91
|
+
def env(kind: str, location: Path, **more) -> Environment:
|
|
92
|
+
return Environment(kind, location, prefix, python, has_pip, **more)
|
|
93
|
+
|
|
94
|
+
if (prefix / "uv-receipt.toml").is_file():
|
|
95
|
+
return env(UV_TOOL, prefix)
|
|
96
|
+
if (prefix / "pipx_metadata.json").is_file():
|
|
97
|
+
return env(PIPX, prefix)
|
|
98
|
+
if project_environment:
|
|
99
|
+
project, found_here = _project_using(prefix, project_environment, cwd)
|
|
100
|
+
if project is not None and found_here:
|
|
101
|
+
return _uv_project(env, project)
|
|
102
|
+
if project is not None or (os.path.isabs(project_environment)
|
|
103
|
+
and _same_path(Path(project_environment), prefix)):
|
|
104
|
+
owner = f"the uv project at {project}" if project else "a uv project"
|
|
105
|
+
return env(VIRTUALENV, prefix, refusal=(
|
|
106
|
+
f"UV_PROJECT_ENVIRONMENT makes this the environment of {owner}, and its next `uv sync` would drop "
|
|
107
|
+
"what agent-env installs here; run this from the project's directory"
|
|
108
|
+
))
|
|
109
|
+
root = prefix.parent
|
|
110
|
+
if prefix.name == ".venv" and (root / "pyproject.toml").is_file():
|
|
111
|
+
if (root / "uv.lock").is_file():
|
|
112
|
+
return _uv_project(env, root)
|
|
113
|
+
tools = set(_toml(root / "pyproject.toml").get("tool", {}))
|
|
114
|
+
if "poetry" in tools or (root / "poetry.lock").is_file():
|
|
115
|
+
return env(POETRY, root)
|
|
116
|
+
if "pdm" in tools or (root / "pdm.lock").is_file():
|
|
117
|
+
return env(PDM, root)
|
|
118
|
+
if hatch := next((d for d in prefix.parents if (d / "pyproject.toml").is_file() and _hatch_env(d, prefix)), None):
|
|
119
|
+
return env(HATCH, hatch)
|
|
120
|
+
parts = prefix.parts
|
|
121
|
+
if "pypoetry" in parts and "virtualenvs" in parts:
|
|
122
|
+
return env(POETRY, prefix)
|
|
123
|
+
if "hatch" in parts and "env" in parts:
|
|
124
|
+
return env(HATCH, prefix)
|
|
125
|
+
return env(VIRTUALENV if prefix != base_prefix else SYSTEM, prefix)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _same_path(a: Path, b: Path) -> bool:
|
|
129
|
+
try:
|
|
130
|
+
return a.resolve() == b.resolve()
|
|
131
|
+
except OSError:
|
|
132
|
+
return False
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _project_using(prefix: Path, project_environment: str, cwd: Optional[Path]) -> tuple[Optional[Path], bool]:
|
|
136
|
+
"""The uv project whose UV_PROJECT_ENVIRONMENT is ``prefix``, and whether agent-env may change
|
|
137
|
+
it from ``cwd``: it is the project uv finds from there, or there is none. A value relative to
|
|
138
|
+
its project, as uv reads it, also finds a project the environment lies under; a command run
|
|
139
|
+
inside a different project must not change that one."""
|
|
140
|
+
path = Path(project_environment)
|
|
141
|
+
|
|
142
|
+
def uses(directory: Path) -> bool:
|
|
143
|
+
return ((directory / "pyproject.toml").is_file() and (directory / "uv.lock").is_file()
|
|
144
|
+
and _same_path(path if path.is_absolute() else directory / path, prefix))
|
|
145
|
+
|
|
146
|
+
nearest = next((d for d in ((cwd, *cwd.parents) if cwd else ())
|
|
147
|
+
if (d / "pyproject.toml").is_file() and (d / "uv.lock").is_file()), None)
|
|
148
|
+
if nearest is not None and uses(nearest):
|
|
149
|
+
return nearest, True
|
|
150
|
+
if path.is_absolute():
|
|
151
|
+
return None, False
|
|
152
|
+
return next((d for d in prefix.parents if uses(d)), None), nearest is None
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def _uv_project(make: Callable[..., Environment], root: Path) -> Environment:
|
|
156
|
+
"""A uv project at ``root``. A workspace root with no [project] table cannot take a dependency
|
|
157
|
+
itself, so the change goes to the one member that declares agent-env."""
|
|
158
|
+
data = _toml(root / "pyproject.toml")
|
|
159
|
+
if "project" in data or "workspace" not in data.get("tool", {}).get("uv", {}):
|
|
160
|
+
return make(UV_PROJECT, root)
|
|
161
|
+
members = [(name, path) for name, path in _workspace_members(root, data)
|
|
162
|
+
if "agentenv-framework" in _declared(path / "pyproject.toml")]
|
|
163
|
+
if len(members) == 1:
|
|
164
|
+
return make(UV_PROJECT, root, member=members[0])
|
|
165
|
+
return make(UV_PROJECT, root, refusal=(
|
|
166
|
+
f"this uv workspace's root has no [project] table, and {len(members)} of its members declare "
|
|
167
|
+
"agentenv-framework, so agent-env cannot tell which one to change; run `uv add --package <member> ...` "
|
|
168
|
+
"yourself"
|
|
169
|
+
))
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def _workspace_members(root: Path, data: dict) -> list[tuple[str, Path]]:
|
|
173
|
+
workspace = data.get("tool", {}).get("uv", {}).get("workspace", {})
|
|
174
|
+
excluded = {path.resolve() for pattern in workspace.get("exclude") or [] for path in root.glob(pattern)}
|
|
175
|
+
found = []
|
|
176
|
+
for pattern in workspace.get("members") or []:
|
|
177
|
+
for path in sorted(root.glob(pattern)):
|
|
178
|
+
name = _toml(path / "pyproject.toml").get("project", {}).get("name")
|
|
179
|
+
if name and path.resolve() not in excluded:
|
|
180
|
+
found.append((name, path))
|
|
181
|
+
return found
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def _hatch_env(root: Path, prefix: Path) -> bool:
|
|
185
|
+
"""Whether ``prefix`` is a Hatch environment that the project keeps in its own directory."""
|
|
186
|
+
envs = _toml(root / "pyproject.toml").get("tool", {}).get("hatch", {}).get("envs", {})
|
|
187
|
+
return any(isinstance(settings, dict) and isinstance(settings.get("path"), str)
|
|
188
|
+
and _same_path(root / settings["path"], prefix) for settings in envs.values())
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def with_refusal(env: Environment, *, stdlib: Path, site_packages: Path) -> Environment:
|
|
192
|
+
"""``env``, refused when its Python is system-managed (PEP 668) or its packages are read-only."""
|
|
193
|
+
if env.kind == SYSTEM and (stdlib / "EXTERNALLY-MANAGED").is_file():
|
|
194
|
+
return replace(env, refusal=(
|
|
195
|
+
"this Python is managed by the system (PEP 668). Install agent-env into its own "
|
|
196
|
+
"environment instead, e.g. `uv tool install agentenv-framework --with <plugin>`"
|
|
197
|
+
))
|
|
198
|
+
if not os.access(site_packages, os.W_OK):
|
|
199
|
+
return replace(env, refusal=f"{site_packages} is read-only, so nothing can be installed into it")
|
|
200
|
+
return env
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def forced(env: Environment, installer: Optional[str]) -> Environment:
|
|
204
|
+
"""``env`` with its installer chosen by ``--installer`` instead of detected."""
|
|
205
|
+
if installer is None:
|
|
206
|
+
return env
|
|
207
|
+
kind = FORCEABLE[installer]
|
|
208
|
+
if kind == UV_TOOL and not (env.prefix / "uv-receipt.toml").is_file():
|
|
209
|
+
raise InstallerError(f"--installer uv-tool needs a uv tool; {env.prefix} has no uv-receipt.toml")
|
|
210
|
+
if kind == PIPX and not (env.prefix / "pipx_metadata.json").is_file():
|
|
211
|
+
raise InstallerError(f"--installer pipx needs a pipx venv; {env.prefix} has no pipx_metadata.json")
|
|
212
|
+
location = env.prefix
|
|
213
|
+
if kind == UV_PROJECT:
|
|
214
|
+
location = env.prefix.parent
|
|
215
|
+
if env.prefix.name != ".venv" or not (location / "pyproject.toml").is_file():
|
|
216
|
+
raise InstallerError(
|
|
217
|
+
f"--installer uv-project needs agent-env to run from a project's own .venv; {env.prefix} is not one"
|
|
218
|
+
)
|
|
219
|
+
return replace(env, kind=kind, location=location)
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def add_plan(env: Environment, specs: list[str], *, index_url: Optional[str] = None) -> Plan:
|
|
223
|
+
"""The commands that install ``specs`` into ``env`` the way its installer keeps them."""
|
|
224
|
+
_refuse(env)
|
|
225
|
+
for spec in specs:
|
|
226
|
+
if requirement_name(spec) in CORE:
|
|
227
|
+
raise InstallerError(f"{spec} is agent-env itself; upgrade it with the installer that owns the environment")
|
|
228
|
+
if env.kind == UV_TOOL:
|
|
229
|
+
receipt = ToolReceipt.read(env.prefix / "uv-receipt.toml")
|
|
230
|
+
return Plan(env, (("uv", "tool", "install", *receipt.install_args(add=specs, default_index=index_url)),))
|
|
231
|
+
if env.kind == PIPX:
|
|
232
|
+
metadata = json.loads((env.prefix / "pipx_metadata.json").read_text())
|
|
233
|
+
injected = {normalize(name) for name in metadata.get("injected_packages") or {}}
|
|
234
|
+
# pipx leaves an injected package as it is unless forced, so an upgrade would do nothing.
|
|
235
|
+
# Only a named spec is forced: an unnamed one could build as the venv's main package,
|
|
236
|
+
# agent-env itself, which a forced inject would reinstall.
|
|
237
|
+
force = ("--force",) if injected & {requirement_name(spec) for spec in specs} else ()
|
|
238
|
+
inject = ("pipx", "inject", env.prefix.name, *specs, *force)
|
|
239
|
+
return Plan(env, (inject + _pipx_args(env) + _flag("--index-url", index_url),))
|
|
240
|
+
if env.kind == UV_PROJECT:
|
|
241
|
+
# `uv add` and `uv sync` sync exactly, which would uninstall extras and anything installed
|
|
242
|
+
# outside the lock, agent-env included; an inexact sync only adds.
|
|
243
|
+
project = ("--project", str(env.location), *_package(env))
|
|
244
|
+
return Plan(env, (
|
|
245
|
+
("uv", "add", "--no-sync", *project, *specs, *_flag("--default-index", index_url)),
|
|
246
|
+
("uv", "sync", "--inexact", *project),
|
|
247
|
+
))
|
|
248
|
+
if env.kind in (VIRTUALENV, SYSTEM):
|
|
249
|
+
return Plan(env, (pip_command(env, "install", *specs, *_flag("--index-url", index_url)),))
|
|
250
|
+
return _printed(env, "add", specs)
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def _package(env: Environment) -> tuple[str, ...]:
|
|
254
|
+
return ("--package", env.member[0]) if env.member else ()
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def remove_plan(env: Environment, names: list[str], *, also: list[str] = ()) -> Plan:
|
|
258
|
+
"""The commands that uninstall ``names`` from ``env`` the way its installer keeps them. ``also``
|
|
259
|
+
are the plugins only ``names`` needed: a uv tool's rebuild drops them by itself, and a uv
|
|
260
|
+
project's lock does, so they are uninstalled with them."""
|
|
261
|
+
_refuse(env)
|
|
262
|
+
if env.kind == UV_TOOL:
|
|
263
|
+
receipt = ToolReceipt.read(env.prefix / "uv-receipt.toml")
|
|
264
|
+
return Plan(env, (("uv", "tool", "install", *receipt.install_args(drop=names)),))
|
|
265
|
+
if env.kind == PIPX:
|
|
266
|
+
main = json.loads((env.prefix / "pipx_metadata.json").read_text())["main_package"]["package"]
|
|
267
|
+
if normalize(main) in {normalize(n) for n in names}:
|
|
268
|
+
raise InstallerError(
|
|
269
|
+
f"{main} is this pipx venv's own package; `pipx uninstall {env.prefix.name}` removes it"
|
|
270
|
+
)
|
|
271
|
+
# Without --leave-deps pipx also uninstalls whatever nothing else requires, agent-env included.
|
|
272
|
+
return Plan(env, (("pipx", "uninject", "--leave-deps", env.prefix.name, *names),))
|
|
273
|
+
if env.kind == UV_PROJECT:
|
|
274
|
+
removes = []
|
|
275
|
+
for name in names:
|
|
276
|
+
places = _places(env, name)
|
|
277
|
+
if not places:
|
|
278
|
+
raise InstallerError(f"the project does not declare {name}, so `uv remove` cannot drop it; it is "
|
|
279
|
+
"installed for another package, or outside the lock")
|
|
280
|
+
removes += [("uv", "remove", "--no-sync", "--project", str(env.location),
|
|
281
|
+
*(("--package", package) if package else ()), *flags, name) for package, flags in places]
|
|
282
|
+
return Plan(env, (*removes, ("uv", "pip", "uninstall", "--python", str(env.python), *names, *also)))
|
|
283
|
+
if env.kind in (VIRTUALENV, SYSTEM):
|
|
284
|
+
return Plan(env, (pip_command(env, "uninstall", *names),))
|
|
285
|
+
return _printed(env, "remove", names)
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
def recorded(env: Environment) -> Optional[dict[str, frozenset[str]]]:
|
|
289
|
+
"""The packages the installer's record lists as wanted, rather than pulled in by others, each
|
|
290
|
+
with the extras it asks for; None when it keeps no record. A uv tool's or project's rebuild
|
|
291
|
+
keeps these and what they need."""
|
|
292
|
+
if env.kind == UV_TOOL:
|
|
293
|
+
return {normalize(entry["name"]): frozenset(map(normalize, entry.get("extras") or ()))
|
|
294
|
+
for entry in ToolReceipt.read(env.prefix / "uv-receipt.toml").requirements}
|
|
295
|
+
if env.kind == PIPX:
|
|
296
|
+
metadata = json.loads((env.prefix / "pipx_metadata.json").read_text())
|
|
297
|
+
names = [metadata["main_package"]["package"], *(metadata.get("injected_packages") or {})]
|
|
298
|
+
return {normalize(name): frozenset() for name in names}
|
|
299
|
+
if env.kind == UV_PROJECT:
|
|
300
|
+
wanted: dict[str, frozenset[str]] = {}
|
|
301
|
+
for _, path in _projects(env.location):
|
|
302
|
+
data = _toml(path / "pyproject.toml")
|
|
303
|
+
if name := data.get("project", {}).get("name"):
|
|
304
|
+
wanted.setdefault(normalize(name), frozenset())
|
|
305
|
+
for requirement, _ in _declarations(data):
|
|
306
|
+
name, extras = _requirement_extras(requirement)
|
|
307
|
+
if name:
|
|
308
|
+
wanted[name] = wanted.get(name, frozenset()) | extras
|
|
309
|
+
return wanted
|
|
310
|
+
return None
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
def project_files(env: Environment) -> list[Path]:
|
|
314
|
+
"""The pyproject.toml files of a uv project and its workspace members."""
|
|
315
|
+
return [path / "pyproject.toml" for _, path in _projects(env.location)]
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
def _projects(root: Path) -> list[tuple[Optional[str], Path]]:
|
|
319
|
+
"""The uv project at ``root`` (None when it is a virtual workspace root) and its workspace
|
|
320
|
+
members, by name, with their directories."""
|
|
321
|
+
data = _toml(root / "pyproject.toml")
|
|
322
|
+
return [(None, root)] + _workspace_members(root, data)
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
def _declarations(data: dict) -> list[tuple[str, tuple[str, ...]]]:
|
|
326
|
+
"""Every dependency a pyproject.toml declares, with the `uv remove` flags that name its group."""
|
|
327
|
+
project = data.get("project", {})
|
|
328
|
+
places = [((), project.get("dependencies") or [])]
|
|
329
|
+
places += [(("--optional", extra), items) for extra, items in (project.get("optional-dependencies") or {}).items()]
|
|
330
|
+
places += [(("--group", group), items) for group, items in (data.get("dependency-groups") or {}).items()]
|
|
331
|
+
places += [(("--dev",), data.get("tool", {}).get("uv", {}).get("dev-dependencies") or [])]
|
|
332
|
+
return [(item, flags) for flags, items in places for item in items if isinstance(item, str)]
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
def _places(env: Environment, name: str) -> list[tuple[Optional[str], tuple[str, ...]]]:
|
|
336
|
+
"""Where the project declares ``name``: the workspace member (None for the root project) and
|
|
337
|
+
the group, as `uv remove` flags."""
|
|
338
|
+
key = normalize(name)
|
|
339
|
+
return [(package, flags) for package, path in _projects(env.location)
|
|
340
|
+
for requirement, flags in _declarations(_toml(path / "pyproject.toml"))
|
|
341
|
+
if requirement_name(requirement) == key]
|
|
342
|
+
|
|
343
|
+
|
|
344
|
+
_EXTRAS = re.compile(r"\s*[A-Za-z0-9][A-Za-z0-9._-]*\s*\[([^\]]*)\]")
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
def _requirement_extras(requirement: str) -> tuple[Optional[str], frozenset[str]]:
|
|
348
|
+
match = _EXTRAS.match(requirement)
|
|
349
|
+
extras = {normalize(e.strip()) for e in match.group(1).split(",") if e.strip()} if match else set()
|
|
350
|
+
return requirement_name(requirement), frozenset(extras)
|
|
351
|
+
|
|
352
|
+
|
|
353
|
+
def _declared(pyproject: Path) -> set[str]:
|
|
354
|
+
"""Every dependency a pyproject.toml declares, in any group."""
|
|
355
|
+
return {requirement_name(requirement) for requirement, _ in _declarations(_toml(pyproject))} - {None}
|
|
356
|
+
|
|
357
|
+
|
|
358
|
+
def _refuse(env: Environment) -> None:
|
|
359
|
+
if env.refusal:
|
|
360
|
+
raise InstallerError(f"agent-env will not change this environment: {env.refusal}")
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
def _flag(flag: str, value: Optional[str]) -> tuple[str, ...]:
|
|
364
|
+
return (flag, value) if value else ()
|
|
365
|
+
|
|
366
|
+
|
|
367
|
+
def pip_command(env: Environment, action: str, *args: str) -> tuple[str, ...]:
|
|
368
|
+
"""pip inside the environment when it has one, else `uv pip` aimed at its interpreter."""
|
|
369
|
+
if env.has_pip:
|
|
370
|
+
return (str(env.python), "-m", "pip", action, *(("-y",) if action == "uninstall" else ()), *args)
|
|
371
|
+
if shutil.which("uv"):
|
|
372
|
+
return ("uv", "pip", action, "--python", str(env.python), *args)
|
|
373
|
+
raise InstallerError(f"{env.prefix} has neither pip nor uv to {action} with")
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
def _pipx_args(env: Environment) -> tuple[str, ...]:
|
|
377
|
+
"""The pip arguments the venv was created with, so an injected package resolves the same way."""
|
|
378
|
+
metadata = json.loads((env.prefix / "pipx_metadata.json").read_text())
|
|
379
|
+
pip_args = metadata["main_package"].get("pip_args") or []
|
|
380
|
+
return ("--pip-args", shlex.join(pip_args)) if pip_args else ()
|
|
381
|
+
|
|
382
|
+
|
|
383
|
+
def _printed(env: Environment, action: str, names: list[str]) -> Plan:
|
|
384
|
+
if env.kind in (POETRY, PDM):
|
|
385
|
+
tool = "poetry" if env.kind == POETRY else "pdm"
|
|
386
|
+
return Plan(env, ((tool, action, *names),), runs=False, cwd=env.location,
|
|
387
|
+
note=f"{env.kind.split()[0]} owns this environment, so run this in the project yourself.")
|
|
388
|
+
verb = "Add" if action == "add" else "Remove"
|
|
389
|
+
return Plan(env, (), runs=False, cwd=env.location, note=(
|
|
390
|
+
f"Hatch has no command for this. {verb} `{' '.join(names)}` in the environment's dependencies in "
|
|
391
|
+
"pyproject.toml, then recreate it with `hatch env prune`."
|
|
392
|
+
))
|
|
393
|
+
|
|
394
|
+
|
|
395
|
+
def _toml(path: Path) -> dict:
|
|
396
|
+
try:
|
|
397
|
+
return tomllib.loads(path.read_text())
|
|
398
|
+
except (OSError, tomllib.TOMLDecodeError):
|
|
399
|
+
return {}
|
|
400
|
+
|
|
401
|
+
|
|
402
|
+
# `[tool.options]` keys a receipt can hold that agent-env passes back to `uv tool install`.
|
|
403
|
+
_RECEIPT_VALUES = {
|
|
404
|
+
"index-url": "--default-index", "default-index": "--default-index", "extra-index-url": "--index",
|
|
405
|
+
"find-links": "--find-links", "index-strategy": "--index-strategy", "keyring-provider": "--keyring-provider",
|
|
406
|
+
"prerelease": "--prerelease", "resolution": "--resolution", "exclude-newer": "--exclude-newer",
|
|
407
|
+
"link-mode": "--link-mode",
|
|
408
|
+
}
|
|
409
|
+
_RECEIPT_FLAGS = {
|
|
410
|
+
"no-index": "--no-index", "compile-bytecode": "--compile-bytecode", "no-build-isolation": "--no-build-isolation",
|
|
411
|
+
"no-sources": "--no-sources", "no-build": "--no-build",
|
|
412
|
+
}
|
|
413
|
+
_RECEIPT_REQUIREMENT_KEYS = frozenset({
|
|
414
|
+
"name", "extras", "marker", "specifier", "url", "path", "directory", "editable", "git", "rev", "tag", "branch",
|
|
415
|
+
"subdirectory",
|
|
416
|
+
})
|
|
417
|
+
|
|
418
|
+
|
|
419
|
+
@dataclass(frozen=True)
|
|
420
|
+
class ToolReceipt:
|
|
421
|
+
"""A uv tool's `uv-receipt.toml`: the requirements it was installed with, and its options.
|
|
422
|
+
|
|
423
|
+
Re-running `uv tool install` forgets any option not passed again, so every change passes the
|
|
424
|
+
receipt's Python and options back; anything that cannot be passed back refuses the change.
|
|
425
|
+
"""
|
|
426
|
+
|
|
427
|
+
requirements: tuple[dict, ...]
|
|
428
|
+
python: Optional[str]
|
|
429
|
+
options: dict
|
|
430
|
+
unsupported: tuple[str, ...] = ()
|
|
431
|
+
|
|
432
|
+
@classmethod
|
|
433
|
+
def read(cls, path: Path) -> "ToolReceipt":
|
|
434
|
+
try:
|
|
435
|
+
tool = tomllib.loads(path.read_text())["tool"]
|
|
436
|
+
except (OSError, KeyError, tomllib.TOMLDecodeError) as exc:
|
|
437
|
+
raise InstallerError(f"cannot read the uv tool receipt at {path}: {exc}") from exc
|
|
438
|
+
requirements = tuple(tool.get("requirements") or ())
|
|
439
|
+
if not requirements:
|
|
440
|
+
raise InstallerError(f"the uv tool receipt at {path} lists no requirements")
|
|
441
|
+
kept_elsewhere = ("constraints", "overrides", "build-constraint-dependencies")
|
|
442
|
+
unsupported = tuple(key for key in kept_elsewhere if tool.get(key))
|
|
443
|
+
tool_name = normalize(requirements[0]["name"])
|
|
444
|
+
if any(normalize(ep.get("from", tool_name)) != tool_name for ep in tool.get("entrypoints") or []):
|
|
445
|
+
unsupported += ("executables from another package (--with-executables-from)",)
|
|
446
|
+
return cls(requirements, tool.get("python"), dict(tool.get("options") or {}), unsupported)
|
|
447
|
+
|
|
448
|
+
def install_args(self, *, add: list[str] = (), drop: list[str] = (),
|
|
449
|
+
default_index: Optional[str] = None) -> tuple[str, ...]:
|
|
450
|
+
"""`uv tool install` arguments for this tool, with ``add`` joined and ``drop`` left out.
|
|
451
|
+
``default_index`` replaces the receipt's own default index, which uv takes only once."""
|
|
452
|
+
if self.unsupported:
|
|
453
|
+
raise InstallerError(
|
|
454
|
+
f"the uv tool was installed with {', '.join(self.unsupported)}, which agent-env cannot pass back to "
|
|
455
|
+
"`uv tool install`; make this change with uv yourself"
|
|
456
|
+
)
|
|
457
|
+
tool, *extras = self.requirements
|
|
458
|
+
dropped = {normalize(n) for n in drop}
|
|
459
|
+
if normalize(tool["name"]) in dropped:
|
|
460
|
+
raise InstallerError(f"{tool['name']} is the tool itself; `uv tool uninstall {tool['name']}` removes it")
|
|
461
|
+
listed = {normalize(e["name"]) for e in extras}
|
|
462
|
+
missing = dropped - listed
|
|
463
|
+
if missing:
|
|
464
|
+
raise InstallerError(
|
|
465
|
+
f"the tool was not installed `--with` {', '.join(sorted(missing))}, so it is a dependency of "
|
|
466
|
+
"another package there"
|
|
467
|
+
)
|
|
468
|
+
# A bare name that is listed already asks for nothing new: its entry stays, pin and all.
|
|
469
|
+
unchanged = {normalize(spec.strip()) for spec in add if _NAME.fullmatch(spec.strip())} & listed
|
|
470
|
+
replaced = {requirement_name(spec) for spec in add} - {None} - unchanged
|
|
471
|
+
_check_source(tool, fix="reinstall the tool with uv")
|
|
472
|
+
editable = _editable(tool)
|
|
473
|
+
args: list[str] = ["-e", editable] if editable else [_spec(tool)]
|
|
474
|
+
for entry in extras:
|
|
475
|
+
if normalize(entry["name"]) not in dropped | replaced:
|
|
476
|
+
_check_source(entry)
|
|
477
|
+
editable = _editable(entry)
|
|
478
|
+
args += ["--with-editable", editable] if editable else ["--with", _spec(entry)]
|
|
479
|
+
for spec in add:
|
|
480
|
+
if normalize(spec.strip()) not in unchanged:
|
|
481
|
+
args += ["--with", spec]
|
|
482
|
+
if self.python:
|
|
483
|
+
args += ["--python", self.python]
|
|
484
|
+
return tuple(args) + self._option_args(default_index)
|
|
485
|
+
|
|
486
|
+
def _option_args(self, default_index: Optional[str]) -> tuple[str, ...]:
|
|
487
|
+
args: list[str] = []
|
|
488
|
+
indexes: list[tuple[str, Optional[str], bool]] = []
|
|
489
|
+
for key, value in self.options.items():
|
|
490
|
+
if key in _RECEIPT_FLAGS:
|
|
491
|
+
args += [_RECEIPT_FLAGS[key]] if value else []
|
|
492
|
+
elif key in _RECEIPT_VALUES and _RECEIPT_VALUES[key] in ("--default-index", "--index"):
|
|
493
|
+
for item in value if isinstance(value, list) else [value]:
|
|
494
|
+
indexes.append((str(item), None, _RECEIPT_VALUES[key] == "--default-index"))
|
|
495
|
+
elif key in _RECEIPT_VALUES:
|
|
496
|
+
for item in value if isinstance(value, list) else [value]:
|
|
497
|
+
args += [_RECEIPT_VALUES[key], str(item)]
|
|
498
|
+
elif key == "index":
|
|
499
|
+
for index in value:
|
|
500
|
+
if isinstance(index, dict):
|
|
501
|
+
indexes.append((index["url"], index.get("name"), bool(index.get("default"))))
|
|
502
|
+
else:
|
|
503
|
+
indexes.append((str(index), None, False))
|
|
504
|
+
else:
|
|
505
|
+
raise InstallerError(
|
|
506
|
+
f"the uv tool receipt sets {key!r}, which agent-env cannot pass back to `uv tool install`; "
|
|
507
|
+
"make this change with uv yourself"
|
|
508
|
+
)
|
|
509
|
+
return tuple(args) + _index_args(indexes, default_index)
|
|
510
|
+
|
|
511
|
+
|
|
512
|
+
def _index_args(indexes: list[tuple[str, Optional[str], bool]], default_index: Optional[str]) -> tuple[str, ...]:
|
|
513
|
+
"""Each index once, and one default. uv records an index from its config and the same index
|
|
514
|
+
passed as a flag side by side, and refuses `--default-index` twice, so indexes are merged by
|
|
515
|
+
URL, and a name is kept so the next install matches the configured index instead of adding
|
|
516
|
+
another. ``default_index`` replaces the receipt's default."""
|
|
517
|
+
merged: dict[str, tuple[Optional[str], bool]] = {}
|
|
518
|
+
for url, name, default in indexes:
|
|
519
|
+
known_name, known_default = merged.get(url, (None, False))
|
|
520
|
+
merged[url] = (known_name or name, known_default or default)
|
|
521
|
+
spelled = {url: f"{name}={url}" if name else url for url, (name, _) in merged.items()}
|
|
522
|
+
chosen = default_index or next((spelled[url] for url, (_, default) in merged.items() if default), None)
|
|
523
|
+
args: list[str] = []
|
|
524
|
+
for url, (_, default) in merged.items():
|
|
525
|
+
if not (default and (default_index or spelled[url] == chosen)):
|
|
526
|
+
args += ["--index", spelled[url]]
|
|
527
|
+
return tuple(args) + (("--default-index", chosen) if chosen else ())
|
|
528
|
+
|
|
529
|
+
|
|
530
|
+
def _check_source(entry: dict, fix: Optional[str] = None) -> None:
|
|
531
|
+
"""Refuse up front when a requirement comes from a local file or directory that is gone: uv
|
|
532
|
+
cannot rebuild the tool without it, whatever the change is."""
|
|
533
|
+
url = entry.get("url") or ""
|
|
534
|
+
local = entry.get("path") or entry.get("directory") or _editable(entry) or (
|
|
535
|
+
unquote(urlparse(url).path) if url.startswith("file:") else None)
|
|
536
|
+
if local and not Path(local).exists():
|
|
537
|
+
name = entry["name"]
|
|
538
|
+
fix = fix or (f"add it again from where it is now (`agent-env plugin add '{name} @ file:///path/to/it'`), or "
|
|
539
|
+
f"remove it (`agent-env plugin remove {name}`)")
|
|
540
|
+
raise InstallerError(f"the uv tool installs {name} from {local}, which no longer exists, so uv cannot rebuild "
|
|
541
|
+
f"it; {fix}")
|
|
542
|
+
|
|
543
|
+
|
|
544
|
+
def _editable(entry: dict) -> Optional[str]:
|
|
545
|
+
"""The path of an editable requirement: uv writes `editable = "<path>"`."""
|
|
546
|
+
value = entry.get("editable")
|
|
547
|
+
if isinstance(value, str):
|
|
548
|
+
return value
|
|
549
|
+
return str(entry.get("directory") or entry.get("path")) if value else None
|
|
550
|
+
|
|
551
|
+
|
|
552
|
+
def _spec(entry: dict) -> str:
|
|
553
|
+
"""A receipt requirement as the PEP 508 spec `uv tool install` accepts."""
|
|
554
|
+
unknown = set(entry) - _RECEIPT_REQUIREMENT_KEYS
|
|
555
|
+
if unknown:
|
|
556
|
+
raise InstallerError(
|
|
557
|
+
f"the uv tool receipt's requirement {entry.get('name')!r} uses {', '.join(sorted(unknown))}, which "
|
|
558
|
+
"agent-env cannot pass back to `uv tool install`; make this change with uv yourself"
|
|
559
|
+
)
|
|
560
|
+
name = entry["name"] + (f"[{','.join(entry['extras'])}]" if entry.get("extras") else "")
|
|
561
|
+
marker = f" ; {entry['marker']}" if entry.get("marker") else ""
|
|
562
|
+
if entry.get("git"):
|
|
563
|
+
# uv keeps the ref and subdirectory in the URL's query: `https://host/repo?rev=v1`.
|
|
564
|
+
parsed = urlparse(entry["git"])
|
|
565
|
+
query = {key: values[0] for key, values in parse_qs(parsed.query).items()}
|
|
566
|
+
ref = next((v for k in ("rev", "tag", "branch") if (v := entry.get(k) or query.get(k))), None)
|
|
567
|
+
subdirectory = entry.get("subdirectory") or query.get("subdirectory")
|
|
568
|
+
url = f"git+{parsed._replace(query='', fragment='').geturl()}" + (f"@{ref}" if ref else "")
|
|
569
|
+
url += f"#subdirectory={subdirectory}" if subdirectory else ""
|
|
570
|
+
return f"{name} @ {url}{marker}"
|
|
571
|
+
if entry.get("url"):
|
|
572
|
+
subdirectory = f"#subdirectory={entry['subdirectory']}" if entry.get("subdirectory") else ""
|
|
573
|
+
return f"{name} @ {entry['url']}{subdirectory}{marker}"
|
|
574
|
+
if entry.get("path") or entry.get("directory"):
|
|
575
|
+
return f"{name} @ {Path(entry.get('path') or entry['directory']).resolve().as_uri()}{marker}"
|
|
576
|
+
return f"{name}{entry.get('specifier', '')}{marker}"
|