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,438 @@
1
+ """`agent-env plugin` — the installed plugins, what each contributes, and whether it took effect."""
2
+
3
+ import dataclasses
4
+ import json
5
+ import logging
6
+ import re
7
+ import sys
8
+ from collections import Counter
9
+ from collections.abc import Iterator, Mapping
10
+ from contextlib import contextmanager, redirect_stdout
11
+ from importlib.metadata import PackageNotFoundError, distribution, packages_distributions
12
+ from pathlib import Path
13
+ from typing import Optional
14
+
15
+ import click
16
+
17
+ from agent_env.bundle import BundleError
18
+ from agent_env.bundle.installed import BUNDLES, InstalledBundle, checked, installed_bundles, run_name
19
+ from agent_env.cli import _installers, _plugin_changes
20
+ from agent_env.cli._installers import FORCEABLE, InstallerError
21
+ from agent_env.plugins import (
22
+ ARTIFACTS,
23
+ ENV_PROVIDERS,
24
+ ENVS,
25
+ EXPLORER_PLUGINS,
26
+ SANDBOX_PROVIDERS,
27
+ STATE_PROVIDERS,
28
+ TASK_STEPS,
29
+ Claimant,
30
+ Contribution,
31
+ Diagnostic,
32
+ Distribution,
33
+ Inventory,
34
+ inventory,
35
+ )
36
+ from agent_env.plugins._cli import CLI_PLUGINS_GROUP, CLI_ROOT_OPTIONS_GROUP, cli_contributions, cli_discovery_errors
37
+ from agent_env.plugins._discovery import discovery_error
38
+ from agent_env.plugins._report import (
39
+ ENTRY_POINTS_UNREADABLE,
40
+ FORMAT_VERSION,
41
+ INVALID_PLUGIN,
42
+ NAME_CONFLICT,
43
+ QUALIFIED_ONLY,
44
+ )
45
+
46
+ # A contribution with one of these statuses did not take effect, so `check` fails on it.
47
+ PROBLEMS = ("conflict", "blocked", "failed", "skipped")
48
+ _ORDER = (*PROBLEMS, "replaced", "unloaded")
49
+ # `check` always loads, so an `unloaded` contribution there is one whose status could not be determined.
50
+ _CHECK_FAILS = (*PROBLEMS, "unloaded")
51
+ _KINDS = {
52
+ ENVS: ("env", "envs"),
53
+ ARTIFACTS: ("artifact", "artifacts"),
54
+ TASK_STEPS: ("task step", "task steps"),
55
+ SANDBOX_PROVIDERS: ("sandbox provider", "sandbox providers"),
56
+ STATE_PROVIDERS: ("state provider", "state providers"),
57
+ ENV_PROVIDERS: ("environment provider", "environment providers"),
58
+ EXPLORER_PLUGINS: ("explorer plugin", "explorer plugins"),
59
+ CLI_PLUGINS_GROUP: ("CLI command", "CLI commands"),
60
+ CLI_ROOT_OPTIONS_GROUP: ("root option", "root options"),
61
+ BUNDLES: ("bundle", "bundles"),
62
+ }
63
+ _CORE = "agentenv-framework"
64
+ # `list` names a package's contributions up to this many, and counts them by kind beyond it.
65
+ _NAMED_UP_TO = 3
66
+
67
+
68
+ @dataclasses.dataclass(frozen=True)
69
+ class Report:
70
+ """What the `plugin` commands print: the inventory, merged with the CLI's own plugins."""
71
+
72
+ core_version: str
73
+ environment: str
74
+ location: Path
75
+ inventory: Inventory
76
+ distributions: tuple[Distribution, ...]
77
+ # Entry-point groups, type and CLI, whose installed metadata could not be read.
78
+ discovery_errors: Mapping[str, Diagnostic]
79
+
80
+
81
+ def _json(payload: object) -> str:
82
+ def encode(value):
83
+ if isinstance(value, Path):
84
+ return str(value)
85
+ raise TypeError(f"cannot serialize {type(value).__name__} in a plugin report")
86
+ return json.dumps(payload, indent=2, default=encode)
87
+
88
+
89
+ def environment(prefix: Path, base_prefix: Path) -> tuple[str, Path]:
90
+ """How agent-env was installed, and where: the answer decides where a plugin has to go."""
91
+ env = _installers.detect(prefix, base_prefix, Path(sys.executable))
92
+ return env.kind, env.location
93
+
94
+
95
+ def _version(name: str) -> Optional[str]:
96
+ try:
97
+ return distribution(name).version
98
+ except PackageNotFoundError:
99
+ return None
100
+
101
+
102
+ def _core_version() -> str:
103
+ for name in (_CORE, *packages_distributions().get("agent_env", [])):
104
+ if (found := _version(name)) is not None:
105
+ return found
106
+ return "unknown"
107
+
108
+
109
+ @contextmanager
110
+ def _quiet() -> Iterator[None]:
111
+ """The report states each failure once; the loaders' own warnings would repeat it."""
112
+ logger = logging.getLogger("agent_env")
113
+ previous = logger.level
114
+ if not logger.isEnabledFor(logging.DEBUG):
115
+ logger.setLevel(logging.ERROR)
116
+ try:
117
+ yield
118
+ finally:
119
+ logger.setLevel(previous)
120
+
121
+
122
+ def collect(root: click.Group, *, load: bool) -> Report:
123
+ # A plugin that prints while it is imported must not corrupt `--json` on stdout.
124
+ with _quiet(), redirect_stdout(sys.stderr):
125
+ inv = inventory(load=load)
126
+ bundles, bundle_errors = _bundle_contributions(load=load)
127
+ merged: dict[tuple[str, str], list[Contribution]] = {
128
+ (d.name, d.version): list(d.contributions) for d in inv.distributions
129
+ }
130
+ for key, found in cli_contributions(root).items():
131
+ merged.setdefault(key, []).extend(found)
132
+ for key, found in bundles.items():
133
+ merged.setdefault(key, []).extend(found)
134
+ kind, location = environment(Path(sys.prefix), Path(sys.base_prefix))
135
+ return Report(
136
+ core_version=_core_version(),
137
+ environment=kind,
138
+ location=location,
139
+ inventory=inv,
140
+ distributions=tuple(
141
+ Distribution(name, version, tuple(found))
142
+ for (name, version), found in sorted(merged.items(), key=lambda item: (item[0][0].lower(), item[0][1]))
143
+ ),
144
+ discovery_errors={**inv.discovery_errors, **cli_discovery_errors(root), **bundle_errors},
145
+ )
146
+
147
+
148
+ def _bundle_contributions(*, load: bool) -> tuple[dict[tuple[str, str], list[Contribution]], dict[str, Diagnostic]]:
149
+ """Each installed bundle as a contribution of its package, and the discovery error if there is one."""
150
+ try:
151
+ bundles = installed_bundles()
152
+ except Exception as e:
153
+ return {}, {BUNDLES: Diagnostic(ENTRY_POINTS_UNREADABLE, discovery_error(e))}
154
+ found: dict[tuple[str, str], list[Contribution]] = {}
155
+ for bundle in bundles:
156
+ found.setdefault((bundle.package, bundle.version), []).append(_bundle_contribution(bundle, bundles, load=load))
157
+ return found, {}
158
+
159
+
160
+ def _bundle_contribution(bundle: InstalledBundle, bundles: tuple[InstalledBundle, ...], *, load: bool) -> Contribution:
161
+ """Whether ``bundle`` runs, by the checks ``agent-env run`` makes before it reads a store. Without loading
162
+ plugins, only that the folder parses."""
163
+ namesakes = tuple(Claimant(other.package, other.version, other.value)
164
+ for other in bundles if other.name == bundle.name and other is not bundle)
165
+ if bundle.problem:
166
+ status = "conflict" if bundle.code == NAME_CONFLICT else "failed"
167
+ return Contribution(BUNDLES, bundle.name, bundle.value, status, code=bundle.code, reason=bundle.problem,
168
+ conflicts_with=namesakes if status == "conflict" else ())
169
+ try:
170
+ checked(bundle, load=load)
171
+ except BundleError as e:
172
+ return Contribution(BUNDLES, bundle.name, bundle.value, "failed", code=INVALID_PLUGIN,
173
+ reason=f"it isn't a valid bundle: {e.summary}")
174
+ if run_name(bundle, bundles) != bundle.name:
175
+ return Contribution(BUNDLES, bundle.name, bundle.value, "active", code=QUALIFIED_ONLY,
176
+ reason=f"another package also installs {bundle.name!r}, so run this one as "
177
+ f"{bundle.qualified!r}", conflicts_with=namesakes)
178
+ return Contribution(BUNDLES, bundle.name, bundle.value, "active")
179
+
180
+
181
+ def _as_dict(report: Report) -> dict:
182
+ """The document `list --json` prints; `show` and `check` add to it. See "Plugin report format"."""
183
+ error = report.inventory.config_error
184
+ return {
185
+ "format_version": FORMAT_VERSION,
186
+ "agent_env": {"version": report.core_version, "environment": report.environment, "location": report.location},
187
+ "config": {"path": report.inventory.config_path, "error": dataclasses.asdict(error) if error else None},
188
+ "loaded": report.inventory.loaded,
189
+ "group_errors": {group: dataclasses.asdict(e) for group, e in report.inventory.group_errors.items()},
190
+ "discovery_errors": {group: dataclasses.asdict(e) for group, e in report.discovery_errors.items()},
191
+ "plugins": [dataclasses.asdict(d) for d in report.distributions],
192
+ }
193
+
194
+
195
+ def _coded(text: str, code: Optional[str]) -> str:
196
+ return f"{text} [{code}]" if code else text
197
+
198
+
199
+ def _provides(contributions: tuple[Contribution, ...]) -> str:
200
+ if len(contributions) <= _NAMED_UP_TO:
201
+ return ", ".join(f"{_KINDS[c.group][0]} {c.name}" for c in contributions)
202
+ counts = Counter(c.group for c in contributions)
203
+ return ", ".join(
204
+ f"{n} {_KINDS[group][0] if n == 1 else _KINDS[group][1]}" for group, n in counts.items()
205
+ )
206
+
207
+
208
+ def _summary(contributions: tuple[Contribution, ...]) -> str:
209
+ counts = Counter(c.status for c in contributions if c.status != "active")
210
+ if not counts:
211
+ return "ok"
212
+ if set(counts) == {"unloaded"}:
213
+ return "not loaded"
214
+ return ", ".join(f"{counts[status]} {status}" for status in _ORDER if status in counts)
215
+
216
+
217
+ def _unreadable(report: Report) -> list[str]:
218
+ # One unparseable entry_points.txt breaks every group alike, so each distinct error is one line.
219
+ by_error: dict[Diagnostic, list[str]] = {}
220
+ for group, error in report.discovery_errors.items():
221
+ by_error.setdefault(error, []).append(group)
222
+ return [
223
+ _coded(f"installed entry points could not be read for {', '.join(groups)}: {error.reason}", error.code)
224
+ for error, groups in by_error.items()
225
+ ]
226
+
227
+
228
+ def _header(report: Report) -> list[str]:
229
+ lines = [f"agent-env {report.core_version} · {report.environment} at {report.location}"]
230
+ inv = report.inventory
231
+ lines.append(f"config: {inv.config_path}" if inv.config_path else "config: (none)")
232
+ if inv.config_error:
233
+ lines.append(_coded(f"(error) {inv.config_error.reason}", inv.config_error.code))
234
+ lines += [f"(error) {line}" for line in _unreadable(report)]
235
+ return lines
236
+
237
+
238
+ def render_list(report: Report) -> str:
239
+ lines = _header(report)
240
+ lines.append("")
241
+ if not report.distributions:
242
+ lines.append("No plugins installed.")
243
+ return "\n".join(lines)
244
+ rows = [("PACKAGE", "VERSION", "PROVIDES", "STATUS")] + [
245
+ (d.name or "(unreadable metadata)", d.version, _provides(d.contributions), _summary(d.contributions))
246
+ for d in report.distributions
247
+ ]
248
+ widths = [max(len(row[i]) for row in rows) for i in range(3)]
249
+ lines += [
250
+ f"{name:<{widths[0]}} {version:<{widths[1]}} {provides:<{widths[2]}} {status}"
251
+ for name, version, provides, status in rows
252
+ ]
253
+ for group, error in report.inventory.group_errors.items():
254
+ lines += ["", _coded(f"(error) nothing in {group} loads: {error.reason}", error.code)]
255
+ if not report.inventory.loaded:
256
+ lines += ["", "--no-load: type plugins were not imported (CLI plugins load when the CLI starts)."]
257
+ return "\n".join(lines)
258
+
259
+
260
+ def _outcome(c: Contribution) -> str:
261
+ return _coded(f"{c.status}: {c.reason}", c.code) if c.reason else c.status
262
+
263
+
264
+ def config_effect(name: str) -> str:
265
+ """Whether importing ``name``'s entry points sets AGENT_ENV_CONFIG, checked in a fresh
266
+ interpreter: this process has already imported the CLI plugins, so it cannot tell."""
267
+ try:
268
+ value = _plugin_changes.config_set_by(name)
269
+ except _plugin_changes.ProbeError as exc:
270
+ return f"not checked: {exc}"
271
+ return f"importing it sets AGENT_ENV_CONFIG to {value}" if value else "importing it leaves AGENT_ENV_CONFIG unset"
272
+
273
+
274
+ def _requires_core(name: str) -> list[str]:
275
+ """The requirements naming agent-env."""
276
+ found = []
277
+ for requirement in distribution(name).requires or []:
278
+ project = re.match(r"\s*([A-Za-z0-9][A-Za-z0-9._-]*)", requirement)
279
+ if project and _normalized(project.group(1)) == _normalized(_CORE):
280
+ found.append(requirement)
281
+ return found
282
+
283
+
284
+ def render_show(report: Report, dist: Distribution, effect: Optional[str]) -> str:
285
+ lines = [f"{dist.name} {dist.version}"]
286
+ try:
287
+ requires = _requires_core(dist.name)
288
+ location = distribution(dist.name).locate_file("")
289
+ except PackageNotFoundError:
290
+ requires, location = [], None
291
+ if dist.name == _CORE:
292
+ lines.append(" agent-env itself")
293
+ else:
294
+ lines.append(f" requires: {', '.join(requires) or 'no agent-env requirement declared'} "
295
+ f"(installed {report.core_version})")
296
+ if location is not None:
297
+ lines.append(f" location: {location}")
298
+ if effect is not None:
299
+ lines.append(f" config: {effect}")
300
+ lines.append("")
301
+ rows = [(_KINDS[c.group][0], c.name, c.value, _outcome(c)) for c in dist.contributions]
302
+ widths = [max(len(row[i]) for row in rows) for i in range(3)]
303
+ lines += [f" {kind:<{widths[0]}} {name:<{widths[1]}} {value:<{widths[2]}} {outcome}"
304
+ for kind, name, value, outcome in rows]
305
+ for group in dict.fromkeys(c.group for c in dist.contributions):
306
+ if (error := report.inventory.group_errors.get(group)) is not None:
307
+ lines += ["", _coded(f" (error) nothing in {group} loads: {error.reason}", error.code)]
308
+ return "\n".join(lines)
309
+
310
+
311
+ def _normalized(name: str) -> str:
312
+ return re.sub(r"[-_.]+", "-", name).lower()
313
+
314
+
315
+ def _root() -> click.Group:
316
+ return click.get_current_context().find_root().command
317
+
318
+
319
+ @click.group()
320
+ def plugin():
321
+ """Inspect, add and remove installed plugins."""
322
+
323
+
324
+ @plugin.command(name="list")
325
+ @click.option("--json", "as_json", is_flag=True, help="Machine-readable.")
326
+ @click.option("--no-load", is_flag=True, help="Read installed metadata only; import no type plugin.")
327
+ def list_command(as_json: bool, no_load: bool):
328
+ """List every installed plugin package, what it provides, and whether it took effect."""
329
+ report = collect(_root(), load=not no_load)
330
+ click.echo(_json(_as_dict(report)) if as_json else render_list(report))
331
+
332
+
333
+ @plugin.command()
334
+ @click.argument("package")
335
+ @click.option("--json", "as_json", is_flag=True, help="Machine-readable.")
336
+ @click.option("--no-load", is_flag=True, help="Read installed metadata only; import no type plugin.")
337
+ def show(package: str, as_json: bool, no_load: bool):
338
+ """Show one plugin PACKAGE: each contribution, its status and why."""
339
+ report = collect(_root(), load=not no_load)
340
+ matches = [d for d in report.distributions if _normalized(d.name) == _normalized(package)]
341
+ if not matches:
342
+ known = ", ".join(d.name for d in report.distributions) or "none"
343
+ raise click.ClickException(f"no installed plugin package named {package!r} (installed: {known})")
344
+ dist = matches[0]
345
+ effect = None if no_load else config_effect(dist.name)
346
+ if as_json:
347
+ click.echo(_json({**_as_dict(report), "plugins": [dataclasses.asdict(dist)], "config_effect": effect}))
348
+ return
349
+ click.echo(render_show(report, dist, effect))
350
+
351
+
352
+ @plugin.command()
353
+ @click.option("--json", "as_json", is_flag=True, help="Machine-readable.")
354
+ @click.pass_context
355
+ def check(ctx: click.Context, as_json: bool):
356
+ """Load every plugin; exit 1 if any contribution did not take effect, or if the config or the
357
+ installed entry points cannot be read.
358
+
359
+ A replaced contribution is not a failure: config chose it. Meant for CI and image builds.
360
+ """
361
+ report = collect(_root(), load=True)
362
+ problems = [(d, c) for d in report.distributions for c in d.contributions if c.status in _CHECK_FAILS]
363
+ error = report.inventory.config_error
364
+ unread = dict(report.discovery_errors)
365
+ reasons = (
366
+ ([f"{len(problems)} plugin contribution(s) did not take effect"] if problems else [])
367
+ + (["the config could not be read"] if error else [])
368
+ + (["installed entry points could not be read"] if unread else [])
369
+ )
370
+ if as_json:
371
+ click.echo(_json({
372
+ **_as_dict(report),
373
+ "ok": not reasons,
374
+ "problems": [{"package": d.name, "version": d.version, **dataclasses.asdict(c)} for d, c in problems],
375
+ }))
376
+ if reasons:
377
+ ctx.exit(1)
378
+ return
379
+ for d, c in problems:
380
+ click.echo(f"{d.name} {d.version}: {_KINDS[c.group][0]} {c.name}: {_outcome(c)}")
381
+ if error:
382
+ click.echo(_coded(f"config: {error.reason}", error.code))
383
+ for line in _unreadable(report):
384
+ click.echo(line)
385
+ if reasons:
386
+ raise click.ClickException("; ".join(reasons))
387
+ total = sum(len(d.contributions) for d in report.distributions)
388
+ replaced = sum(c.status == "replaced" for d in report.distributions for c in d.contributions)
389
+ note = f"; {replaced} replaced by config" if replaced else ", all in effect"
390
+ click.echo(f"ok: {len(report.distributions)} plugin package(s), {total} contribution(s){note}")
391
+
392
+
393
+ @plugin.command()
394
+ @click.argument("specs", nargs=-1, required=True)
395
+ @click.option("--installer", type=click.Choice(sorted(FORCEABLE)), help="Use this installer, not the detected one.")
396
+ @click.option("--index-url", help="The index the installer resolves from, passed through to it.")
397
+ @click.option("--dry-run", is_flag=True, help="Show what would run, and change nothing.")
398
+ @click.option("--yes", "-y", is_flag=True, help="Do not ask before changing the environment.")
399
+ @click.option("--keep", is_flag=True, help="Keep the change even when a plugin does not take effect.")
400
+ @click.pass_context
401
+ def add(ctx: click.Context, specs: tuple[str, ...], installer: Optional[str], index_url: Optional[str],
402
+ dry_run: bool, yes: bool, keep: bool):
403
+ """Install plugin packages through the installer that owns this environment, then check them.
404
+
405
+ SPECS are whatever that installer accepts: names with versions, paths, URLs. If a new plugin
406
+ does not take effect, the environment is restored as it was, unless --keep.
407
+ """
408
+ try:
409
+ code = _plugin_changes.add(list(specs), installer=installer, index_url=index_url, dry_run=dry_run, yes=yes,
410
+ keep=keep, tools=_plugin_changes.Tools())
411
+ except InstallerError as exc:
412
+ raise click.ClickException(str(exc)) from exc
413
+ ctx.exit(code)
414
+
415
+
416
+ @plugin.command()
417
+ @click.argument("packages", nargs=-1, required=True)
418
+ @click.option("--installer", type=click.Choice(sorted(FORCEABLE)), help="Use this installer, not the detected one.")
419
+ @click.option("--dry-run", is_flag=True, help="Show what would run, and change nothing.")
420
+ @click.option("--yes", "-y", is_flag=True, help="Do not ask before changing the environment.")
421
+ @click.option("--force", is_flag=True, help="Remove even when something still depends on or names the package.")
422
+ @click.option("--check-usage", is_flag=True, help="Also count stored documents in a remote document store.")
423
+ @click.pass_context
424
+ def remove(ctx: click.Context, packages: tuple[str, ...], installer: Optional[str], dry_run: bool, yes: bool,
425
+ force: bool, check_usage: bool):
426
+ """Uninstall plugin PACKAGES through the installer that owns this environment.
427
+
428
+ A package that `plugin add` installed next to a plugin, such as a pin it needs, can be removed
429
+ too. Refused, unless --force, while another package requires it, the config file names what it
430
+ provides, or stored documents use its types (checked for a local store; --check-usage for a
431
+ remote one).
432
+ """
433
+ try:
434
+ code = _plugin_changes.remove(list(packages), installer=installer, dry_run=dry_run, yes=yes, force=force,
435
+ check_usage=check_usage, tools=_plugin_changes.Tools())
436
+ except InstallerError as exc:
437
+ raise click.ClickException(str(exc)) from exc
438
+ ctx.exit(code)