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.
Files changed (312) hide show
  1. agent_env/__init__.py +0 -0
  2. agent_env/a2a_agent/__init__.py +23 -0
  3. agent_env/a2a_agent/a2a_agent.py +600 -0
  4. agent_env/a2a_agent/conversation_store.py +356 -0
  5. agent_env/a2a_agent/object_transfer.py +609 -0
  6. agent_env/a2a_agent/protocol.py +238 -0
  7. agent_env/a2a_agent/store.py +201 -0
  8. agent_env/a2a_agent/validator.py +901 -0
  9. agent_env/artifact/__init__.py +48 -0
  10. agent_env/artifact/artifact.py +74 -0
  11. agent_env/artifact/artifacts/__init__.py +0 -0
  12. agent_env/artifact/artifacts/cli.py +83 -0
  13. agent_env/artifact/artifacts/docker_image.py +457 -0
  14. agent_env/artifact/artifacts/environment.py +89 -0
  15. agent_env/artifact/artifacts/environment_universe.py +156 -0
  16. agent_env/artifact/artifacts/file.py +214 -0
  17. agent_env/artifact/artifacts/file_artifact_universe.py +206 -0
  18. agent_env/artifact/artifacts/skill.py +206 -0
  19. agent_env/artifact/artifacts/vm_image.py +95 -0
  20. agent_env/artifact/ref.py +15 -0
  21. agent_env/artifact/registry.py +251 -0
  22. agent_env/artifact/store.py +295 -0
  23. agent_env/artifact/universe.py +38 -0
  24. agent_env/attribution.py +41 -0
  25. agent_env/bundle/__init__.py +4 -0
  26. agent_env/bundle/_fs.py +128 -0
  27. agent_env/bundle/authoring.py +239 -0
  28. agent_env/bundle/installed.py +175 -0
  29. agent_env/bundle/ledger.py +269 -0
  30. agent_env/bundle/materialize.py +204 -0
  31. agent_env/bundle/parse.py +594 -0
  32. agent_env/bundle/plan.py +414 -0
  33. agent_env/bundle/resolve.py +404 -0
  34. agent_env/bundle/run.py +361 -0
  35. agent_env/cli/__init__.py +69 -0
  36. agent_env/cli/__main__.py +10 -0
  37. agent_env/cli/_installers.py +576 -0
  38. agent_env/cli/_plugin_changes.py +947 -0
  39. agent_env/cli/a2a_agent/__init__.py +22 -0
  40. agent_env/cli/a2a_agent/add_skill.py +97 -0
  41. agent_env/cli/a2a_agent/deploy.py +60 -0
  42. agent_env/cli/a2a_agent/get.py +15 -0
  43. agent_env/cli/a2a_agent/get_instance.py +26 -0
  44. agent_env/cli/a2a_agent/put.py +78 -0
  45. agent_env/cli/a2a_agent/validate.py +56 -0
  46. agent_env/cli/artifact/__init__.py +20 -0
  47. agent_env/cli/artifact/cli.py +83 -0
  48. agent_env/cli/artifact/environment.py +44 -0
  49. agent_env/cli/artifact/environment_universe.py +163 -0
  50. agent_env/cli/artifact/file_artifact_universe.py +281 -0
  51. agent_env/cli/artifact/skill.py +128 -0
  52. agent_env/cli/banner.py +25 -0
  53. agent_env/cli/config.py +263 -0
  54. agent_env/cli/env/__init__.py +31 -0
  55. agent_env/cli/env/deploy.py +112 -0
  56. agent_env/cli/env/gateway.py +57 -0
  57. agent_env/cli/env/get_instance.py +40 -0
  58. agent_env/cli/env/mcp_server.py +410 -0
  59. agent_env/cli/env/multi.py +282 -0
  60. agent_env/cli/env/service_db.py +99 -0
  61. agent_env/cli/env/snapshot.py +35 -0
  62. agent_env/cli/env/state/__init__.py +6 -0
  63. agent_env/cli/env/state/init.py +108 -0
  64. agent_env/cli/env/state/teardown.py +44 -0
  65. agent_env/cli/env/website.py +216 -0
  66. agent_env/cli/env/website_browser.py +67 -0
  67. agent_env/cli/eval/__init__.py +16 -0
  68. agent_env/cli/eval/add_tasks.py +63 -0
  69. agent_env/cli/eval/create.py +49 -0
  70. agent_env/cli/eval/run.py +194 -0
  71. agent_env/cli/identity/__init__.py +5 -0
  72. agent_env/cli/identity/client_identity.py +37 -0
  73. agent_env/cli/plugin.py +438 -0
  74. agent_env/cli/run.py +285 -0
  75. agent_env/cli/task/__init__.py +21 -0
  76. agent_env/cli/task/create.py +109 -0
  77. agent_env/cli/task/get.py +17 -0
  78. agent_env/cli/task/get_instance.py +34 -0
  79. agent_env/cli/task/run.py +615 -0
  80. agent_env/cli/task/validate.py +31 -0
  81. agent_env/cli/up.py +123 -0
  82. agent_env/cli/utils.py +183 -0
  83. agent_env/config/__init__.py +50 -0
  84. agent_env/config/describe.py +1067 -0
  85. agent_env/config/errors.py +13 -0
  86. agent_env/config/loader.py +245 -0
  87. agent_env/config/model.py +154 -0
  88. agent_env/config/paths.py +25 -0
  89. agent_env/config/plugin_tables.py +101 -0
  90. agent_env/config/provenance.py +134 -0
  91. agent_env/config/runtime.py +1064 -0
  92. agent_env/config/snapshot.py +81 -0
  93. agent_env/entity_refs.py +186 -0
  94. agent_env/env/__init__.py +49 -0
  95. agent_env/env/env.py +433 -0
  96. agent_env/env/env_artifact_store.py +87 -0
  97. agent_env/env/envs/__init__.py +7 -0
  98. agent_env/env/envs/_deployment.py +281 -0
  99. agent_env/env/envs/gateway_server.py +32 -0
  100. agent_env/env/envs/mcp_server.py +387 -0
  101. agent_env/env/envs/multi_env.py +780 -0
  102. agent_env/env/envs/service_db/Dockerfile +20 -0
  103. agent_env/env/envs/service_db/Dockerfile.db-mcp +42 -0
  104. agent_env/env/envs/service_db/Dockerfile.db-web +8 -0
  105. agent_env/env/envs/service_db.py +92 -0
  106. agent_env/env/envs/website.py +294 -0
  107. agent_env/env/envs/website_browser/Dockerfile +40 -0
  108. agent_env/env/envs/website_browser/__init__.py +17 -0
  109. agent_env/env/envs/website_browser/entrypoint.sh +13 -0
  110. agent_env/env/gateway/Dockerfile +14 -0
  111. agent_env/env/gateway/__init__.py +37 -0
  112. agent_env/env/gateway/clock.py +184 -0
  113. agent_env/env/gateway/constants.py +190 -0
  114. agent_env/env/gateway/entrypoint.py +156 -0
  115. agent_env/env/gateway/gateway.py +1095 -0
  116. agent_env/env/gateway/get_time.py +60 -0
  117. agent_env/env/gateway/requirements.txt +4 -0
  118. agent_env/env/gateway/triggers.py +1193 -0
  119. agent_env/env/legacy_protocol.py +146 -0
  120. agent_env/env/registry.py +93 -0
  121. agent_env/env/snapshot_store.py +372 -0
  122. agent_env/env/store.py +411 -0
  123. agent_env/eval/__init__.py +14 -0
  124. agent_env/eval/eval.py +68 -0
  125. agent_env/eval/store.py +116 -0
  126. agent_env/examples/hello/README.md +9 -0
  127. agent_env/examples/hello/artifacts/greeting/check.sh +1 -0
  128. agent_env/examples/hello/artifacts/greeting/hello.txt +1 -0
  129. agent_env/examples/hello/tasks/hello.json +10 -0
  130. agent_env/explorer/__init__.py +12 -0
  131. agent_env/explorer/app.py +277 -0
  132. agent_env/explorer/openapi_docs.py +242 -0
  133. agent_env/explorer/plugin.py +95 -0
  134. agent_env/explorer/routers/__init__.py +1 -0
  135. agent_env/explorer/routers/common.py +174 -0
  136. agent_env/explorer/routers/conversations.py +25 -0
  137. agent_env/explorer/routers/objects.py +112 -0
  138. agent_env/explorer/routers/runs.py +475 -0
  139. agent_env/plugins/__init__.py +59 -0
  140. agent_env/plugins/_cli.py +244 -0
  141. agent_env/plugins/_discovery.py +97 -0
  142. agent_env/plugins/_inventory.py +262 -0
  143. agent_env/plugins/_registration.py +268 -0
  144. agent_env/plugins/_report.py +47 -0
  145. agent_env/plugins/_requirements.py +55 -0
  146. agent_env/providers/__init__.py +37 -0
  147. agent_env/providers/env_providers/__init__.py +12 -0
  148. agent_env/providers/env_providers/constants.py +13 -0
  149. agent_env/providers/env_providers/env_gateway_provider.py +1354 -0
  150. agent_env/providers/env_providers/env_provider.py +237 -0
  151. agent_env/providers/env_providers/env_server_provider.py +133 -0
  152. agent_env/providers/env_state/__init__.py +49 -0
  153. agent_env/providers/env_state/env_state_provider.py +554 -0
  154. agent_env/providers/env_state/local_postgres.py +390 -0
  155. agent_env/providers/env_state/store.py +112 -0
  156. agent_env/providers/sandbox_providers/__init__.py +29 -0
  157. agent_env/providers/sandbox_providers/chained_sandbox_provider.py +93 -0
  158. agent_env/providers/sandbox_providers/e2b/__init__.py +6 -0
  159. agent_env/providers/sandbox_providers/e2b/provider.py +376 -0
  160. agent_env/providers/sandbox_providers/e2b/sandbox.py +342 -0
  161. agent_env/providers/sandbox_providers/e2b/template.py +158 -0
  162. agent_env/providers/sandbox_providers/local_sandbox.py +408 -0
  163. agent_env/providers/sandbox_providers/modal_sandbox.py +500 -0
  164. agent_env/providers/sandbox_providers/modal_vm_sandbox.py +466 -0
  165. agent_env/providers/sandbox_providers/sandbox.py +387 -0
  166. agent_env/providers/sandbox_providers/sandbox_provider.py +614 -0
  167. agent_env/py.typed +0 -0
  168. agent_env/runner/__init__.py +16 -0
  169. agent_env/runner/local_runner.py +190 -0
  170. agent_env/runner/runner.py +127 -0
  171. agent_env/runner/store.py +94 -0
  172. agent_env/store/__init__.py +126 -0
  173. agent_env/store/_google.py +68 -0
  174. agent_env/store/base.py +33 -0
  175. agent_env/store/document_store/__init__.py +60 -0
  176. agent_env/store/document_store/document_store.py +519 -0
  177. agent_env/store/document_store/dynamodb_document_store.py +306 -0
  178. agent_env/store/document_store/evaluation.py +199 -0
  179. agent_env/store/document_store/firestore_mongo_document_store.py +242 -0
  180. agent_env/store/document_store/mongo_document_store.py +259 -0
  181. agent_env/store/document_store/sqlite_document_store.py +314 -0
  182. agent_env/store/ids.py +123 -0
  183. agent_env/store/image_store/__init__.py +34 -0
  184. agent_env/store/image_store/ecr_image_store.py +131 -0
  185. agent_env/store/image_store/google_credentials.py +113 -0
  186. agent_env/store/image_store/image_store.py +113 -0
  187. agent_env/store/image_store/local_registry_image_store.py +106 -0
  188. agent_env/store/image_store/oci_registry_credentials.py +196 -0
  189. agent_env/store/local_state.py +27 -0
  190. agent_env/store/object_store/__init__.py +24 -0
  191. agent_env/store/object_store/gcs_object_store.py +415 -0
  192. agent_env/store/object_store/local_object_store.py +143 -0
  193. agent_env/store/object_store/object_store.py +198 -0
  194. agent_env/store/object_store/s3_object_store.py +354 -0
  195. agent_env/store/query.py +112 -0
  196. agent_env/store/routing.py +609 -0
  197. agent_env/store/secret_store/__init__.py +19 -0
  198. agent_env/store/secret_store/aws_secrets_manager_secret_store.py +293 -0
  199. agent_env/store/secret_store/gcp_secret_manager_secret_store.py +319 -0
  200. agent_env/store/secret_store/local_secret_store.py +47 -0
  201. agent_env/store/secret_store/secret_store.py +19 -0
  202. agent_env/task/__init__.py +27 -0
  203. agent_env/task/interrupts.py +109 -0
  204. agent_env/task/registry.py +27 -0
  205. agent_env/task/step_journal.py +99 -0
  206. agent_env/task/store.py +940 -0
  207. agent_env/task/task.py +815 -0
  208. agent_env/task/teardown.py +142 -0
  209. agent_env/task_step/__init__.py +47 -0
  210. agent_env/task_step/context.py +195 -0
  211. agent_env/task_step/context_ops.py +224 -0
  212. agent_env/task_step/registry.py +182 -0
  213. agent_env/task_step/review_store.py +118 -0
  214. agent_env/task_step/snapshot_utils/__init__.py +2 -0
  215. agent_env/task_step/snapshot_utils/agent_state_capture.py +261 -0
  216. agent_env/task_step/snapshot_utils/snapshot_series.py +631 -0
  217. agent_env/task_step/store.py +129 -0
  218. agent_env/task_step/task_step.py +173 -0
  219. agent_env/task_step/task_steps/__init__.py +27 -0
  220. agent_env/task_step/task_steps/a2a_agent_validator/__init__.py +31 -0
  221. agent_env/task_step/task_steps/a2a_agent_validator/fixtures/README.md +158 -0
  222. agent_env/task_step/task_steps/a2a_agent_validator/fixtures/clip.m4a +0 -0
  223. agent_env/task_step/task_steps/a2a_agent_validator/fixtures/clip.mp3 +0 -0
  224. agent_env/task_step/task_steps/a2a_agent_validator/fixtures/clip.mp4 +0 -0
  225. agent_env/task_step/task_steps/a2a_agent_validator/fixtures/clip.ogg +0 -0
  226. agent_env/task_step/task_steps/a2a_agent_validator/fixtures/clip.wav +0 -0
  227. agent_env/task_step/task_steps/a2a_agent_validator/fixtures/document.pdf +0 -0
  228. agent_env/task_step/task_steps/a2a_agent_validator/fixtures/red.gif +0 -0
  229. agent_env/task_step/task_steps/a2a_agent_validator/fixtures/red.jpg +0 -0
  230. agent_env/task_step/task_steps/a2a_agent_validator/fixtures/red.png +0 -0
  231. agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_agent_card.py +103 -0
  232. agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_agent_config_identity.py +69 -0
  233. agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_agent_mcp.py +178 -0
  234. agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_core_protocol.py +67 -0
  235. agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_install.py +115 -0
  236. agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_litellm_attribution.py +124 -0
  237. agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_litellm_attribution_runtime.py +173 -0
  238. agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_modalities.py +270 -0
  239. agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_peer_agents.py +102 -0
  240. agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_role.py +151 -0
  241. agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_skill_config.py +194 -0
  242. agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_snapshot.py +111 -0
  243. agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_system_prompt.py +215 -0
  244. agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_trajectory.py +164 -0
  245. agent_env/task_step/task_steps/add_skills.py +240 -0
  246. agent_env/task_step/task_steps/apply_server_config.py +288 -0
  247. agent_env/task_step/task_steps/collect_artifacts.py +940 -0
  248. agent_env/task_step/task_steps/deploy_agent.py +626 -0
  249. agent_env/task_step/task_steps/deploy_env.py +197 -0
  250. agent_env/task_step/task_steps/deploy_human_agent.py +100 -0
  251. agent_env/task_step/task_steps/deploy_sandbox.py +170 -0
  252. agent_env/task_step/task_steps/env_card_validator/__init__.py +4 -0
  253. agent_env/task_step/task_steps/env_card_validator/verify_env_card.py +109 -0
  254. agent_env/task_step/task_steps/env_card_validator/verify_env_core_protocol.py +108 -0
  255. agent_env/task_step/task_steps/install_agent.py +376 -0
  256. agent_env/task_step/task_steps/load_artifact.py +775 -0
  257. agent_env/task_step/task_steps/mcp_cli_builder/__init__.py +4 -0
  258. agent_env/task_step/task_steps/mcp_cli_builder/build_mcp_cli.py +201 -0
  259. agent_env/task_step/task_steps/mcp_cli_builder/codegen.py +627 -0
  260. agent_env/task_step/task_steps/mcp_env_validator/__init__.py +44 -0
  261. agent_env/task_step/task_steps/mcp_env_validator/validation_gate_aggregator.py +102 -0
  262. agent_env/task_step/task_steps/mcp_env_validator/verify_mcp_env_assessment.py +78 -0
  263. agent_env/task_step/task_steps/mcp_env_validator/verify_mcp_tool_schema.py +152 -0
  264. agent_env/task_step/task_steps/mcp_env_validator/verify_spec_conformance.py +486 -0
  265. agent_env/task_step/task_steps/modify_env_tool_access.py +80 -0
  266. agent_env/task_step/task_steps/multienv_validator/__init__.py +3 -0
  267. agent_env/task_step/task_steps/multienv_validator/combine_universe_verdicts.py +107 -0
  268. agent_env/task_step/task_steps/multienv_validator/universe_comparison.py +253 -0
  269. agent_env/task_step/task_steps/multienv_validator/verify_universe_agent_judge.py +180 -0
  270. agent_env/task_step/task_steps/multienv_validator/verify_universe_roundtrip.py +241 -0
  271. agent_env/task_step/task_steps/peer_agents.py +92 -0
  272. agent_env/task_step/task_steps/prompt_agent.py +900 -0
  273. agent_env/task_step/task_steps/register_agent_triggers.py +113 -0
  274. agent_env/task_step/task_steps/register_env_triggers.py +97 -0
  275. agent_env/task_step/task_steps/reset_env.py +71 -0
  276. agent_env/task_step/task_steps/review.py +152 -0
  277. agent_env/task_step/task_steps/run_code.py +461 -0
  278. agent_env/task_step/task_steps/run_code_runner.py +52 -0
  279. agent_env/task_step/task_steps/run_docker_container.py +380 -0
  280. agent_env/task_step/task_steps/sandbox_utils/__init__.py +0 -0
  281. agent_env/task_step/task_steps/sandbox_utils/sandbox_utils.py +79 -0
  282. agent_env/task_step/task_steps/snapshot_agent_state.py +205 -0
  283. agent_env/task_step/task_steps/snapshot_env.py +637 -0
  284. agent_env/task_step/task_steps/sync_env_clock.py +132 -0
  285. agent_env/task_step/task_steps/teardown_sandboxes.py +170 -0
  286. agent_env/task_step/task_steps/verifiers/__init__.py +23 -0
  287. agent_env/task_step/task_steps/verifiers/agent_prompt_response_verifier.py +166 -0
  288. agent_env/task_step/task_steps/verifiers/aggregate_verifiers.py +90 -0
  289. agent_env/task_step/task_steps/verifiers/env_outcome_verifier.py +127 -0
  290. agent_env/task_step/task_steps/verifiers/judge_utils/__init__.py +2 -0
  291. agent_env/task_step/task_steps/verifiers/judge_utils/frame_selection.py +377 -0
  292. agent_env/task_step/task_steps/verifiers/judge_utils/judge_output_format.py +1293 -0
  293. agent_env/task_step/task_steps/verifiers/judge_utils/trajectory_filter.py +514 -0
  294. agent_env/task_step/task_steps/verifiers/rubrics_verifier.py +1318 -0
  295. agent_env/task_step/task_steps/verifiers/run_container_unit_tests_verifier.py +434 -0
  296. agent_env/task_step/task_steps/verifiers/scoring.py +40 -0
  297. agent_env/task_step/task_steps/verifiers/verify_sandbox.py +308 -0
  298. agent_env/task_step/thread_work.py +61 -0
  299. agent_env/utils/__init__.py +0 -0
  300. agent_env/utils/card_naming.py +108 -0
  301. agent_env/utils/deprecation.py +109 -0
  302. agent_env/utils/docker_build.py +29 -0
  303. agent_env/utils/exec_retry.py +77 -0
  304. agent_env/utils/litellm_attribution.py +59 -0
  305. agent_env/utils/paths.py +20 -0
  306. agentenv_framework-0.9.1254.dist-info/METADATA +394 -0
  307. agentenv_framework-0.9.1254.dist-info/RECORD +312 -0
  308. agentenv_framework-0.9.1254.dist-info/WHEEL +4 -0
  309. agentenv_framework-0.9.1254.dist-info/entry_points.txt +5 -0
  310. agentenv_framework-0.9.1254.dist-info/licenses/LICENSE +202 -0
  311. agentenv_framework-0.9.1254.dist-info/licenses/NOTICE +4 -0
  312. agentenv_framework-0.9.1254.dist-info/licenses/THIRD_PARTY_NOTICES.md +7665 -0
@@ -0,0 +1,947 @@
1
+ """`agent-env plugin add` and `remove`: plan, preview, run through the installer, verify, roll back.
2
+
3
+ Every check that needs installed state runs in a fresh interpreter of the environment, because
4
+ this process has already imported its plugins and cannot see a change to them.
5
+ """
6
+
7
+ import difflib
8
+ import hashlib
9
+ import importlib.metadata
10
+ import importlib.util
11
+ import json
12
+ import os
13
+ import shlex
14
+ import shutil
15
+ import signal
16
+ import subprocess
17
+ import sys
18
+ import sysconfig
19
+ import tempfile
20
+ from collections.abc import Iterator
21
+ from contextlib import contextmanager
22
+ from dataclasses import dataclass, field
23
+ from pathlib import Path
24
+ from typing import Callable, Optional
25
+ from urllib.parse import unquote, urlparse
26
+
27
+ import click
28
+
29
+ from agent_env.cli import _installers
30
+ from agent_env.cli._installers import Environment, InstallerError, Plan, ToolReceipt, normalize
31
+ from agent_env.config import get_config
32
+ from agent_env.config.loader import interpolate
33
+ from agent_env.config.paths import state_root
34
+ from agent_env.store.routing import RoutingDocumentStore
35
+ from agent_env.plugins import ARTIFACTS, ENV_PROVIDERS, ENVS, SANDBOX_PROVIDERS, STATE_PROVIDERS, TASK_STEPS
36
+ from agent_env.plugins._report import FORMAT_VERSION
37
+ from agent_env.store.document_store.document_store import Filter, In
38
+
39
+ try:
40
+ import fcntl
41
+ except ImportError: # Windows, which agent-env does not target: changes run without the lock.
42
+ fcntl = None
43
+
44
+ # Every installed distribution: its version and source, what this environment needs of it, its
45
+ # agent_env entry points, and for a plugin the modules it owns.
46
+ _SNAPSHOT_PROBE = r"""
47
+ import importlib.metadata as md, json, re, sys
48
+ try:
49
+ from packaging.requirements import Requirement
50
+ except Exception:
51
+ Requirement = None
52
+ def norm(name):
53
+ return re.sub(r"[-_.]+", "-", name).lower()
54
+ def needed(requirement, extra=""):
55
+ if Requirement is None:
56
+ return not extra and "extra ==" not in requirement.replace('"', "").replace("'", "")
57
+ try:
58
+ marker = Requirement(requirement).marker
59
+ except Exception:
60
+ return not extra
61
+ return marker is None or marker.evaluate({"extra": extra})
62
+ def extras_of(requirement):
63
+ try:
64
+ return sorted(norm(e) for e in Requirement(requirement).extras) if Requirement else []
65
+ except Exception:
66
+ return []
67
+ def modules(dist, values):
68
+ found = set()
69
+ for f in dist.files or []:
70
+ if f.suffix == ".py" and f.parts and not f.parts[0].startswith(".."):
71
+ dotted = list(f.parts[:-1]) + ([] if f.stem == "__init__" else [f.stem])
72
+ if dotted and all(part.isidentifier() for part in dotted):
73
+ found.add(".".join(dotted))
74
+ if not found:
75
+ # An editable install lists no source files; its entry points still name its modules.
76
+ for value in values:
77
+ module = value.split(":", 1)[0].strip()
78
+ found.update(filter(None, {module, module.rpartition(".")[0]}))
79
+ return sorted(found)
80
+ out = {}
81
+ for dist in md.distributions():
82
+ try:
83
+ name = dist.metadata["Name"]
84
+ if not name:
85
+ continue
86
+ requires, wants, extras = [], {}, {}
87
+ provided = [norm(e) for e in dist.metadata.get_all("Provides-Extra") or []]
88
+ for requirement in dist.requires or []:
89
+ match = re.match(r"\s*([A-Za-z0-9][A-Za-z0-9._-]*)", requirement)
90
+ if not match:
91
+ continue
92
+ dep = norm(match.group(1))
93
+ if needed(requirement):
94
+ requires.append(dep)
95
+ if extras_of(requirement):
96
+ wants[dep] = sorted(set(wants.get(dep, [])) | set(extras_of(requirement)))
97
+ for extra in provided:
98
+ if not needed(requirement) and needed(requirement, extra):
99
+ asked = extras.setdefault(extra, {}).setdefault(dep, [])
100
+ asked[:] = sorted(set(asked) | set(extras_of(requirement)))
101
+ points = [ep for ep in dist.entry_points if ep.group.startswith("agent_env.")]
102
+ direct = dist.read_text("direct_url.json")
103
+ # requires: what it always needs; wants: the extras it asks of those; extras: what each of
104
+ # its own extras adds, with the extras it asks of each.
105
+ entry = {"name": name, "version": dist.version, "requires": requires, "wants": wants, "extras": extras,
106
+ "entry_points": [[ep.group, ep.name] for ep in points],
107
+ "direct_url": json.loads(direct) if direct else None}
108
+ if points:
109
+ entry["modules"] = modules(dist, [ep.value for ep in points])
110
+ except Exception:
111
+ continue
112
+ out[norm(name)] = entry
113
+ json.dump(out, sys.stdout)
114
+ """
115
+ _OK = ("active", "replaced")
116
+ _UNNAMED_PIPX_HINT = ("pipx leaves a package it already has as it is. To upgrade an installed plugin from a URL or a "
117
+ "directory, name it: `agent-env plugin add 'NAME @ URL'`.")
118
+ # How long the fresh-interpreter snapshot, the `plugin show` check and the resolver dry run may take.
119
+ _SNAPSHOT_TIMEOUT_S = 120
120
+ _INSPECT_TIMEOUT_S = 300
121
+ _PREVIEW_TIMEOUT_S = 600
122
+
123
+ # How long `show` and `remove` wait for a package's entry points to import in the fresh interpreter.
124
+ _PROBE_TIMEOUT_S = 120
125
+ # Loads one distribution's entry points in a fresh interpreter and writes AGENT_ENV_CONFIG after
126
+ # to the file in argv[2]. The other CLI plugins are hidden, because importing agent_env.cli would
127
+ # otherwise load them all and credit their import effects to this one.
128
+ _CONFIG_PROBE = """
129
+ import importlib.metadata as md, json, os, sys
130
+ real = md.entry_points
131
+ def entry_points(**params):
132
+ if params.get("group") in ("agent_env.cli_plugins", "agent_env.cli_root_options"):
133
+ return md.EntryPoints(())
134
+ return real(**params)
135
+ md.entry_points = entry_points
136
+ os.environ.pop("AGENT_ENV_CONFIG", None)
137
+ for ep in md.distribution(sys.argv[1]).entry_points:
138
+ # A bundle is a folder; agent-env never imports its package.
139
+ if ep.group.startswith("agent_env.") and ep.group != "agent_env.bundles":
140
+ try:
141
+ ep.load()
142
+ except Exception:
143
+ pass
144
+ with open(sys.argv[2], "w") as out:
145
+ json.dump(os.environ.get("AGENT_ENV_CONFIG"), out)
146
+ """
147
+
148
+ Snapshot = dict[str, dict]
149
+ Runner = Callable[[tuple[str, ...], Optional[Path]], int]
150
+
151
+
152
+ def run(command: tuple[str, ...], cwd: Optional[Path] = None) -> int:
153
+ """Run one installer command, its output going straight to the terminal.
154
+
155
+ The installer starts with Ctrl-C ignored: stopped halfway, it leaves packages without their
156
+ metadata, which no installer can read or roll back. Ctrl-C reaches agent-env, which lets it
157
+ finish and then rolls back; a second Ctrl-C stops it at once. It keeps the terminal, so its own
158
+ prompts, such as git's for credentials, still work.
159
+ """
160
+ previous = signal.signal(signal.SIGINT, signal.SIG_IGN)
161
+ try:
162
+ proc = subprocess.Popen(list(command), cwd=cwd)
163
+ finally:
164
+ signal.signal(signal.SIGINT, previous)
165
+ try:
166
+ return proc.wait()
167
+ except KeyboardInterrupt:
168
+ click.echo("Interrupted; letting the installer finish before restoring (Ctrl-C again stops it now).", err=True)
169
+ try:
170
+ proc.wait()
171
+ except KeyboardInterrupt:
172
+ proc.terminate()
173
+ _wait_out(proc)
174
+ raise
175
+
176
+
177
+ def _wait_out(proc: subprocess.Popen) -> None:
178
+ while True:
179
+ try:
180
+ proc.wait()
181
+ return
182
+ except KeyboardInterrupt:
183
+ proc.kill()
184
+
185
+
186
+ def broken() -> set[Path]:
187
+ """Package records in this environment without their METADATA: what an installer stopped
188
+ halfway leaves. No installer can read them, so every later change fails until they are gone."""
189
+ roots = {Path(sysconfig.get_path("purelib")), Path(sysconfig.get_path("platlib"))}
190
+ return {record for root in roots if root.is_dir() for record in root.glob("*.dist-info")
191
+ if not (record / "METADATA").is_file()}
192
+
193
+
194
+ def snapshot(python: Path) -> Snapshot:
195
+ """The environment's installed distributions, read by a fresh interpreter."""
196
+ proc = subprocess.run(
197
+ [str(python), "-c", _SNAPSHOT_PROBE], capture_output=True, text=True, timeout=_SNAPSHOT_TIMEOUT_S
198
+ )
199
+ if proc.returncode != 0:
200
+ raise InstallerError(f"could not read the installed packages: {proc.stderr.strip() or proc.returncode}")
201
+ return json.loads(proc.stdout)
202
+
203
+
204
+ def inspect(python: Path, dist: str) -> dict:
205
+ """`plugin show DIST --json`, run by a fresh interpreter without the current folder on its path, so the
206
+ installed code is what loads."""
207
+ proc = subprocess.run(
208
+ [str(python), "-P", "-m", "agent_env.cli", "plugin", "show", dist, "--json"],
209
+ capture_output=True, text=True, timeout=_INSPECT_TIMEOUT_S,
210
+ )
211
+ if proc.returncode != 0:
212
+ detail = proc.stderr.strip().splitlines()[-1] if proc.stderr.strip() else f"exit status {proc.returncode}"
213
+ return {"error": detail}
214
+ try:
215
+ return json.loads(proc.stdout)
216
+ except ValueError as exc:
217
+ return {"error": f"`plugin show {dist} --json` printed no JSON report ({exc})"}
218
+
219
+
220
+ class ProbeError(Exception):
221
+ """A fresh-interpreter check that could not tell."""
222
+
223
+
224
+ def config_set_by(name: str) -> Optional[str]:
225
+ """The AGENT_ENV_CONFIG that importing ``name``'s entry points sets, or None. Checked in a
226
+ fresh interpreter: this process has already imported the CLI plugins, so it cannot tell."""
227
+ env = {k: v for k, v in os.environ.items() if k != "AGENT_ENV_CONFIG"}
228
+ with tempfile.TemporaryDirectory() as scratch:
229
+ result = Path(scratch) / "config.json"
230
+ try:
231
+ proc = subprocess.run(
232
+ [sys.executable, "-P", "-c", _CONFIG_PROBE, name, str(result)],
233
+ capture_output=True, text=True, env=env, timeout=_PROBE_TIMEOUT_S,
234
+ )
235
+ except subprocess.TimeoutExpired:
236
+ raise ProbeError(f"importing it took more than {_PROBE_TIMEOUT_S}s") from None
237
+ try:
238
+ return json.loads(result.read_text())
239
+ except (OSError, ValueError):
240
+ last = proc.stderr.strip().splitlines()[-1] if proc.stderr.strip() else f"exit status {proc.returncode}"
241
+ raise ProbeError(last) from None
242
+
243
+
244
+ def installs(name: str, path: Path) -> bool:
245
+ """Whether ``path`` is one of the files installed with ``name``, so uninstalling it deletes
246
+ the file. An editable install records none of its sources, so it never qualifies."""
247
+ try:
248
+ dist = importlib.metadata.distribution(name)
249
+ except importlib.metadata.PackageNotFoundError:
250
+ return False
251
+ target = Path(path).resolve()
252
+ return any(Path(dist.locate_file(file)).resolve() == target for file in dist.files or [])
253
+
254
+
255
+ def current_environment(installer: Optional[str] = None) -> Environment:
256
+ """The environment this agent-env runs in, and the installer that owns it."""
257
+ env = _installers.detect(
258
+ Path(sys.prefix), Path(sys.base_prefix), Path(sys.executable),
259
+ has_pip=importlib.util.find_spec("pip") is not None,
260
+ project_environment=os.environ.get("UV_PROJECT_ENVIRONMENT"), cwd=Path.cwd(),
261
+ )
262
+ env = _installers.forced(env, installer)
263
+ return _installers.with_refusal(
264
+ env, stdlib=Path(sysconfig.get_path("stdlib")), site_packages=Path(sysconfig.get_path("purelib"))
265
+ )
266
+
267
+
268
+ @dataclass
269
+ class Tools:
270
+ """The side-effecting pieces, swapped out by the unit tests."""
271
+
272
+ run: Runner = run
273
+ snapshot: Callable[[Path], Snapshot] = snapshot
274
+ inspect: Callable[[Path, str], dict] = inspect
275
+ config_set_by: Callable[[str], Optional[str]] = config_set_by
276
+ installs: Callable[[str, Path], bool] = installs
277
+ broken: Callable[[], set[Path]] = broken
278
+
279
+
280
+ @dataclass
281
+ class _Rollback:
282
+ """What a change restores when it does not take effect."""
283
+
284
+ env: Environment
285
+ before: Snapshot
286
+ files: dict[Path, bytes]
287
+ broken: set[Path] = field(default_factory=set)
288
+ receipt: Optional[ToolReceipt] = None
289
+ injected: set[str] = field(default_factory=set)
290
+
291
+
292
+ def _save(env: Environment, before: Snapshot, tools: Tools) -> _Rollback:
293
+ saved = _Rollback(env, before, _files(env), tools.broken())
294
+ if env.kind == _installers.UV_TOOL:
295
+ saved.receipt = ToolReceipt.read(env.prefix / "uv-receipt.toml")
296
+ if env.kind == _installers.PIPX:
297
+ saved.injected = _injected(env)
298
+ return saved
299
+
300
+
301
+ def add(specs: list[str], *, installer: Optional[str], index_url: Optional[str], dry_run: bool, yes: bool,
302
+ keep: bool, tools: Tools) -> int:
303
+ env = current_environment(installer)
304
+ with _locked(env):
305
+ plan = _installers.add_plan(env, specs, index_url=index_url)
306
+ planned = _files(env)
307
+ _describe(plan)
308
+ if not plan.runs:
309
+ return 0
310
+ if env.kind in (_installers.VIRTUALENV, _installers.SYSTEM) and not _preview(env, specs, index_url):
311
+ return 1
312
+ if dry_run:
313
+ return 0
314
+ if not _proceed(yes):
315
+ click.echo("Nothing changed.")
316
+ return 1
317
+ _still_as_planned(env, planned)
318
+ saved = _save(env, tools.snapshot(env.python), tools)
319
+ unnamed = env.kind == _installers.PIPX and None in {_installers.requirement_name(s) for s in specs}
320
+ hint = _UNNAMED_PIPX_HINT if unnamed else None
321
+ return _apply(saved, lambda: _install_and_verify(plan, saved, specs, tools, unchanged_hint=hint), tools,
322
+ keep=keep)
323
+
324
+
325
+ def _still_as_planned(env: Environment, planned: dict[Path, bytes]) -> None:
326
+ """The plan was built from the installer's record before the prompt; if something else changed
327
+ the record while it waited, running it would undo that change."""
328
+ if _files(env) != planned:
329
+ raise InstallerError(
330
+ "the installer's record of this environment changed while this waited to be confirmed, so the plan is "
331
+ "out of date; nothing was changed. Run the command again."
332
+ )
333
+
334
+
335
+ def _install_and_verify(plan: Plan, saved: _Rollback, specs: list[str], tools: Tools, *,
336
+ unchanged_hint: Optional[str] = None) -> list[str]:
337
+ """Run the installer and check what it added. Empty when the change took effect."""
338
+ env = plan.environment
339
+ for command in plan.commands:
340
+ if tools.run(command, plan.cwd) != 0:
341
+ return ["the installer failed"]
342
+ after = tools.snapshot(env.python)
343
+ _show_changes(saved.before, after)
344
+ if env.kind == _installers.UV_PROJECT:
345
+ for path in _record(env, lock=False):
346
+ _show_diff(saved.files, path)
347
+ if lost := _lost(saved.before, after):
348
+ return [f"the installer removed {', '.join(lost)}, which this change did not ask for"]
349
+ if not _changed(saved.before, after):
350
+ if _files(env) == saved.files:
351
+ click.echo("Nothing changed: the installer left every package as it was.")
352
+ if unchanged_hint:
353
+ click.echo(unchanged_hint)
354
+ return []
355
+ # Only the installer's record changed, so what it names must be a plugin that is here.
356
+ named = [key for key in map(_installers.requirement_name, specs) if key in after]
357
+ if not any(after[key]["entry_points"] for key in named):
358
+ return ["none of the packages it names declares an agent_env entry point, so it is not an agent-env plugin"]
359
+ for path in _record(env, lock=False) if env.kind != _installers.UV_PROJECT else ():
360
+ _show_diff(saved.files, path)
361
+ click.echo("Recorded. The installed packages did not change.")
362
+ return []
363
+ problems = _core_replaced(saved.before, after) or _verify(env, saved.before, after, tools)
364
+ if not problems:
365
+ click.echo("Added. `agent-env plugin list` shows every installed plugin.")
366
+ return problems
367
+
368
+
369
+ def _lost(before: Snapshot, after: Snapshot, expected: frozenset[str] = frozenset()) -> list[str]:
370
+ """Plugins the installer removed that the change did not name."""
371
+ return sorted(before[key]["name"] for key in before
372
+ if key not in after and key not in expected and before[key]["entry_points"])
373
+
374
+
375
+ def _core_replaced(before: Snapshot, after: Snapshot) -> list[str]:
376
+ """agent-env itself installed from a URL, git or a directory it did not come from: only a spec
377
+ that built as agent-env does that, and a bare URL or directory cannot be refused before it
378
+ builds. An upgrade from the index, which a plugin's requirements may need, is not refused."""
379
+ found = []
380
+ for key in _installers.CORE:
381
+ new = after.get(key)
382
+ if new and new.get("direct_url") and not _same(before.get(key), new):
383
+ found.append(f"{new['name']} now comes from {new['direct_url'].get('url')}: a spec built as agent-env "
384
+ "itself, which `plugin add` does not replace. Upgrade it with the installer that owns the "
385
+ "environment.")
386
+ return found
387
+
388
+
389
+ def remove(names: list[str], *, installer: Optional[str], dry_run: bool, yes: bool, force: bool, check_usage: bool,
390
+ tools: Tools) -> int:
391
+ env = current_environment(installer)
392
+ with _locked(env):
393
+ installed = tools.snapshot(env.python)
394
+ wanted = _installers.recorded(env)
395
+ targets = [normalize(name) for name in names]
396
+ for name, key in zip(names, targets):
397
+ if key in _installers.CORE:
398
+ raise InstallerError(f"{name} is agent-env itself; uninstall it with the installer that owns it")
399
+ if key not in installed:
400
+ raise InstallerError(f"{name} is not installed in this environment")
401
+ # A package `plugin add` recorded next to a plugin, such as a pin the plugin needs, can
402
+ # go the way it came; anything else without entry points belongs to what requires it.
403
+ if not installed[key]["entry_points"] and key not in (wanted or ()):
404
+ raise InstallerError(
405
+ f"{installed[key]['name']} declares no agent_env entry points, so it is not a plugin"
406
+ )
407
+ also = _taken_along(env, installed, targets, wanted)
408
+ if also:
409
+ click.echo(f"This also removes {', '.join(installed[key]['name'] for key in also)}: nothing that stays "
410
+ f"needs {'it' if len(also) == 1 else 'them'}.")
411
+ checked = targets + also
412
+ blockers = _dependents(installed, checked) + _config_references(installed, checked, tools)
413
+ blockers += _stored_usage(installed, checked, check_remote=check_usage)
414
+ for blocker in blockers:
415
+ click.echo(f"{'warning' if force else 'blocked'}: {blocker}", err=True)
416
+ if blockers and not force:
417
+ raise InstallerError("not removed; fix the above, or pass --force to remove anyway")
418
+ plan = _installers.remove_plan(env, [installed[key]["name"] for key in targets],
419
+ also=[installed[key]["name"] for key in also])
420
+ planned = _files(env)
421
+ _describe(plan)
422
+ if left := _left_behind(installed, checked, wanted):
423
+ one = len(left) == 1
424
+ click.echo(f"note: {', '.join(left)} {'stays' if one else 'stay'} installed: the installer records "
425
+ f"{'it' if one else 'them'} on {'its' if one else 'their'} own, though only what this removes "
426
+ f"needed {'it' if one else 'them'}. `agent-env plugin remove {' '.join(left)}` removes "
427
+ f"{'it' if one else 'them'} too.", err=True)
428
+ if not plan.runs or dry_run:
429
+ return 0
430
+ if not _proceed(yes):
431
+ click.echo("Nothing changed.")
432
+ return 1
433
+ _still_as_planned(env, planned)
434
+ saved = _save(env, installed, tools)
435
+ return _apply(saved, lambda: _uninstall(plan, saved, targets, also, tools), tools)
436
+
437
+
438
+ Wanted = dict[str, frozenset[str]]
439
+
440
+
441
+ def _needed(installed: Snapshot, roots: Wanted) -> set[str]:
442
+ """``roots`` and everything they require as installed, following the extras each asks for."""
443
+ found, seen, todo = set(), set(), list(roots.items())
444
+ while todo:
445
+ key, extras = todo.pop()
446
+ if key not in installed or (key, extras) in seen:
447
+ continue
448
+ seen.add((key, extras))
449
+ found.add(key)
450
+ dist = installed[key]
451
+ wants = dist.get("wants") or {}
452
+ todo += [(dep, frozenset(wants.get(dep, ()))) for dep in dist["requires"]]
453
+ for extra in extras:
454
+ todo += [(dep, frozenset(asked)) for dep, asked in ((dist.get("extras") or {}).get(extra) or {}).items()]
455
+ return found
456
+
457
+
458
+ def _roots(installed: Snapshot, wanted: Wanted, without: list[str] = ()) -> Wanted:
459
+ """What the installer keeps installed on its own, agent-env included, less ``without``."""
460
+ roots = {key: extras for key, extras in wanted.items() if key in installed and key not in without}
461
+ return {**{key: frozenset() for key in _installers.CORE if key in installed}, **roots}
462
+
463
+
464
+ def _taken_along(env: Environment, installed: Snapshot, targets: list[str], wanted: Optional[Wanted]) -> list[str]:
465
+ """Other plugins that go with ``targets``: needed before, and by nothing the installer keeps
466
+ after. A uv tool's rebuild and a uv project's lock drop them; pip and pipx leave them."""
467
+ if wanted is None or env.kind not in (_installers.UV_TOOL, _installers.UV_PROJECT):
468
+ return []
469
+ gone = _needed(installed, _roots(installed, wanted)) - _needed(installed, _roots(installed, wanted, targets))
470
+ return sorted(key for key in gone - set(targets) if installed[key]["entry_points"])
471
+
472
+
473
+ def _left_behind(installed: Snapshot, removed: list[str], wanted: Optional[Wanted]) -> list[str]:
474
+ """Packages the record lists on their own that only ``removed`` needed, such as the pins added
475
+ with a plugin. They stay, since the record asks for them."""
476
+ if not wanted:
477
+ return []
478
+ needed_by_removed = _needed(installed, {key: wanted.get(key, frozenset()) for key in removed})
479
+ return sorted(installed[key]["name"] for key in wanted
480
+ if key in installed and key not in removed and key not in _installers.CORE
481
+ and not installed[key]["entry_points"] and key in needed_by_removed
482
+ and key not in _needed(installed, _roots(installed, wanted, [*removed, key])))
483
+
484
+
485
+ def _uninstall(plan: Plan, saved: _Rollback, targets: list[str], also: list[str], tools: Tools) -> list[str]:
486
+ for command in plan.commands:
487
+ if tools.run(command, plan.cwd) != 0:
488
+ return ["the installer failed"]
489
+ after = tools.snapshot(plan.environment.python)
490
+ _show_changes(saved.before, after)
491
+ left = [saved.before[key]["name"] for key in targets if key in after]
492
+ if left:
493
+ return [f"still installed after the installer ran: {', '.join(left)}"]
494
+ if lost := _lost(saved.before, after, frozenset(targets + also)):
495
+ names = " ".join([saved.before[key]["name"] for key in targets] + lost)
496
+ return [f"the installer also removed {', '.join(lost)}, which this change did not name; "
497
+ f"`agent-env plugin remove {names}` removes them together"]
498
+ click.echo("Removed.")
499
+ return []
500
+
501
+
502
+ def _apply(saved: _Rollback, change: Callable[[], list[str]], tools: Tools, *, keep: bool = False) -> int:
503
+ """Make the change, and put the environment back as it was unless it took effect."""
504
+ with _interruptible():
505
+ try:
506
+ problems = change()
507
+ except KeyboardInterrupt:
508
+ click.echo("Interrupted; restoring the environment as it was.", err=True)
509
+ _restore(saved, tools)
510
+ return 130
511
+ except Exception as exc:
512
+ problems = [f"could not finish the change: {exc}"]
513
+ if not problems:
514
+ return 0
515
+ for problem in problems:
516
+ click.echo(f"problem: {problem}", err=True)
517
+ if keep:
518
+ click.echo("Kept as installed (--keep).", err=True)
519
+ return 1
520
+ click.echo("Restoring the environment as it was.", err=True)
521
+ _restore(saved, tools)
522
+ return 1
523
+
524
+
525
+ @contextmanager
526
+ def _locked(env: Environment) -> Iterator[None]:
527
+ """One `plugin add` or `remove` at a time per environment, held from reading the environment to
528
+ the result so neither runs a plan the other has made stale. The lock lives outside the
529
+ environment, which the installer may recreate, in a directory only this user can write to."""
530
+ if fcntl is None:
531
+ yield
532
+ return
533
+ path = _lock_path(env)
534
+ try:
535
+ path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
536
+ fd = os.open(path, os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW, 0o600)
537
+ except OSError as exc:
538
+ raise InstallerError(f"cannot take the lock {path}: {exc.strerror or exc}") from exc
539
+ try:
540
+ try:
541
+ fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
542
+ except BlockingIOError:
543
+ raise InstallerError(
544
+ "another `agent-env plugin add` or `remove` is changing this environment; run this after it finishes"
545
+ ) from None
546
+ yield
547
+ finally:
548
+ os.close(fd)
549
+
550
+
551
+ def _lock_path(env: Environment) -> Path:
552
+ digest = hashlib.sha256(str(env.prefix.resolve()).encode()).hexdigest()[:16]
553
+ return state_root() / "locks" / f"plugin-{digest}.lock"
554
+
555
+
556
+ @contextmanager
557
+ def _interruptible() -> Iterator[None]:
558
+ """SIGTERM interrupts like Ctrl-C, so both reach the rollback."""
559
+ def interrupt(signum, frame):
560
+ raise KeyboardInterrupt
561
+
562
+ previous = signal.signal(signal.SIGTERM, interrupt)
563
+ try:
564
+ yield
565
+ finally:
566
+ signal.signal(signal.SIGTERM, previous)
567
+
568
+
569
+ @contextmanager
570
+ def _uninterrupted() -> Iterator[None]:
571
+ """Ctrl-C and SIGTERM wait until the restore finishes; stopping halfway would leave the
572
+ environment in neither state."""
573
+ previous = {sig: signal.signal(sig, signal.SIG_IGN) for sig in (signal.SIGINT, signal.SIGTERM)}
574
+ try:
575
+ yield
576
+ finally:
577
+ for sig, handler in previous.items():
578
+ signal.signal(sig, handler)
579
+
580
+
581
+ def _describe(plan: Plan) -> None:
582
+ env = plan.environment
583
+ click.echo(f"agent-env: {env.kind} at {env.location}")
584
+ if plan.note:
585
+ click.echo(plan.note)
586
+ for command in plan.commands:
587
+ prefix = f"cd {shlex.quote(str(plan.cwd))} && " if plan.cwd and not plan.runs else ""
588
+ click.echo(f"{'Run' if not plan.runs else 'Will run'}: {prefix}{shlex.join(command)}")
589
+
590
+
591
+ def _proceed(yes: bool) -> bool:
592
+ return yes or click.confirm("Proceed?", default=False)
593
+
594
+
595
+ def _preview(env: Environment, specs: list[str], index_url: Optional[str]) -> bool:
596
+ """A resolver dry run, for the installers that have one. False when it cannot resolve."""
597
+ flags = ("--index-url", index_url) if index_url else ()
598
+ if env.has_pip:
599
+ command = [str(env.python), "-m", "pip", "install", "--dry-run", *flags, *specs]
600
+ elif shutil.which("uv"):
601
+ command = ["uv", "pip", "install", "--dry-run", "--python", str(env.python), *specs]
602
+ command += ["--default-index", index_url] if index_url else []
603
+ else:
604
+ return True
605
+ proc = subprocess.run(command, capture_output=True, text=True, timeout=_PREVIEW_TIMEOUT_S)
606
+ lines = [ln.strip() for ln in (proc.stdout + proc.stderr).splitlines()]
607
+ if proc.returncode != 0:
608
+ click.echo("The installer cannot resolve this:", err=True)
609
+ for line in lines[-8:]:
610
+ click.echo(f" {line}", err=True)
611
+ return False
612
+ plan = [ln for ln in lines if ln.startswith(("Would install", "+ ", "- "))]
613
+ for line in plan:
614
+ core = " (agent-env itself)" if _names_in(line) & set(_installers.CORE) else ""
615
+ click.echo(f" {line}{core}")
616
+ return True
617
+
618
+
619
+ def _names_in(line: str) -> set[str]:
620
+ """The packages a resolver's dry-run line names: `+ name==1.0` or `+ name @ url` from uv, and
621
+ `Would install name-1.0 other-2.0` from pip."""
622
+ if line.startswith(("+ ", "- ")):
623
+ return {_installers.requirement_name(line[2:].strip())} - {None}
624
+ return {normalize(word.rsplit("-", 1)[0]) for word in line.split()[2:]}
625
+
626
+
627
+ def _record(env: Environment, *, lock: bool = True) -> list[Path]:
628
+ """The files in which the installer records this environment."""
629
+ if env.kind == _installers.UV_PROJECT:
630
+ return [*_installers.project_files(env), *([env.location / "uv.lock"] if lock else [])]
631
+ return {
632
+ _installers.UV_TOOL: [env.prefix / "uv-receipt.toml"],
633
+ _installers.PIPX: [env.prefix / "pipx_metadata.json"],
634
+ }.get(env.kind, [])
635
+
636
+
637
+ def _files(env: Environment) -> dict[Path, bytes]:
638
+ """The installer's record of this environment, kept byte for byte to restore."""
639
+ return {path: path.read_bytes() for path in _record(env) if path.is_file()}
640
+
641
+
642
+ def _injected(env: Environment) -> set[str]:
643
+ metadata = json.loads((env.prefix / "pipx_metadata.json").read_text())
644
+ return {normalize(name) for name in metadata.get("injected_packages") or {}}
645
+
646
+
647
+ def _same(a: Optional[dict], b: Optional[dict]) -> bool:
648
+ """Whether two installs are the same version from the same source. The requested git revision
649
+ is left out, since a rollback reinstalls by commit; a hash counts only when both installs
650
+ recorded one, since uv records none."""
651
+ if a is None or b is None:
652
+ return a is b
653
+ da, db = a.get("direct_url") or {}, b.get("direct_url") or {}
654
+ if (a["version"], _origin(da)) != (b["version"], _origin(db)):
655
+ return False
656
+ ha, hb = _sha256(da), _sha256(db)
657
+ return ha is None or hb is None or ha == hb
658
+
659
+
660
+ def _origin(direct: dict) -> tuple:
661
+ return (direct.get("url"), (direct.get("vcs_info") or {}).get("commit_id"),
662
+ bool((direct.get("dir_info") or {}).get("editable")), direct.get("subdirectory"))
663
+
664
+
665
+ def _sha256(direct: dict) -> Optional[str]:
666
+ return ((direct.get("archive_info") or {}).get("hashes") or {}).get("sha256")
667
+
668
+
669
+ def _changed(before: Snapshot, after: Snapshot) -> list[str]:
670
+ return sorted(key for key in set(before) | set(after) if not _same(before.get(key), after.get(key)))
671
+
672
+
673
+ def _show_changes(before: Snapshot, after: Snapshot) -> None:
674
+ for key in _changed(before, after):
675
+ old, new = before.get(key), after.get(key)
676
+ core = " (agent-env itself)" if key in _installers.CORE else ""
677
+ if old is None:
678
+ click.echo(f" + {new['name']} {new['version']}{core}")
679
+ elif new is None:
680
+ click.echo(f" - {old['name']} {old['version']}{core}")
681
+ elif old["version"] != new["version"]:
682
+ click.echo(f" ~ {new['name']} {old['version']} -> {new['version']}{core}")
683
+ else:
684
+ click.echo(f" ~ {new['name']} {new['version']}, from a different source{core}")
685
+
686
+
687
+ def _show_diff(files: dict[Path, bytes], path: Path) -> None:
688
+ if path not in files or not path.is_file():
689
+ return
690
+ old = files[path].decode().splitlines(keepends=True)
691
+ new = path.read_text().splitlines(keepends=True)
692
+ for line in difflib.unified_diff(old, new, f"{path.name} (before)", f"{path.name} (after)"):
693
+ click.echo(line.rstrip("\n"))
694
+
695
+
696
+ def _verify(env: Environment, before: Snapshot, after: Snapshot, tools: Tools) -> list[str]:
697
+ """Why the change did not take effect, or nothing."""
698
+ plugins = [key for key in _changed(before, after) if key in after and after[key]["entry_points"]]
699
+ if all(key in _installers.CORE for key in plugins):
700
+ return ["none of the packages it installed declares an agent_env entry point, so it is not an agent-env plugin"]
701
+ problems = []
702
+ for key in plugins:
703
+ name = after[key]["name"]
704
+ report = tools.inspect(env.python, name)
705
+ if "error" in report:
706
+ problems.append(f"{name}: {report['error']}")
707
+ continue
708
+ # A report from before format 1 has no version but the same shape, so it is read as format 1.
709
+ version = report.get("format_version", FORMAT_VERSION)
710
+ if version != FORMAT_VERSION:
711
+ problems.append(f"{name}: after the change agent-env reports plugins in format {version!r}, but this "
712
+ f"agent-env reads format {FORMAT_VERSION}; upgrade agent-env first, then add the plugin")
713
+ continue
714
+ if not isinstance(report.get("plugins"), list) or not report["plugins"]:
715
+ problems.append(f"{name}: `plugin show {name} --json` reported no plugin package")
716
+ continue
717
+ for plugin in report["plugins"]:
718
+ for c in plugin["contributions"]:
719
+ status = c["status"]
720
+ why = f" ({c['reason']})" if c.get("reason") else ""
721
+ click.echo(f" {name}: {c['group'].removeprefix('agent_env.')} {c['name']} {status}{why}")
722
+ if status not in _OK:
723
+ problems.append(f"{name}: {c['name']} is {status}{why}")
724
+ if report.get("config_effect"):
725
+ click.echo(f" {name}: {report['config_effect']}")
726
+ return problems
727
+
728
+
729
+ def _pinned(entry: dict) -> list[str]:
730
+ """Installer arguments that reinstall ``entry`` exactly: the same version from the same source."""
731
+ direct = entry.get("direct_url")
732
+ if not direct:
733
+ return [f"{entry['name']}=={entry['version']}"]
734
+ url = direct["url"]
735
+ if direct.get("dir_info", {}).get("editable"):
736
+ return ["-e", unquote(urlparse(url).path) if url.startswith("file:") else url]
737
+ vcs = direct.get("vcs_info")
738
+ if vcs:
739
+ url = f"{vcs['vcs']}+{url}@{vcs.get('commit_id') or vcs.get('requested_revision')}"
740
+ subdirectory = f"#subdirectory={direct['subdirectory']}" if direct.get("subdirectory") else ""
741
+ return [f"{entry['name']} @ {url}{subdirectory}"]
742
+
743
+
744
+ def _restore(saved: _Rollback, tools: Tools) -> None:
745
+ with _uninterrupted():
746
+ _restore_now(saved, tools)
747
+
748
+
749
+ def _restore_now(saved: _Rollback, tools: Tools) -> None:
750
+ env = saved.env
751
+ # Records an installer stopped halfway left behind: no installer can read them, so the restore
752
+ # itself would fail on them. What they stood for is reinstalled below.
753
+ for record in sorted(tools.broken() - saved.broken):
754
+ shutil.rmtree(record, ignore_errors=True)
755
+ now = tools.snapshot(env.python)
756
+ if not _changed(saved.before, now):
757
+ pass # the change never reached the packages; only the record may need putting back
758
+ elif env.kind == _installers.UV_TOOL and saved.receipt is not None:
759
+ # The old requirements alone keep whatever newer versions still satisfy them.
760
+ with tempfile.NamedTemporaryFile("w", suffix=".txt", delete=False) as constraints:
761
+ constraints.write("".join(f"{e['name']}=={e['version']}\n" for e in saved.before.values()
762
+ if not e.get("direct_url")))
763
+ try:
764
+ tools.run(("uv", "tool", "install", *saved.receipt.install_args(), "--constraints", constraints.name), None)
765
+ finally:
766
+ Path(constraints.name).unlink(missing_ok=True)
767
+ else:
768
+ injected = sorted(_injected(env) - saved.injected) if env.kind == _installers.PIPX else []
769
+ if injected:
770
+ tools.run(("pipx", "uninject", "--leave-deps", env.prefix.name, *injected), None)
771
+ now = tools.snapshot(env.python)
772
+ if added := [now[key]["name"] for key in now if key not in saved.before]:
773
+ tools.run(_pip(env, "uninstall", *added), None)
774
+ pinned = [arg for key, entry in saved.before.items() if not _same(now.get(key), entry)
775
+ for arg in _pinned(entry)]
776
+ if pinned:
777
+ tools.run(_pip(env, "install", "--no-deps", *pinned), None)
778
+ for path in _record(env):
779
+ if path in saved.files:
780
+ path.write_bytes(saved.files[path])
781
+ elif path.exists():
782
+ path.unlink()
783
+ drift = _changed(saved.before, tools.snapshot(env.python))
784
+ drift += sorted(record.name for record in tools.broken() - saved.broken)
785
+ if not drift:
786
+ click.echo("Restored.", err=True)
787
+ return
788
+ click.echo(f"Could not restore exactly; these differ from before: {', '.join(drift)}", err=True)
789
+ repair = {
790
+ _installers.UV_TOOL: f"uv tool upgrade --reinstall {env.prefix.name}",
791
+ _installers.PIPX: f"pipx reinstall {env.prefix.name}",
792
+ _installers.UV_PROJECT: f"uv sync --inexact --reinstall --project {shlex.quote(str(env.location))}"
793
+ + (f" --package {env.member[0]}" if env.member else ""),
794
+ }.get(env.kind)
795
+ if repair:
796
+ click.echo(f"`{repair}` reinstalls what the installer records.", err=True)
797
+
798
+
799
+ def _pip(env: Environment, action: str, *args: str) -> tuple[str, ...]:
800
+ if env.kind != _installers.PIPX:
801
+ return _installers.pip_command(env, action, *args)
802
+ if action == "uninstall":
803
+ return ("pipx", "runpip", env.prefix.name, "uninstall", "-y", *args)
804
+ metadata = json.loads((env.prefix / "pipx_metadata.json").read_text())
805
+ return ("pipx", "runpip", env.prefix.name, action, *(metadata["main_package"].get("pip_args") or []), *args)
806
+
807
+
808
+ def _dependents(installed: Snapshot, targets: list[str]) -> list[str]:
809
+ found = []
810
+ for key in targets:
811
+ users = sorted(installed[d]["name"] for d in installed if key in installed[d]["requires"] and d not in targets)
812
+ if users:
813
+ found.append(f"{installed[key]['name']} is required by {', '.join(users)}")
814
+ return found
815
+
816
+
817
+ def _contributed(installed: Snapshot, targets: list[str]) -> dict[str, set[str]]:
818
+ """What these packages provide that no remaining package also provides."""
819
+ kept = {(group, name) for key, dist in installed.items() if key not in targets
820
+ for group, name in dist["entry_points"]}
821
+ names: dict[str, set[str]] = {}
822
+ for key in targets:
823
+ for group, name in installed[key]["entry_points"]:
824
+ if (group, name) not in kept:
825
+ names.setdefault(group, set()).add(name)
826
+ return names
827
+
828
+
829
+ def _owns(modules: set[str], impl: object) -> bool:
830
+ if not isinstance(impl, str):
831
+ return False
832
+ module = impl.split(":", 1)[0].strip()
833
+ return any(module == owned or module.startswith(f"{owned}.") for owned in modules)
834
+
835
+
836
+ def _config_references(installed: Snapshot, targets: list[str], tools: Tools) -> list[str]:
837
+ """Where the config file still names something only these packages provide. Nothing, when
838
+ the file in effect is one a package selects on import and installs: it goes with that package."""
839
+ contributed = _contributed(installed, targets)
840
+ modules = {module for key in targets for module in installed[key].get("modules", [])}
841
+ config = get_config()
842
+ try:
843
+ sandbox, state, artifacts = config.section("sandbox"), config.section("state"), config.section("artifacts")
844
+ impl_lists = {"envs": config.section("envs"), "task_steps": config.section("task_steps"),
845
+ "artifacts": artifacts, "explorer.plugins": config.section("explorer", "plugins")}
846
+ stores = ("document", "object", "image", "secret", "runner")
847
+ tables = {name: config.trace_section(name).value for name in stores}
848
+ except Exception as exc:
849
+ return [f"the config file cannot be read to check what it names: {exc}"]
850
+ found: list[str] = []
851
+ providers = contributed.get(SANDBOX_PROVIDERS, set())
852
+ for key in ("default", "agent_default"):
853
+ value = sandbox.get(key)
854
+ if isinstance(value, str) and providers & {token.strip() for token in value.split(",")}:
855
+ found.append(f"[sandbox] {key} = {value!r} names its sandbox provider")
856
+ for group, section, table in ((SANDBOX_PROVIDERS, sandbox, "sandbox"), (STATE_PROVIDERS, state, "state")):
857
+ for name, settings in (section.get("providers") or {}).items():
858
+ if name in contributed.get(group, set()):
859
+ found.append(f"[{table}.providers.{name}] configures its provider")
860
+ elif isinstance(settings, dict) and _owns(modules, settings.get("impl")):
861
+ found.append(f"[{table}.providers.{name}] impl {settings['impl']!r} is from it")
862
+ for alias, target in (artifacts.get("type_aliases") or {}).items():
863
+ if target in contributed.get(ARTIFACTS, set()):
864
+ found.append(f"[artifacts] type_aliases maps {alias!r} to its type {target!r}")
865
+ for table, section in impl_lists.items():
866
+ for impl in section.get("impls") or []:
867
+ if _owns(modules, impl):
868
+ found.append(f"[{table}] impls names {impl!r} from it")
869
+ for name, table in tables.items():
870
+ if isinstance(table, dict) and _owns(modules, table.get("impl")):
871
+ where = "runner" if name == "runner" else f"stores.{name}"
872
+ found.append(f"[{where}] impl {table['impl']!r} is from it")
873
+ owner = _config_owner(config.config_path(), [installed[key]["name"] for key in targets], tools) if found else None
874
+ if owner:
875
+ click.echo(f"note: {owner} installs the config file in effect and selects it when it is imported, "
876
+ "so what it names goes with it", err=True)
877
+ return []
878
+ return found
879
+
880
+
881
+ def _config_owner(path: Optional[Path], names: list[str], tools: Tools) -> Optional[str]:
882
+ """Which of these packages both installs ``path`` and sets AGENT_ENV_CONFIG to it when it is
883
+ imported. Selecting a file alone is not enough: a shared file stays, and discovery may still
884
+ pick it once the package is gone."""
885
+ if path is None:
886
+ return None
887
+ for name in names:
888
+ if not tools.installs(name, path):
889
+ continue
890
+ try:
891
+ selected = tools.config_set_by(name)
892
+ except ProbeError:
893
+ continue
894
+ if selected and Path(selected).resolve() == Path(path).resolve():
895
+ return name
896
+ return None
897
+
898
+
899
+ def _local_namespace_documents_exist(config) -> bool:
900
+ store = config.get_document_store()
901
+ return isinstance(store, RoutingDocumentStore) and store.local.path.is_file()
902
+
903
+
904
+ def _stored_usage(installed: Snapshot, targets: list[str], *, check_remote: bool) -> list[str]:
905
+ """Stored documents of types only these packages provide: always for a local store, with
906
+ --check-usage for a remote one. Reads a local database only if it already exists."""
907
+ contributed = _contributed(installed, targets)
908
+ envs, artifacts, steps, providers = (contributed.get(g, set()) for g in (ENVS, ARTIFACTS, TASK_STEPS, ENV_PROVIDERS))
909
+ if not (envs or artifacts or steps or providers):
910
+ return []
911
+ config = get_config()
912
+ try:
913
+ section = config.trace_section("document").value
914
+ local = str(section.get("impl", "")).endswith("LocalSqliteDocumentStore")
915
+ path = interpolate(section.get("config") or {}).get("path", "") if local else ""
916
+ except Exception as exc:
917
+ return [f"the document store's config cannot be read to check stored documents: {exc}"]
918
+ if local and not Path(path).is_file() and not _local_namespace_documents_exist(config):
919
+ return []
920
+ if not local and not check_remote:
921
+ click.echo("note: the document store is remote, so stored documents were not checked (--check-usage does)",
922
+ err=True)
923
+ return []
924
+ try:
925
+ store = config.get_document_store()
926
+ found = []
927
+ for collection, types, what in (("envs", envs, "env"), ("artifacts", artifacts, "artifact")):
928
+ if types:
929
+ count = store.count_distinct(collection, Filter().where("type", In(sorted(types))))
930
+ if count:
931
+ found.append(f"{count} stored {what}(s) use its types ({', '.join(sorted(types))})")
932
+ if steps:
933
+ # Step types sit inside each task's steps list, which a filter cannot reach.
934
+ ids = {task.get("id") for task in store.query("tasks", Filter())
935
+ if any(isinstance(step, dict) and step.get("type") in steps for step in task.get("steps") or [])}
936
+ if ids:
937
+ found.append(f"{len(ids)} stored task(s) use its step types ({', '.join(sorted(steps))})")
938
+ if providers:
939
+ # An env declares the provider it deploys through, and an instance records the one that deployed it.
940
+ names = In(sorted(providers))
941
+ for collection, id_field, what in (("envs", "id", "env"), ("env_instances", "instance_id", "env instance")):
942
+ count = store.count_distinct(collection, Filter().where("env_provider_type", names), id_field=id_field)
943
+ if count:
944
+ found.append(f"{count} stored {what}(s) use its environment providers ({', '.join(sorted(providers))})")
945
+ return found
946
+ except Exception as exc:
947
+ return [f"the document store cannot be read to check stored documents: {exc!r}"]