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,60 @@
1
+ """Backend-agnostic document store abstraction + its implementations.
2
+
3
+ ``document_store`` defines the abstraction (Filter/UpdateSpec/Sort/DocumentStore/
4
+ VersionedEntityStore); ``mongo_document_store``, ``sqlite_document_store``, and
5
+ ``dynamodb_document_store`` are implementations. ``firestore_mongo_document_store`` is one
6
+ too, not re-exported here because it needs the ``gcp`` extra. Future backends (Cosmos DB,
7
+ ...) live alongside as new modules.
8
+ """
9
+
10
+ from agent_env.store.document_store.document_store import (
11
+ AbsentOrNull,
12
+ DocumentStore,
13
+ DuplicateKeyError,
14
+ Eq,
15
+ Exists,
16
+ Filter,
17
+ Gte,
18
+ In,
19
+ Lte,
20
+ LteOrAbsent,
21
+ Ne,
22
+ Predicate,
23
+ Sort,
24
+ SortKey,
25
+ UpdateSpec,
26
+ VersionedEntityStore,
27
+ VersionedEntityStoreCache,
28
+ compare_and_swap,
29
+ reject_reserved_id,
30
+ rev_precondition,
31
+ )
32
+ from agent_env.store.document_store.dynamodb_document_store import DynamoDbDocumentStore
33
+ from agent_env.store.document_store.mongo_document_store import MongoDocumentStore
34
+ from agent_env.store.document_store.sqlite_document_store import LocalSqliteDocumentStore
35
+
36
+ __all__ = [
37
+ "DocumentStore",
38
+ "DuplicateKeyError",
39
+ "MongoDocumentStore",
40
+ "LocalSqliteDocumentStore",
41
+ "DynamoDbDocumentStore",
42
+ "VersionedEntityStore",
43
+ "VersionedEntityStoreCache",
44
+ "compare_and_swap",
45
+ "reject_reserved_id",
46
+ "rev_precondition",
47
+ "Filter",
48
+ "Predicate",
49
+ "Eq",
50
+ "Ne",
51
+ "Gte",
52
+ "Lte",
53
+ "In",
54
+ "Exists",
55
+ "LteOrAbsent",
56
+ "AbsentOrNull",
57
+ "Sort",
58
+ "SortKey",
59
+ "UpdateSpec",
60
+ ]
@@ -0,0 +1,519 @@
1
+ """Backend-agnostic document store abstraction."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from abc import ABC, abstractmethod
7
+ from dataclasses import dataclass, field
8
+ from typing import Any, Callable, Generic, Optional, TypeVar, Union
9
+
10
+ from agent_env.store.ids import is_local_id
11
+
12
+ T = TypeVar("T")
13
+
14
+
15
+ # --- Predicates ------------------------------------------------------------
16
+
17
+
18
+ @dataclass(frozen=True)
19
+ class Eq:
20
+ """Field equals value."""
21
+
22
+ value: Any
23
+
24
+
25
+ @dataclass(frozen=True)
26
+ class Ne:
27
+ """Field is present and not equal to value; an absent field does not match."""
28
+
29
+ value: Any
30
+
31
+
32
+ @dataclass(frozen=True)
33
+ class Gte:
34
+ """Field is greater than or equal to value."""
35
+
36
+ value: Any
37
+
38
+
39
+ @dataclass(frozen=True)
40
+ class Lte:
41
+ """Field is less than or equal to value."""
42
+
43
+ value: Any
44
+
45
+
46
+ @dataclass(frozen=True)
47
+ class In:
48
+ """Field is one of values."""
49
+
50
+ values: list[Any]
51
+
52
+
53
+ @dataclass(frozen=True)
54
+ class Exists:
55
+ """Field is present (present=True) or absent (present=False)."""
56
+
57
+ present: bool
58
+
59
+
60
+ @dataclass(frozen=True)
61
+ class LteOrAbsent:
62
+ """Field is absent, null, or <= value."""
63
+
64
+ value: Any
65
+
66
+
67
+ @dataclass(frozen=True)
68
+ class AbsentOrNull:
69
+ """Field is absent or null."""
70
+
71
+
72
+ Predicate = Union[Eq, Ne, Gte, Lte, In, Exists, LteOrAbsent, AbsentOrNull]
73
+
74
+
75
+ @dataclass
76
+ class Filter:
77
+ """A flat AND of per-field predicate lists."""
78
+
79
+ conditions: dict[str, list[Predicate]] = field(default_factory=dict)
80
+
81
+ @classmethod
82
+ def of(cls, **eq: Any) -> "Filter":
83
+ """Build an all-equality filter, e.g. ``Filter.of(id="x", version=3)``."""
84
+ return cls({path: [Eq(value)] for path, value in eq.items()})
85
+
86
+ def where(self, field_path: str, predicate: Predicate) -> "Filter":
87
+ """Return a new filter with ``predicate`` added to ``field_path`` (AND)."""
88
+ merged = {path: list(preds) for path, preds in self.conditions.items()}
89
+ merged.setdefault(field_path, []).append(predicate)
90
+ return Filter(merged)
91
+
92
+
93
+ # --- Sort ------------------------------------------------------------------
94
+
95
+
96
+ @dataclass(frozen=True)
97
+ class SortKey:
98
+ field: str
99
+ descending: bool = True
100
+
101
+
102
+ @dataclass(frozen=True)
103
+ class Sort:
104
+ """An ordered list of sort keys (first key is primary)."""
105
+
106
+ keys: tuple[SortKey, ...] = ()
107
+
108
+ @classmethod
109
+ def by(cls, field: str, descending: bool = True) -> "Sort":
110
+ return cls((SortKey(field, descending),))
111
+
112
+
113
+ # --- Update ----------------------------------------------------------------
114
+
115
+
116
+ @dataclass
117
+ class UpdateSpec:
118
+ """A primitive, backend-agnostic document update; keys are dotted paths."""
119
+
120
+ set: dict[str, Any] = field(default_factory=dict)
121
+ unset: set[str] = field(default_factory=lambda: set())
122
+ inc: dict[str, Union[int, float]] = field(default_factory=dict)
123
+ add_to_set: dict[str, list[Any]] = field(default_factory=dict)
124
+ push: dict[str, list[Any]] = field(default_factory=dict)
125
+
126
+ def is_empty(self) -> bool:
127
+ return not (self.set or self.unset or self.inc or self.add_to_set or self.push)
128
+
129
+ def validate(self) -> None:
130
+ """Raise ValueError if a dotted path appears under more than one operator, or if one
131
+ emitted path is an ancestor of another (Mongo rejects both as a path conflict)."""
132
+ seen: dict[str, str] = {}
133
+ conflicts: set[str] = set()
134
+ groups = {
135
+ "set": self.set,
136
+ "unset": self.unset,
137
+ "inc": self.inc,
138
+ "add_to_set": self.add_to_set,
139
+ "push": self.push,
140
+ }
141
+ for op, mapping in groups.items():
142
+ for path in mapping:
143
+ if path in seen:
144
+ conflicts.add(path)
145
+ seen[path] = op
146
+ if conflicts:
147
+ raise ValueError(
148
+ f"UpdateSpec emits the same path under multiple operators: {sorted(conflicts)}"
149
+ )
150
+ nested = sorted(p for p in seen if any(p.startswith(q + ".") for q in seen))
151
+ if nested:
152
+ raise ValueError(f"UpdateSpec emits a path and one of its ancestors: {nested}")
153
+
154
+
155
+ class DuplicateKeyError(Exception):
156
+ """Raised by a ``DocumentStore`` write that would violate a unique index: an ``insert``, or the
157
+ insert an upsert falls back to when its filter matches nothing."""
158
+
159
+
160
+ def _dig(doc: dict, path: str) -> tuple[bool, Any]:
161
+ """Resolve a dotted path in ``doc``; ``(found, value)``, value None when absent."""
162
+ cur: Any = doc
163
+ for part in path.split("."):
164
+ if not isinstance(cur, dict) or part not in cur:
165
+ return False, None
166
+ cur = cur[part]
167
+ return True, cur
168
+
169
+
170
+ def _order_key(value: Any) -> Any:
171
+ """A total-order proxy for a JSON value used as a sort key. ``dict`` and ``list`` are the
172
+ only JSON types Python 3 refuses to ``<``-compare, so collapse them to a deterministic
173
+ string — a same-type sort bucket then never raises ``TypeError``. Scalars pass through so
174
+ their native ordering is preserved (``2 < 10``, not ``"10" < "2"``). ``default=str`` covers
175
+ any non-JSON leaf a backend may hand back (e.g. a BSON datetime)."""
176
+ if isinstance(value, (dict, list)):
177
+ return json.dumps(value, sort_keys=True, default=str)
178
+ return value
179
+
180
+
181
+ def _reduce_to_latest(docs: list[dict], id_field: str, version_field: str) -> list[dict]:
182
+ """Keep the highest-``version_field`` doc per ``id_field``; skip docs with no id."""
183
+ best: dict[Any, tuple[tuple[bool, Any], dict]] = {}
184
+ for doc in docs:
185
+ found, key = _dig(doc, id_field)
186
+ if not found:
187
+ continue
188
+ has_version, version = _dig(doc, version_field)
189
+ rank = (has_version and version is not None, version) # missing version sorts lowest
190
+ current = best.get(key)
191
+ if current is None or rank > current[0]:
192
+ best[key] = (rank, doc)
193
+ return [doc for _, doc in best.values()]
194
+
195
+
196
+ def _apply_sort(docs: list[dict], sort: Optional[Sort]) -> list[dict]:
197
+ """Apply ``sort`` to an already-materialized list; absent values order last,
198
+ independent of each key's direction. The sort key is ``(type_name, order_key)``: the
199
+ type name keeps mixed-type values across documents (an int in one, a str in another)
200
+ from ever reaching a ``<`` (Python 3 refuses to compare unlike types), and ``_order_key``
201
+ keeps same-type-but-uncomparable values (two dicts, two lists) from raising too —
202
+ within a type, by value."""
203
+ if not sort or not sort.keys:
204
+ return docs
205
+ ordered = list(docs)
206
+ for key in reversed(sort.keys):
207
+ present, absent = [], []
208
+ for doc in ordered:
209
+ found, value = _dig(doc, key.field)
210
+ (present if found and value is not None else absent).append(doc)
211
+ present.sort(
212
+ key=lambda d, f=key.field: (type(v := _dig(d, f)[1]).__name__, _order_key(v)),
213
+ reverse=key.descending,
214
+ )
215
+ ordered = present + absent
216
+ return ordered
217
+
218
+
219
+ class DocumentStore(ABC):
220
+ """A backend-agnostic document store over named collections; backend id fields never leak."""
221
+
222
+ @classmethod
223
+ def from_config(cls, **config) -> DocumentStore:
224
+ """Construct from a resolved config table; backends that build a client override this."""
225
+ return cls(**config)
226
+
227
+ @abstractmethod
228
+ def find_one(
229
+ self, collection: str, filter: Filter, sort: Optional[Sort] = None
230
+ ) -> Optional[dict]:
231
+ """Return the first matching document (per ``sort``), or None."""
232
+
233
+ @abstractmethod
234
+ def query(
235
+ self,
236
+ collection: str,
237
+ filter: Filter,
238
+ sort: Optional[Sort] = None,
239
+ limit: Optional[int] = None,
240
+ offset: Optional[int] = None,
241
+ ) -> list[dict]:
242
+ """Return all matching documents, applying sort then offset then limit."""
243
+
244
+ @abstractmethod
245
+ def count(self, collection: str, filter: Filter) -> int:
246
+ """Return the number of matching documents."""
247
+
248
+ def latest_per_id(
249
+ self,
250
+ collection: str,
251
+ filter: Filter,
252
+ *,
253
+ id_field: str = "id",
254
+ version_field: str = "version",
255
+ sort: Optional[Sort] = None,
256
+ limit: Optional[int] = None,
257
+ offset: Optional[int] = None,
258
+ ) -> list[dict]:
259
+ """The highest-``version_field`` document for each distinct ``id_field`` — the
260
+ "latest version of each entity" read a list endpoint needs.
261
+
262
+ ``filter`` applies before grouping (it selects among all versions, then reduces
263
+ to the newest per id); ``sort`` / ``offset`` / ``limit`` apply after, to the
264
+ reduced set. Documents missing ``id_field`` are skipped; a missing
265
+ ``version_field`` sorts lowest. Reduces in Python over `query()`, so any
266
+ backend gets it without extra work.
267
+ """
268
+ docs = _reduce_to_latest(self.query(collection, filter), id_field, version_field)
269
+ docs = _apply_sort(docs, sort)
270
+ if offset:
271
+ docs = docs[offset:]
272
+ if limit:
273
+ docs = docs[:limit]
274
+ return docs
275
+
276
+ def count_distinct(self, collection: str, filter: Filter, *, id_field: str = "id") -> int:
277
+ """Number of distinct ``id_field`` values among matching documents.
278
+
279
+ The pagination total that pairs with `latest_per_id()` — a row count would
280
+ over-report, since one entity contributes one row per version.
281
+ """
282
+ keys = set()
283
+ for doc in self.query(collection, filter):
284
+ found, value = _dig(doc, id_field)
285
+ if found:
286
+ keys.add(value)
287
+ return len(keys)
288
+
289
+ @abstractmethod
290
+ def insert(self, collection: str, doc: dict) -> None:
291
+ """Insert one document. Raises DuplicateKeyError on unique violation."""
292
+
293
+ @abstractmethod
294
+ def update(
295
+ self, collection: str, filter: Filter, update: UpdateSpec, upsert: bool = False
296
+ ) -> int:
297
+ """Apply ``update`` to the first match; return matched count (0/1), where 0 is the CAS miss. ``upsert=True`` synthesizes a doc from the filter on no match, and raises DuplicateKeyError if inserting it violates a unique index."""
298
+
299
+ @abstractmethod
300
+ def update_one_and_get(
301
+ self,
302
+ collection: str,
303
+ filter: Filter,
304
+ update: UpdateSpec,
305
+ return_after: bool = True,
306
+ upsert: bool = False,
307
+ ) -> Optional[dict]:
308
+ """Apply ``update`` to the first match; return the doc (post-update if ``return_after`` else pre-update), or None on no match. An upsert raises DuplicateKeyError as ``update`` does."""
309
+
310
+ @abstractmethod
311
+ def replace(
312
+ self, collection: str, filter: Filter, doc: dict, upsert: bool = False
313
+ ) -> int:
314
+ """Replace the first matching document wholesale; return matched count (0/1). An upsert that inserts ``doc`` raises DuplicateKeyError on a unique violation."""
315
+
316
+ @abstractmethod
317
+ def delete(self, collection: str, filter: Filter) -> int:
318
+ """Delete the first matching document; return deleted count (0/1)."""
319
+
320
+ @abstractmethod
321
+ def ensure_index(
322
+ self,
323
+ collection: str,
324
+ fields: list[str],
325
+ unique: bool = False,
326
+ ttl_seconds: Optional[int] = None,
327
+ ) -> None:
328
+ """Register an index over ``fields`` (idempotent); ``unique=True`` is enforced by ``insert`` and upserts via ``DuplicateKeyError``. ``ttl_seconds`` requests server-side expiry off the single indexed datetime field (backends without TTL may ignore it)."""
329
+
330
+ def check_id(self, entity_id: str) -> None:
331
+ """Raise ValueError unless an entity with ``entity_id`` may be written here. No store takes an id
332
+ opening with the reserved ``@`` but the ``@local`` namespace's own, which takes only ``@local`` ids."""
333
+ reject_reserved_id(entity_id)
334
+
335
+
336
+ RESERVED_ID_PREFIX = "@"
337
+
338
+
339
+ def reject_reserved_id(entity_id: object) -> None:
340
+ """Refuse an id claiming the ``@`` prefix, which opens a registry-qualified
341
+ ``@namespace/id``. Only the ``@local`` namespace's store holds such ids, its own.
342
+
343
+ Reserved while agent-env is still private: once third parties have created ids, taking
344
+ the prefix back stops being free.
345
+ """
346
+ if isinstance(entity_id, str) and is_local_id(entity_id):
347
+ raise ValueError(
348
+ f"id {entity_id!r} is an @local id, which only the @local namespace's store holds; "
349
+ "the agent-env CLI writes @local ids there"
350
+ )
351
+ if isinstance(entity_id, str) and entity_id.startswith(RESERVED_ID_PREFIX):
352
+ raise ValueError(
353
+ f"id {entity_id!r} starts with the reserved {RESERVED_ID_PREFIX!r} prefix: that "
354
+ "addresses a registry-qualified name (@namespace/id), so a local id cannot use it"
355
+ )
356
+
357
+
358
+ # Collections of versioned (id, version) entities, which namespace routing places by id. The core
359
+ # ones are known up front, so a read made before their store exists is placed too; every
360
+ # VersionedEntityStore adds its own, a plugin's included, before its first read or write.
361
+ _entity_collections: set[str] = {"a2a_agents", "artifacts", "envs", "evals", "task_steps", "tasks"}
362
+
363
+
364
+ def is_entity_collection(collection: str) -> bool:
365
+ return collection in _entity_collections
366
+
367
+
368
+ class VersionedEntityStore(Generic[T]):
369
+ """The shared ``(id, version)`` versioning logic on top of a DocumentStore."""
370
+
371
+ def __init__(
372
+ self,
373
+ docs: DocumentStore,
374
+ collection: str,
375
+ serialize: Optional[Callable[[T], dict]],
376
+ deserialize: Callable[[dict], T],
377
+ secondary_indexes: Optional[list[list[str]]] = None,
378
+ ) -> None:
379
+ _entity_collections.add(collection)
380
+ self._doc_store = docs
381
+ self._collection = collection
382
+ self._serialize = serialize
383
+ self._deserialize = deserialize
384
+ self._doc_store.ensure_index(collection, ["id", "version"], unique=True)
385
+ for fields in secondary_indexes or []:
386
+ self._doc_store.ensure_index(collection, fields)
387
+
388
+ def get(self, id: str, version: Optional[int] = None) -> Optional[T]:
389
+ if version is not None:
390
+ doc = self._doc_store.find_one(self._collection, Filter.of(id=id, version=version))
391
+ else:
392
+ doc = self._doc_store.find_one(
393
+ self._collection, Filter.of(id=id), sort=Sort.by("version", descending=True)
394
+ )
395
+ return self._deserialize(doc) if doc is not None else None
396
+
397
+ def next_version(self, id: str) -> int:
398
+ """Allocate the version a write to ``id`` would land on.
399
+
400
+ The id is checked here and not only at ``put`` because every artifact
401
+ helper calls this first and then writes remote data — an object to S3, an image to a
402
+ registry — before it has a document to store. Refusing the id at the end would leave
403
+ that data orphaned with no artifact record pointing at it.
404
+ """
405
+ self._doc_store.check_id(id)
406
+ doc = self._doc_store.find_one(
407
+ self._collection, Filter.of(id=id), sort=Sort.by("version", descending=True)
408
+ )
409
+ return (doc["version"] + 1) if doc is not None else 1
410
+
411
+ def put(self, entity: T, max_retries: int = 5) -> int:
412
+ """Serialize and insert the entity under the next free version; return that version."""
413
+ if self._serialize is None:
414
+ raise RuntimeError("VersionedEntityStore was built without a serializer; put() is unsupported")
415
+ doc = self._serialize(entity)
416
+ if not isinstance(doc.get("id"), str):
417
+ raise ValueError(f"an entity in {self._collection!r} needs a string id, got {doc.get('id')!r}")
418
+ self._doc_store.check_id(doc["id"])
419
+ last_error: Optional[DuplicateKeyError] = None
420
+ for _ in range(max_retries):
421
+ version = self.next_version(doc["id"])
422
+ attempt = {**doc, "version": version}
423
+ try:
424
+ self._doc_store.insert(self._collection, attempt)
425
+ return version
426
+ except DuplicateKeyError as e:
427
+ last_error = e
428
+ raise DuplicateKeyError(
429
+ f"Could not assign a version for id={doc.get('id')!r} after {max_retries} retries"
430
+ ) from last_error
431
+
432
+ def query(
433
+ self,
434
+ filter: Filter,
435
+ sort: Optional[Sort] = None,
436
+ limit: Optional[int] = None,
437
+ offset: Optional[int] = None,
438
+ ) -> list[T]:
439
+ return [
440
+ self._deserialize(doc)
441
+ for doc in self._doc_store.query(self._collection, filter, sort, limit, offset)
442
+ ]
443
+
444
+ def count(self, filter: Filter) -> int:
445
+ return self._doc_store.count(self._collection, filter)
446
+
447
+
448
+ class VersionedEntityStoreCache(Generic[T]):
449
+ """The ``VersionedEntityStore`` for whichever backend is current.
450
+
451
+ Building one runs ``ensure_index``, so it is cached rather than rebuilt per call; but one
452
+ built on a previous backend goes on writing there after ``reset_config()`` re-points, so
453
+ the cache is keyed on the backend instead of filled once.
454
+
455
+ Lock-free, and deliberately so: constructing the view does I/O, which is not something to
456
+ hold a lock across. The backend and the view built for it are one tuple rebound in a
457
+ single assignment, so they cannot be seen apart; and ``for_store`` returns the view it
458
+ built rather than re-reading the field, so a builder that loses the race still hands its
459
+ caller a view on the backend that caller asked for. The loser's only cost is a redundant
460
+ ``ensure_index``, which is idempotent.
461
+ """
462
+
463
+ def __init__(
464
+ self,
465
+ collection: str,
466
+ serialize: Optional[Callable[[T], dict]],
467
+ deserialize: Callable[[dict], T],
468
+ secondary_indexes: Optional[list[list[str]]] = None,
469
+ ) -> None:
470
+ self._collection = collection
471
+ self._serialize = serialize
472
+ self._deserialize = deserialize
473
+ self._secondary_indexes = secondary_indexes
474
+ self._cached: Optional[tuple[DocumentStore, VersionedEntityStore[T]]] = None
475
+
476
+ def for_store(self, store: DocumentStore) -> VersionedEntityStore[T]:
477
+ cached = self._cached
478
+ if cached is not None and cached[0] is store:
479
+ return cached[1]
480
+ view: VersionedEntityStore[T] = VersionedEntityStore(
481
+ store, self._collection, self._serialize, self._deserialize,
482
+ secondary_indexes=self._secondary_indexes,
483
+ )
484
+ self._cached = (store, view)
485
+ return view
486
+
487
+
488
+ def rev_precondition(doc: dict, counter_field: str) -> Predicate:
489
+ """CAS predicate for ``doc``'s current ``counter_field``; ``Exists(False)`` when absent so the first write migrates a pre-counter doc rather than dead-looping on ``Eq(0)``."""
490
+ current = doc.get(counter_field)
491
+ return Eq(current) if current is not None else Exists(present=False)
492
+
493
+
494
+ def compare_and_swap(
495
+ docs: DocumentStore,
496
+ collection: str,
497
+ key: Filter,
498
+ mutate: Callable[[dict], Optional[UpdateSpec]],
499
+ *,
500
+ counter_field: str,
501
+ max_attempts: int = 1000,
502
+ ) -> Optional[dict]:
503
+ """Read the doc matched by ``key``, apply ``mutate`` under an optimistic CAS on ``counter_field``, retrying on contention; return the post-update doc (or None if ``key`` misses or ``mutate`` returns None). ``mutate`` must not write ``counter_field`` — the increment is managed here."""
504
+ for _ in range(max_attempts):
505
+ doc = docs.find_one(collection, key)
506
+ if doc is None:
507
+ return None
508
+ spec = mutate(doc)
509
+ if spec is None:
510
+ return None
511
+ spec.inc = {**spec.inc, counter_field: 1}
512
+ result = docs.update_one_and_get(
513
+ collection, key.where(counter_field, rev_precondition(doc, counter_field)), spec
514
+ )
515
+ if result is not None:
516
+ return result
517
+ raise RuntimeError(
518
+ f"compare_and_swap: did not converge for collection={collection} key={key.conditions}"
519
+ )