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,277 @@
1
+ """The local explorer: a FastAPI control plane over the configured stores and runner.
2
+
3
+ Serves eight surfaces: Home, Docs, Task Hub, Task Runner, Evals Hub, Environment Hub,
4
+ Agents Hub, Universes Hub. Universes are not a resource — they are ``artifacts`` filtered
5
+ by type — so they need no routes of their own.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import logging
11
+ from contextlib import asynccontextmanager
12
+ from pathlib import Path
13
+ from typing import Optional
14
+
15
+ from fastapi import FastAPI
16
+ from fastapi.middleware.cors import CORSMiddleware
17
+ from fastapi.responses import JSONResponse
18
+
19
+ from agent_env.config import get_config, get_runner, runtime
20
+ from agent_env.config.errors import ConfigError
21
+ from agent_env.explorer.openapi_docs import docs_metadata, enrich_openapi_schema
22
+ from agent_env.explorer.plugin import load_plugins
23
+ from agent_env.explorer.routers import conversations as conversations_router
24
+ from agent_env.explorer.routers import objects as objects_router
25
+ from agent_env.explorer.routers import runs as runs_router
26
+ from agent_env.explorer.routers.common import versioned_router
27
+ from agent_env.store import NotFoundError
28
+ from agent_env.store.routing import configured_store
29
+
30
+ logger = logging.getLogger(__name__)
31
+
32
+ API = "/api/v1"
33
+
34
+ # Host headers we always accept; everything else is refused — a DNS-rebinding defense.
35
+ # (The packaged explorer binds loopback only — see LOCAL_BIND_HOST — so this is
36
+ # defense-in-depth, not the sole barrier.)
37
+ _LOOPBACK_HOSTS = frozenset({"localhost", "127.0.0.1", "[::1]"})
38
+
39
+ # FastAPI's own API-docs pages, exempted from the app CSP (see the guard middleware).
40
+ # Keep in step with the docs_url / redoc_url / openapi_url passed to FastAPI below.
41
+ _DOCS_PATHS = frozenset({"/api/docs", "/api/redoc", "/openapi.json"})
42
+
43
+ # The packaged explorer is an unauthenticated local control plane, so it always binds
44
+ # loopback — a ``0.0.0.0`` footgun is simply unrepresentable. A hosted deployment that
45
+ # needs a public bind runs its own ``uvicorn agent_env.explorer.app:create_app --factory
46
+ # --host …`` and lists its public hostname(s) under ``[explorer] allowed_hosts``.
47
+ LOCAL_BIND_HOST = "127.0.0.1"
48
+
49
+
50
+ def _host_only(raw: str) -> str:
51
+ """The host from a ``Host`` header with the port stripped (IPv6 literals stay bracketed)."""
52
+ raw = raw.strip().lower()
53
+ if raw.startswith("["):
54
+ return raw[: raw.find("]") + 1]
55
+ return raw.split(":", 1)[0]
56
+
57
+
58
+ def packaged_ui_dir() -> Optional[str]:
59
+ """The UI shipped inside the wheel (``agent_env/explorer/static``), or None from a source
60
+ checkout with no built ``static/`` — then the explorer is API-only unless ``--ui`` is given."""
61
+ candidate = Path(__file__).parent / "static"
62
+ return str(candidate) if (candidate / "index.html").is_file() else None
63
+
64
+
65
+ def explorer_settings() -> dict:
66
+ """The ``[explorer]`` table: port, CORS origins, Host allow-list, and static dir.
67
+
68
+ ``host`` is intentionally *not* read from config — the packaged explorer always binds
69
+ loopback (see ``LOCAL_BIND_HOST``); a hosted deployment sets its bind via its own
70
+ ``uvicorn --host`` and opts hostnames in through ``allowed_hosts``."""
71
+ section = runtime.get_config().section("explorer")
72
+ return {
73
+ "host": LOCAL_BIND_HOST, # loopback only; not configurable — see docstring
74
+ "port": int(section.get("port", 8234)),
75
+ "cors_origins": section.get("cors_origins"),
76
+ "allowed_hosts": section.get("allowed_hosts") or [],
77
+ "static_dir": section.get("static_dir") or None,
78
+ }
79
+
80
+
81
+ @asynccontextmanager
82
+ async def lifespan(app: FastAPI):
83
+ cfg = get_config()
84
+ logger.info("agent-env explorer starting")
85
+ logger.info("document store: %s", type(configured_store(cfg.get_document_store())).__name__)
86
+
87
+ runner = get_runner()
88
+ logger.info("runner: %s (%s)", runner.type, type(runner).__name__)
89
+ await runner.start() # in-process for LocalRunner; a no-op for external ones
90
+ try:
91
+ yield
92
+ finally:
93
+ await runner.stop()
94
+
95
+
96
+ def create_app(static_dir: Optional[str] = None) -> FastAPI:
97
+ settings = explorer_settings()
98
+ app = FastAPI(
99
+ title="agent-env explorer",
100
+ description="Local control plane for agent-env: browse environments, tasks, "
101
+ "agents, universes and evals, and run tasks.",
102
+ version="0.1.0",
103
+ lifespan=lifespan,
104
+ # Swagger under /api; the UI owns /docs. openapi_url stays at the root for the UI.
105
+ docs_url="/api/docs",
106
+ redoc_url="/api/redoc",
107
+ openapi_url="/openapi.json",
108
+ )
109
+ # Loopback-only by default (a no-auth local explorer); an explicit [explorer] cors_origins overrides.
110
+ cors = settings["cors_origins"]
111
+ if cors and "*" in cors:
112
+ raise ConfigError(
113
+ "[explorer] cors_origins cannot contain '*': the explorer has no auth, so a "
114
+ "wildcard would let any site you visit drive it. List the origins explicitly."
115
+ )
116
+ app.add_middleware(
117
+ CORSMiddleware,
118
+ allow_origins=cors or [],
119
+ allow_origin_regex=None if cors else r"https?://(localhost|127\.0\.0\.1)(:\d+)?",
120
+ allow_methods=["GET", "POST", "OPTIONS"],
121
+ allow_headers=["*"],
122
+ )
123
+
124
+ # A no-auth local explorer needs two guards CORS alone doesn't give (CORS withholds
125
+ # the *response*, not the *request*). The bind is loopback-only, so the Host allow-list
126
+ # is just loopback plus any hostnames a hosted deployment explicitly opts into.
127
+ allowed_hosts = set(_LOOPBACK_HOSTS) | {str(h).lower() for h in settings["allowed_hosts"]}
128
+ # Configuring cors_origins used to switch the CSRF guard off for all of /api. On a
129
+ # no-auth plane that traded a named allowlist for none at all: any site could drive
130
+ # a cross-site write, not just the ones opted in. The guard now stays on and admits
131
+ # a cross-site request only when its Origin is one of the configured values.
132
+ allowed_origins = {str(o).rstrip("/").lower() for o in (cors or [])}
133
+
134
+ @app.middleware("http")
135
+ async def _guard(request, call_next):
136
+ # Host allow-list: reject a Host that isn't loopback / configured — blocks
137
+ # DNS-rebinding (an attacker domain pointed at 127.0.0.1 arrives with its own
138
+ # Host). The bind is loopback-only, so this backs that up rather than standing alone.
139
+ host = _host_only(request.headers.get("host") or "")
140
+ if host and host not in allowed_hosts:
141
+ return JSONResponse(status_code=421, content={"detail": f"host {host!r} not allowed"})
142
+ # CSRF: a page you visit while `up` runs can't read our loopback-CORS reply,
143
+ # but a cross-site *write* already fires. Browsers tag such requests
144
+ # Sec-Fetch-Site: cross-site (a forbidden header page JS can't set); curl and
145
+ # the agent-env CLI send none, so only a genuine browser cross-site hit to
146
+ # /api is refused.
147
+ if (request.url.path.startswith("/api")
148
+ and request.headers.get("sec-fetch-site") == "cross-site"
149
+ and (request.headers.get("origin") or "").rstrip("/").lower() not in allowed_origins):
150
+ return JSONResponse(status_code=403, content={"detail": "cross-site request refused"})
151
+ response = await call_next(request)
152
+ # The object byte-proxy picks its own per-content-type policy (CSP: sandbox on
153
+ # active types, deliberately none on passive ones), so leave it alone entirely
154
+ # rather than layering a weaker app policy over it.
155
+ if request.url.path.startswith(f"{API}/objects/"):
156
+ return response
157
+ # Swagger and ReDoc load their bundles from a CDN, so `default-src 'self'`
158
+ # blanks both pages. They serve no agent-produced bytes; exempting them beats
159
+ # widening the policy everywhere. Self-hosting the assets would be better.
160
+ if request.url.path in _DOCS_PATHS:
161
+ return response
162
+ # These bound what a compromised page can reach (frame-ancestors, object-src,
163
+ # base-uri, connect-src); they are NOT a backstop for an inline handler, since
164
+ # script-src must keep 'unsafe-inline' for the static export's one bootstrap
165
+ # script — containment for agent-produced bytes is the preview sandbox.
166
+ # 'unsafe-eval' is withheld: the built bundle has no eval/new Function.
167
+ # setdefault, so a route that chose its own policy keeps it.
168
+ response.headers.setdefault(
169
+ "Content-Security-Policy",
170
+ "default-src 'self'; "
171
+ "script-src 'self' 'unsafe-inline'; "
172
+ "style-src 'self' 'unsafe-inline'; "
173
+ "img-src 'self' data: blob:; "
174
+ "font-src 'self' data:; "
175
+ "connect-src 'self'; "
176
+ "object-src 'none'; "
177
+ "base-uri 'self'; "
178
+ "form-action 'self'; "
179
+ "frame-ancestors 'none'",
180
+ )
181
+ response.headers.setdefault("X-Content-Type-Options", "nosniff")
182
+ response.headers.setdefault("Referrer-Policy", "no-referrer")
183
+ response.headers.setdefault("X-Frame-Options", "DENY")
184
+ return response
185
+
186
+ @app.exception_handler(NotFoundError)
187
+ async def _not_found(request, exc: NotFoundError):
188
+ return JSONResponse(status_code=404, content={"detail": str(exc)})
189
+
190
+ # Plugins mount BEFORE the core routers so a plugin may add a literal path under
191
+ # a core prefix (e.g. /api/v1/agents/trajectory-url) that the core /{entity_id}
192
+ # catch-all would otherwise shadow — Starlette matches in registration order.
193
+ for plugin in load_plugins():
194
+ logger.info("Mounting explorer plugin %r", plugin.type)
195
+ app.include_router(plugin.router)
196
+
197
+ # The five (id, version) collections behind Task/Env/Agent/Universe/Evals Hub.
198
+ # Universes Hub reads /artifacts?type=environment_universe — no route of its own.
199
+ app.include_router(versioned_router(prefix=f"{API}/artifacts", tag="artifacts", collection="artifacts"))
200
+ app.include_router(versioned_router(prefix=f"{API}/envs", tag="envs", collection="envs"))
201
+ app.include_router(versioned_router(prefix=f"{API}/tasks", tag="tasks", collection="tasks"))
202
+ app.include_router(versioned_router(prefix=f"{API}/agents", tag="agents", collection="a2a_agents"))
203
+ app.include_router(versioned_router(prefix=f"{API}/evals", tag="evals", collection="evals"))
204
+ app.include_router(runs_router.router)
205
+ app.include_router(objects_router.router)
206
+ app.include_router(conversations_router.router)
207
+
208
+ @app.get(f"{API}/docs/openapi", include_in_schema=False)
209
+ def openapi_document() -> dict:
210
+ """The explorer's OpenAPI schema plus its primitive catalogue, enriched per-request so a
211
+ lazily-registered primitive still appears."""
212
+ return enrich_openapi_schema(dict(app.openapi()))
213
+
214
+ @app.get(f"{API}/docs/openapi/metadata", include_in_schema=False)
215
+ def openapi_metadata() -> dict:
216
+ """Provenance for the spec above."""
217
+ return docs_metadata(app.openapi())
218
+
219
+ def _health() -> dict:
220
+ cfg = get_config()
221
+ return {
222
+ "status": "ok",
223
+ "document_store": type(configured_store(cfg.get_document_store())).__name__,
224
+ "runner": get_runner().type,
225
+ }
226
+
227
+ app.get("/health")(_health)
228
+
229
+ static = static_dir or settings["static_dir"] or packaged_ui_dir()
230
+ if not (static and Path(static).is_dir()):
231
+ # Serve health at "/" only when no UI is mounted (else the SPA owns "/").
232
+ app.get("/")(_health)
233
+
234
+ if static and Path(static).is_dir():
235
+ _mount_spa(app, Path(static))
236
+ logger.info("Serving UI from %s", static)
237
+
238
+ return app
239
+
240
+
241
+ def _mount_spa(app: FastAPI, root: Path) -> None:
242
+ """Serve a client-routed SPA from ``root``: real files served directly, all other paths
243
+ fall back to ``index.html``. Registered after the API routers; refuses ``/api``/``/health``.
244
+ """
245
+ from fastapi import HTTPException
246
+ from fastapi.responses import FileResponse
247
+ from fastapi.staticfiles import StaticFiles
248
+
249
+ index = root / "index.html"
250
+ if not index.is_file():
251
+ raise RuntimeError(
252
+ f"{root} has no index.html — build the UI with `npm run build:static` "
253
+ "(a plain `next build` leaves the catch-all as '[[...slug]].html')."
254
+ )
255
+
256
+ for sub in ("_next", "logos"):
257
+ if (root / sub).is_dir():
258
+ app.mount(f"/{sub}", StaticFiles(directory=root / sub), name=f"ui-{sub}")
259
+
260
+ @app.get("/{path:path}", include_in_schema=False)
261
+ def spa(path: str):
262
+ if path.startswith("api/") or path in {"health", "api", "openapi.json"}:
263
+ raise HTTPException(status_code=404, detail="Not Found")
264
+ candidate = (root / path).resolve()
265
+ if path and candidate.is_file() and candidate.is_relative_to(root.resolve()):
266
+ return FileResponse(candidate)
267
+ return FileResponse(index)
268
+
269
+
270
+ def __getattr__(name: str):
271
+ # Lazy module-level ``app`` so importing this module (e.g. ``up`` importing
272
+ # ``explorer_settings``, or the test suite) doesn't eagerly build the app — a bad
273
+ # [explorer] static_dir or plugin entry would otherwise turn a config error into an
274
+ # import error. Deployments can still point uvicorn at ``agent_env.explorer.app:app``.
275
+ if name == "app":
276
+ return create_app()
277
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
@@ -0,0 +1,242 @@
1
+ """Docs support: describe *this* install's primitives alongside its API schema.
2
+
3
+ The Docs surface renders two things — the explorer's OpenAPI operations, and a catalogue of
4
+ the agent-env primitives available here (artifact types, env types, task-step types).
5
+
6
+ The primitive catalogue is built by walking the same registries the runtime dispatches
7
+ on, so anything registered through ``[artifacts]`` / ``[envs]`` / ``[task_steps]`` in a
8
+ ``config.toml`` shows up in the docs automatically.
9
+
10
+ Each entry carries where the class actually lives (module + line), so a reader can jump
11
+ from "this task step exists" to its source without a search.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import copy
17
+ import inspect
18
+ import logging
19
+ from datetime import datetime, timezone
20
+ from importlib.metadata import PackageNotFoundError, version as pkg_version
21
+ from typing import Any, Callable, Mapping
22
+
23
+ logger = logging.getLogger(__name__)
24
+
25
+ PRIMITIVES_VERSION = 1
26
+
27
+
28
+ _PRIMITIVE_TYPE_MAP: dict[Any, dict[str, Any]] = {
29
+ str: {"type": "string"},
30
+ int: {"type": "integer"},
31
+ float: {"type": "number"},
32
+ bool: {"type": "boolean"},
33
+ dict: {"type": "object"},
34
+ list: {"type": "array"},
35
+ }
36
+
37
+
38
+ def _annotation_schema(annotation: Any) -> dict[str, Any]:
39
+ """A shallow JSON-Schema sketch of a type annotation for the Docs page; anything it
40
+ cannot map cleanly is reported by name under ``x-python-type``."""
41
+ import typing
42
+
43
+ if annotation is inspect.Parameter.empty:
44
+ return {}
45
+ if annotation in _PRIMITIVE_TYPE_MAP:
46
+ return dict(_PRIMITIVE_TYPE_MAP[annotation])
47
+
48
+ origin = typing.get_origin(annotation)
49
+ args = [a for a in typing.get_args(annotation) if a is not type(None)]
50
+ if origin in (list, set, tuple):
51
+ return {"type": "array", "items": _annotation_schema(args[0]) if args else {}}
52
+ if origin is dict:
53
+ return {"type": "object"}
54
+ if origin is not None and args: # Optional[X] / Union[X, None]
55
+ schema = _annotation_schema(args[0])
56
+ if len(args) == 1:
57
+ schema["nullable"] = True
58
+ return schema
59
+
60
+ name = getattr(annotation, "__name__", None) or str(annotation)
61
+ return {"x-python-type": name}
62
+
63
+
64
+ def _resolved_hints(func: Callable) -> dict[str, Any]:
65
+ """Real type objects for ``func``'s annotations (via ``get_type_hints``, which resolves
66
+ the string annotations ``from __future__ import annotations`` produces), or ``{}`` if
67
+ resolution fails."""
68
+ import typing
69
+
70
+ try:
71
+ return typing.get_type_hints(func)
72
+ except Exception:
73
+ return {}
74
+
75
+
76
+ def _constructor_schema(cls: type, primitive_type: str) -> dict[str, Any]:
77
+ """Describe ``cls.__init__`` as an object schema: one property per keyword."""
78
+ try:
79
+ signature = inspect.signature(cls.__init__)
80
+ except (TypeError, ValueError):
81
+ return {"type": "object", "title": cls.__name__}
82
+ hints = _resolved_hints(cls.__init__)
83
+
84
+ properties: dict[str, Any] = {}
85
+ required: list[str] = []
86
+ for name, param in signature.parameters.items():
87
+ if name in ("self", "args", "kwargs") or param.kind in (
88
+ inspect.Parameter.VAR_POSITIONAL, inspect.Parameter.VAR_KEYWORD
89
+ ):
90
+ continue
91
+ prop = _annotation_schema(hints.get(name, param.annotation))
92
+ if param.default is inspect.Parameter.empty:
93
+ required.append(name)
94
+ else:
95
+ try: # only inline JSON-representable defaults
96
+ import json
97
+ json.dumps(param.default)
98
+ prop["default"] = param.default
99
+ except (TypeError, ValueError):
100
+ pass
101
+ properties[name] = prop
102
+
103
+ schema: dict[str, Any] = {
104
+ "type": "object",
105
+ "title": cls.__name__,
106
+ "description": _description(cls) or f"Constructor arguments for {primitive_type!r}.",
107
+ "properties": properties,
108
+ }
109
+ if required:
110
+ schema["required"] = required
111
+ return schema
112
+
113
+
114
+ def _component_name(group: str, cls: type) -> str:
115
+ return f"AgentEnv{group[:1].upper()}{group[1:]}_{cls.__name__}"
116
+
117
+
118
+ def _description(cls: type) -> str:
119
+ """First paragraph of the class's own ``__doc__`` (not ``inspect.getdoc``, which would
120
+ inherit a base class's docstring), collapsed to one line."""
121
+ doc = cls.__dict__.get("__doc__") or ""
122
+ first = doc.strip().split("\n\n", 1)[0]
123
+ return " ".join(first.split())
124
+
125
+
126
+ def _source_location(cls: type) -> dict[str, Any]:
127
+ """Where the class is defined. Best-effort: a C or dynamically-built class has none."""
128
+ try:
129
+ module = inspect.getmodule(cls)
130
+ file = inspect.getsourcefile(cls) if module else None
131
+ _, line = inspect.getsourcelines(cls)
132
+ except (OSError, TypeError):
133
+ return {"module": getattr(cls, "__module__", "")}
134
+ return {"module": getattr(cls, "__module__", ""), "file": file, "line": line}
135
+
136
+
137
+ def _aliases_for_class(registry: Mapping[str, type], primitive_type: str, cls: type) -> list[str]:
138
+ """Other keys the same class is registered under (e.g. service/environment spellings)."""
139
+ return sorted(k for k, v in registry.items() if v is cls and k != primitive_type)
140
+
141
+
142
+ def _collect(
143
+ group: str, load: Callable[[], Mapping[str, type]], components: dict[str, Any]
144
+ ) -> list[dict[str, Any]]:
145
+ """One catalogue group, sorted by type. A registry that cannot be built is skipped."""
146
+ try:
147
+ registry = load()
148
+ except Exception:
149
+ logger.warning("Could not load the %s registry for docs", group, exc_info=True)
150
+ return []
151
+
152
+ entries: list[dict[str, Any]] = []
153
+ for primitive_type, cls in sorted(registry.items()):
154
+ if not inspect.isclass(cls):
155
+ continue
156
+ entry: dict[str, Any] = {
157
+ "type": primitive_type,
158
+ "className": cls.__name__,
159
+ "module": cls.__module__,
160
+ "description": _description(cls),
161
+ "source": _source_location(cls),
162
+ }
163
+ component_name = _component_name(group, cls)
164
+ components.setdefault(component_name, _constructor_schema(cls, primitive_type))
165
+ entry["component"] = f"#/components/schemas/{component_name}"
166
+ aliases = _aliases_for_class(registry, primitive_type, cls)
167
+ if aliases:
168
+ entry["aliases"] = aliases
169
+ entries.append(entry)
170
+ return entries
171
+
172
+
173
+ def collect_primitives(components: dict[str, Any] | None = None) -> dict[str, Any]:
174
+ """The artifact / env / task-step catalogue for this install.
175
+
176
+ Constructor schemas are written into ``components`` (the OpenAPI
177
+ ``components.schemas`` map) and referenced by each entry, so the Docs page can render
178
+ a primitive's arguments the same way it renders a request body.
179
+ """
180
+ from agent_env.artifact.registry import get_artifact_registry
181
+ from agent_env.env.registry import get_env_registry
182
+ from agent_env.task_step.registry import get_task_step_registry
183
+
184
+ components = {} if components is None else components
185
+ return {
186
+ "version": PRIMITIVES_VERSION,
187
+ "artifacts": _collect("artifacts", get_artifact_registry, components),
188
+ "envs": _collect("envs", get_env_registry, components),
189
+ "taskSteps": _collect("taskSteps", get_task_step_registry, components),
190
+ }
191
+
192
+
193
+ def enrich_openapi_schema(schema: dict[str, Any]) -> dict[str, Any]:
194
+ """Attach the primitive catalogue + a docs block to a generated OpenAPI schema.
195
+
196
+ Deep-copies the input first: the caller passes ``app.openapi()``, whose nested
197
+ ``components.schemas`` dict FastAPI caches — mutating it in place would make
198
+ ``/openapi.json`` (and the Swagger page) grow every time Docs is opened."""
199
+ schema = copy.deepcopy(schema)
200
+ components = schema.setdefault("components", {}).setdefault("schemas", {})
201
+ primitives = collect_primitives(components)
202
+ schema["x-agent-env-primitives"] = primitives
203
+ schema["x-agent-env-docs"] = {
204
+ "source": "live",
205
+ "description": (
206
+ "Served from the running explorer, so this reflects the primitives registered in "
207
+ "this install — including any added through .agentenv/config.toml."
208
+ ),
209
+ "counts": {
210
+ "artifacts": len(primitives["artifacts"]),
211
+ "envs": len(primitives["envs"]),
212
+ "taskSteps": len(primitives["taskSteps"]),
213
+ "operations": sum(
214
+ 1
215
+ for ops in (schema.get("paths") or {}).values()
216
+ for method in ops
217
+ if method in {"get", "post", "put", "patch", "delete"}
218
+ ),
219
+ },
220
+ }
221
+ return schema
222
+
223
+
224
+ def _package_version(name: str) -> str:
225
+ try:
226
+ return pkg_version(name)
227
+ except PackageNotFoundError:
228
+ return ""
229
+
230
+
231
+ def docs_metadata(schema: dict[str, Any]) -> dict[str, Any]:
232
+ """Provenance for the live served spec: source, timestamp, OpenAPI version, and
233
+ package versions."""
234
+ return {
235
+ "source": "live",
236
+ "generated_at": datetime.now(timezone.utc).isoformat(),
237
+ "openapi_version": schema.get("openapi", ""),
238
+ "versions": {
239
+ "agentenv-framework": _package_version("agentenv-framework"),
240
+ "agentenv-protocol": _package_version("agentenv-framework-protocol") or _package_version("agentenv-protocol"),
241
+ },
242
+ }
@@ -0,0 +1,95 @@
1
+ """``ExplorerPlugin`` — a class wrapping an ``APIRouter`` so an installed package can add routes
2
+ to the explorer, through an ``agent_env.explorer_plugins`` entry point or ``[explorer.plugins]``.
3
+
4
+ Plugins mount *before* the core routers (see ``create_app``), so a plugin may add a
5
+ literal path under a core prefix (e.g. ``/api/v1/agents/trajectory-url``) that the core
6
+ ``/{entity_id}`` catch-all would otherwise shadow. ``[explorer.plugins].impls`` is a flat list of
7
+ ``module:Class`` strings, so this seam contributes routes; a plugin reads its own settings from
8
+ ``[plugins.<distribution name>]`` with ``agent_env.plugins.settings``.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from abc import ABC, abstractmethod
14
+ from typing import TYPE_CHECKING, ClassVar, Self
15
+
16
+ from agent_env.plugins import _registration, _report
17
+
18
+ if TYPE_CHECKING:
19
+ from fastapi import APIRouter
20
+ from agent_env.config.runtime import Config
21
+
22
+
23
+ class ExplorerPlugin(ABC):
24
+ """A named bundle of routes contributed to the explorer by an installed package."""
25
+
26
+ type: ClassVar[str] = "explorer_plugin"
27
+
28
+ @classmethod
29
+ def from_config(cls) -> Self:
30
+ # [explorer.plugins].impls is a flat list of 'module:Class' strings, so a plugin is
31
+ # constructed with no arguments and reads its settings with agent_env.plugins.settings.
32
+ return cls()
33
+
34
+ @property
35
+ @abstractmethod
36
+ def router(self) -> "APIRouter":
37
+ """The router to mount. Its prefix should be namespaced under /api/v1."""
38
+
39
+
40
+ def load_plugins(*, source: Config | None = None) -> list[ExplorerPlugin]:
41
+ """Instantiate every ``agent_env.explorer_plugins`` entry point, then every
42
+ ``[explorer.plugins] impls`` entry, raising on a missing ``type``, a duplicate, or a bad spec.
43
+ An impl whose ``type`` a plugin already registered replaces it, with a warning. A plugin that
44
+ fails to construct is skipped and recorded, like one that fails to load; an impl raises.
45
+ ``router`` is left unread: ``create_app`` reads it once, to mount it."""
46
+ from agent_env.config import runtime
47
+ from agent_env.config import ConfigError, load_impl
48
+
49
+ config = source or runtime.get_config()
50
+ section = config.section("explorer", "plugins")
51
+ impls = section.get("impls", [])
52
+ if not isinstance(impls, list):
53
+ raise ConfigError(
54
+ f"[explorer.plugins] impls must be a list of 'module:Class' strings, got {type(impls).__name__}"
55
+ )
56
+
57
+ classes: dict[str, type[ExplorerPlugin]] = {}
58
+ validate = _registration.typed_validator(ExplorerPlugin)
59
+ from_plugins = _registration.merge(classes, _registration.EXPLORER_PLUGINS, validate, source=config)
60
+ # Placeholders keep each plugin's mount position while impls are constructed in list order.
61
+ built: dict[str, ExplorerPlugin | None] = dict.fromkeys(classes)
62
+ seen: dict[str, str] = {}
63
+ for impl in impls:
64
+ if not isinstance(impl, str):
65
+ raise ConfigError(
66
+ f"[explorer.plugins] impl must be a 'module:Class' string, got {type(impl).__name__}: {impl!r}"
67
+ )
68
+ cls = load_impl(impl, ExplorerPlugin)
69
+ if cls.type == ExplorerPlugin.type:
70
+ raise ConfigError(
71
+ f"[explorer.plugins] impl {impl!r} does not define its own 'type' "
72
+ f"(inherits the base default {ExplorerPlugin.type!r}); set a unique 'type' ClassVar"
73
+ )
74
+ if cls.type in seen:
75
+ raise ConfigError(
76
+ f"[explorer.plugins] impl {impl!r} type {cls.type!r} is already registered by {seen[cls.type]!r}"
77
+ )
78
+ if problem := _registration.unimplemented(cls, ExplorerPlugin):
79
+ raise ConfigError(f"[explorer.plugins] impl {impl!r}: {problem}")
80
+ seen[cls.type] = impl
81
+ if from_plugins.refuse(cls.type, f"[explorer.plugins] impl {impl!r}"):
82
+ continue
83
+ from_plugins.release(cls.type, "explorer.plugins", impl, cls)
84
+ classes[cls.type] = cls
85
+ built[cls.type] = cls.from_config()
86
+ for name in from_plugins:
87
+ try:
88
+ instance = classes[name].from_config()
89
+ except (Exception, SystemExit) as exc:
90
+ from_plugins.reject(name, _report.LOAD_FAILED, f"failed to construct: {exc!r}")
91
+ del built[name]
92
+ continue
93
+ built[name] = instance
94
+ return [instance for instance in built.values() if instance is not None]
95
+
@@ -0,0 +1 @@
1
+ """Core explorer routers — the eight in-scope surfaces, DocumentStore-only."""