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,242 @@
1
+ """Firestore with MongoDB compatibility as a DocumentStore (the ``gcp`` extra)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import threading
7
+ import time
8
+ import uuid
9
+ from collections.abc import Callable
10
+ from typing import Optional, TypeVar
11
+
12
+ import google.auth
13
+ import pymongo
14
+ from google.api_core.exceptions import RetryError
15
+ from google.auth.credentials import Credentials
16
+ from google.auth.exceptions import DefaultCredentialsError, TransportError
17
+ from pymongo import MongoClient, ReturnDocument
18
+ from pymongo.database import Database
19
+ from pymongo.auth_oidc import OIDCCallback, OIDCCallbackContext, OIDCCallbackResult
20
+ from pymongo.errors import PyMongoError
21
+
22
+ from agent_env.config.errors import ConfigError
23
+ from agent_env.store import _google
24
+ from agent_env.store.document_store.document_store import DuplicateKeyError, Filter, Sort, UpdateSpec
25
+ from agent_env.store.document_store.mongo_document_store import (
26
+ MongoDocumentStore,
27
+ _to_mongo_filter,
28
+ _strip_id,
29
+ _to_mongo_update,
30
+ _unique_violations,
31
+ )
32
+
33
+ logger = logging.getLogger(__name__)
34
+
35
+ T = TypeVar("T")
36
+
37
+ #: Stamped with a fresh value by every update and replace, and stripped from every read.
38
+ WRITE_STAMP_FIELD = "_agentenv_write"
39
+
40
+ # Firestore's MongoDB endpoint listens on the TLS port only.
41
+ _PORT = 443
42
+
43
+ # The client's timeouts, as MongoDocumentStore's; index builds get their own below.
44
+ _SERVER_SELECTION_TIMEOUT_MS = 30000
45
+ _CONNECT_TIMEOUT_MS = 15000
46
+ _SOCKET_TIMEOUT_MS = 30000
47
+
48
+ # createIndex answers only once the index is built, which takes a minute or more even on an
49
+ # empty collection; the client's 30 s socket timeout would end every first build.
50
+ _INDEX_BUILD_SECONDS = 600
51
+
52
+ # A transaction that loses to another writer on the same document is refused (code 112) and
53
+ # must be retried by the client.
54
+ _WRITE_CONFLICT = 112
55
+ _TRANSACTION_ATTEMPTS = 20
56
+ _TRANSACTION_BACKOFF_SECONDS = 0.02
57
+
58
+
59
+ # Index builds this process has finished, and a lock per index being built, shared by every store
60
+ # on one backend: Firestore answers a createIndex re-issued during a build before the index
61
+ # enforces anything, so only the first caller may issue it.
62
+ _built_indexes: set[tuple] = set()
63
+ _index_locks: dict[tuple, threading.Lock] = {}
64
+ _index_locks_guard = threading.Lock()
65
+
66
+
67
+ def _strip(doc: Optional[dict]) -> Optional[dict]:
68
+ if doc is not None:
69
+ doc.pop(WRITE_STAMP_FIELD, None)
70
+ return doc
71
+
72
+
73
+ class _AccessTokenCallback(OIDCCallback):
74
+ """MONGODB-OIDC over Application Default Credentials: Firestore takes a Google OAuth2
75
+ access token, so this works wherever ADC does, not only on Google Cloud."""
76
+
77
+ def __init__(self, credentials: Credentials) -> None:
78
+ self._credentials = credentials
79
+ self._request = _google.pooled_request()
80
+ self._lock = threading.Lock()
81
+
82
+ def fetch(self, context: OIDCCallbackContext) -> OIDCCallbackResult:
83
+ with self._lock:
84
+ if not self._credentials.valid:
85
+ try:
86
+ _google.RETRY(self._credentials.refresh)(self._request)
87
+ except RetryError as e:
88
+ raise TransportError(f"Google issued no access token within the retry window: {e.cause}") from e
89
+ return OIDCCallbackResult(access_token=self._credentials.token)
90
+
91
+
92
+ class FirestoreMongoDocumentStore(MongoDocumentStore):
93
+ """``MongoDocumentStore`` on a Firestore database with MongoDB compatibility.
94
+
95
+ Firestore takes the MongoDB wire protocol, but a guarded write that loses a race to
96
+ another writer on the same document is reported as matched: ``update_one`` counts it
97
+ and ``find_one_and_update`` hands back the winner's document. So every update and
98
+ replace here stamps ``WRITE_STAMP_FIELD`` with a fresh value, and counts as applied only
99
+ when it modified the document or returned its own stamp. A pre-image read runs in a
100
+ transaction instead, since a pre-image cannot carry the stamp. An upsert that loses an
101
+ insert race is retried once, as MongoDB's server does for itself.
102
+
103
+ Raw pymongo access to the same collections (``database``, ``mongo_collection``,
104
+ ``Config.db``) bypasses all of this: readers see the stamp field, and a raw guarded write
105
+ that loses a race is still reported as matched.
106
+ """
107
+
108
+ def __init__(self, database: Database, *, backend: Optional[str] = None) -> None:
109
+ """``backend`` names the database, so that stores on it share their index builds;
110
+ a store without one coordinates only its own callers."""
111
+ super().__init__(database)
112
+ self._backend = backend or uuid.uuid4().hex
113
+
114
+ @classmethod
115
+ def from_config(cls, *, host: str, database: str) -> FirestoreMongoDocumentStore:
116
+ """Connect to the database at ``host`` (``<uid>.<location>.firestore.goog``) as the
117
+ Application Default Credentials' identity, and ping it."""
118
+ try:
119
+ credentials, _ = google.auth.default(scopes=_google.SCOPES)
120
+ except (DefaultCredentialsError, OSError) as e:
121
+ raise ConfigError(f"No Google credentials for Firestore database {database!r}: {e}") from e
122
+ client = MongoClient(
123
+ f"mongodb://{host}:{_PORT}/{database}",
124
+ loadBalanced=True,
125
+ tls=True,
126
+ authMechanism="MONGODB-OIDC",
127
+ authMechanismProperties={"OIDC_CALLBACK": _AccessTokenCallback(credentials)},
128
+ serverSelectionTimeoutMS=_SERVER_SELECTION_TIMEOUT_MS,
129
+ connectTimeoutMS=_CONNECT_TIMEOUT_MS,
130
+ socketTimeoutMS=_SOCKET_TIMEOUT_MS,
131
+ retryReads=True,
132
+ retryWrites=False, # Firestore rejects retryable writes' transaction numbers
133
+ )
134
+ try:
135
+ client.admin.command("ping")
136
+ except Exception as e:
137
+ raise ConnectionError(f"Failed to connect to Firestore database {database!r}: {e}") from e
138
+ logger.info("Connected to Firestore database: %s", database)
139
+ return cls(client[database], backend=f"{host}/{database}")
140
+
141
+ def find_one(self, collection: str, filter: Filter, sort: Optional[Sort] = None) -> Optional[dict]:
142
+ return _strip(super().find_one(collection, filter, sort))
143
+
144
+ def query(
145
+ self,
146
+ collection: str,
147
+ filter: Filter,
148
+ sort: Optional[Sort] = None,
149
+ limit: Optional[int] = None,
150
+ offset: Optional[int] = None,
151
+ ) -> list[dict]:
152
+ return [_strip(doc) for doc in super().query(collection, filter, sort, limit, offset)]
153
+
154
+ def update(self, collection: str, filter: Filter, update: UpdateSpec, upsert: bool = False) -> int:
155
+ spec, _ = self._stamped(update)
156
+ result = self._upserting(
157
+ lambda: self._c(collection).update_one(_to_mongo_filter(filter), spec, upsert=upsert), upsert
158
+ )
159
+ return 1 if result.upserted_id is not None else result.modified_count
160
+
161
+ def update_one_and_get(
162
+ self,
163
+ collection: str,
164
+ filter: Filter,
165
+ update: UpdateSpec,
166
+ return_after: bool = True,
167
+ upsert: bool = False,
168
+ ) -> Optional[dict]:
169
+ if not return_after:
170
+ return self._update_returning_pre_image(collection, filter, update, upsert)
171
+ spec, stamp = self._stamped(update)
172
+ doc = self._upserting(
173
+ lambda: self._c(collection).find_one_and_update(
174
+ _to_mongo_filter(filter), spec, return_document=ReturnDocument.AFTER, upsert=upsert
175
+ ),
176
+ upsert,
177
+ )
178
+ if doc is None or doc.get(WRITE_STAMP_FIELD) != stamp:
179
+ return None
180
+ return _strip(_strip_id(doc))
181
+
182
+ def replace(self, collection: str, filter: Filter, doc: dict, upsert: bool = False) -> int:
183
+ body = {**doc, WRITE_STAMP_FIELD: uuid.uuid4().hex}
184
+ result = self._upserting(
185
+ lambda: self._c(collection).replace_one(_to_mongo_filter(filter), body, upsert=upsert), upsert
186
+ )
187
+ return 1 if result.upserted_id is not None else result.modified_count
188
+
189
+ def ensure_index(
190
+ self,
191
+ collection: str,
192
+ fields: list[str],
193
+ unique: bool = False,
194
+ ttl_seconds: Optional[int] = None,
195
+ ) -> None:
196
+ key = (self._backend, collection, tuple(fields), unique, ttl_seconds)
197
+ with _index_locks_guard:
198
+ lock = _index_locks.setdefault(key, threading.Lock())
199
+ with lock:
200
+ if key in _built_indexes:
201
+ return
202
+ with pymongo.timeout(_INDEX_BUILD_SECONDS):
203
+ super().ensure_index(collection, fields, unique=unique, ttl_seconds=ttl_seconds)
204
+ _built_indexes.add(key)
205
+
206
+ def _stamped(self, update: UpdateSpec) -> tuple[dict, str]:
207
+ stamp = uuid.uuid4().hex
208
+ spec = _to_mongo_update(update)
209
+ spec.setdefault("$set", {})[WRITE_STAMP_FIELD] = stamp
210
+ return spec, stamp
211
+
212
+ def _upserting(self, write: Callable[[], T], upsert: bool) -> T:
213
+ try:
214
+ with _unique_violations():
215
+ return write()
216
+ except DuplicateKeyError:
217
+ if not upsert:
218
+ raise
219
+ # Two upserts both missed and the other inserted first: this one now matches it.
220
+ with _unique_violations():
221
+ return write()
222
+
223
+ def _update_returning_pre_image(
224
+ self, collection: str, filter: Filter, update: UpdateSpec, upsert: bool
225
+ ) -> Optional[dict]:
226
+ mongo_filter, spec = _to_mongo_filter(filter), self._stamped(update)[0]
227
+ coll = self._c(collection)
228
+ for attempt in range(_TRANSACTION_ATTEMPTS):
229
+ try:
230
+ with _unique_violations(), self._db.client.start_session() as session:
231
+ with session.start_transaction():
232
+ before = coll.find_one(mongo_filter, session=session)
233
+ if before is not None:
234
+ coll.update_one({"_id": before["_id"]}, spec, session=session)
235
+ elif upsert:
236
+ coll.update_one(mongo_filter, spec, upsert=True, session=session)
237
+ return _strip(_strip_id(before))
238
+ except PyMongoError as e:
239
+ if getattr(e, "code", None) != _WRITE_CONFLICT and not e.has_error_label("TransientTransactionError"):
240
+ raise
241
+ time.sleep(_TRANSACTION_BACKOFF_SECONDS * (attempt + 1))
242
+ raise RuntimeError(f"a pre-image update on {collection!r} lost {_TRANSACTION_ATTEMPTS} write conflicts in a row")
@@ -0,0 +1,259 @@
1
+ """MongoDB implementation of the DocumentStore interface.
2
+
3
+ Translates the backend-agnostic ``Filter`` / ``UpdateSpec`` / ``Sort`` into
4
+ pymongo queries and updates. This is the concrete home for the pymongo idioms
5
+ currently spread across the individual ``*/store.py`` modules.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import logging
11
+ from collections.abc import Iterator
12
+ from contextlib import contextmanager
13
+ from typing import Optional
14
+
15
+ from pymongo import ASCENDING, DESCENDING, MongoClient, ReturnDocument
16
+ from pymongo.collection import Collection
17
+ from pymongo.database import Database
18
+ from pymongo.errors import DuplicateKeyError as PyMongoDuplicateKeyError
19
+ from pymongo.errors import OperationFailure
20
+
21
+ from agent_env.store.document_store.document_store import (
22
+ AbsentOrNull,
23
+ DocumentStore,
24
+ DuplicateKeyError,
25
+ Eq,
26
+ Exists,
27
+ Filter,
28
+ Gte,
29
+ In,
30
+ Lte,
31
+ LteOrAbsent,
32
+ Ne,
33
+ Predicate,
34
+ Sort,
35
+ UpdateSpec,
36
+ )
37
+
38
+ logger = logging.getLogger(__name__)
39
+
40
+
41
+ def _field_cond(mongo: dict, field: str) -> dict:
42
+ if field in mongo and not isinstance(mongo[field], dict):
43
+ raise ValueError(f"filter fuses an operator predicate with Eq on field {field!r}; not supported")
44
+ return mongo.setdefault(field, {})
45
+
46
+
47
+ def _apply_predicate(mongo: dict, field: str, pred: Predicate) -> None:
48
+ if isinstance(pred, Eq):
49
+ if isinstance(mongo.get(field), dict):
50
+ raise ValueError(f"filter fuses Eq with an operator predicate on field {field!r}; not supported")
51
+ mongo[field] = pred.value
52
+ elif isinstance(pred, Ne):
53
+ cond = _field_cond(mongo, field)
54
+ cond["$ne"] = pred.value
55
+ cond["$exists"] = True
56
+ elif isinstance(pred, Gte):
57
+ _field_cond(mongo, field)["$gte"] = pred.value
58
+ elif isinstance(pred, Lte):
59
+ _field_cond(mongo, field)["$lte"] = pred.value
60
+ elif isinstance(pred, In):
61
+ _field_cond(mongo, field)["$in"] = list(pred.values)
62
+ elif isinstance(pred, Exists):
63
+ _field_cond(mongo, field)["$exists"] = pred.present
64
+ elif isinstance(pred, LteOrAbsent):
65
+ mongo.setdefault("$and", []).append({"$or": [
66
+ {field: {"$exists": False}},
67
+ {field: None},
68
+ {field: {"$lte": pred.value}},
69
+ ]})
70
+ elif isinstance(pred, AbsentOrNull):
71
+ mongo.setdefault("$and", []).append({"$or": [
72
+ {field: {"$exists": False}},
73
+ {field: None},
74
+ ]})
75
+ else:
76
+ raise TypeError(f"Unsupported predicate: {pred!r}")
77
+
78
+
79
+ def _to_mongo_filter(filter: Filter) -> dict:
80
+ mongo: dict = {}
81
+ for field, predicates in filter.conditions.items():
82
+ for pred in predicates:
83
+ _apply_predicate(mongo, field, pred)
84
+ return mongo
85
+
86
+
87
+ def _to_mongo_sort(sort: Optional[Sort]) -> Optional[list[tuple[str, int]]]:
88
+ if sort is None or not sort.keys:
89
+ return None
90
+ return [(k.field, DESCENDING if k.descending else ASCENDING) for k in sort.keys]
91
+
92
+
93
+ def _to_mongo_update(update: UpdateSpec) -> dict:
94
+ update.validate()
95
+ mongo: dict = {}
96
+ if update.set:
97
+ mongo["$set"] = dict(update.set)
98
+ if update.unset:
99
+ mongo["$unset"] = {path: "" for path in update.unset}
100
+ if update.inc:
101
+ mongo["$inc"] = dict(update.inc)
102
+ if update.add_to_set:
103
+ mongo["$addToSet"] = {p: {"$each": list(v)} for p, v in update.add_to_set.items()}
104
+ if update.push:
105
+ mongo["$push"] = {p: {"$each": list(v)} for p, v in update.push.items()}
106
+ return mongo
107
+
108
+
109
+ @contextmanager
110
+ def _unique_violations() -> Iterator[None]:
111
+ """pymongo's duplicate-key error, as the store's own. An upsert can raise it as well as an
112
+ insert: two concurrent upserts both miss, and the second one's insert collides."""
113
+ try:
114
+ yield
115
+ except PyMongoDuplicateKeyError as e:
116
+ raise DuplicateKeyError(str(e)) from e
117
+
118
+
119
+ def _strip_id(doc: Optional[dict]) -> Optional[dict]:
120
+ if doc is not None:
121
+ doc.pop("_id", None)
122
+ return doc
123
+
124
+
125
+ class MongoDocumentStore(DocumentStore):
126
+ """DocumentStore backed by a pymongo ``Database`` (injected, config-free)."""
127
+
128
+ def __init__(self, database: Database) -> None:
129
+ self._db = database
130
+
131
+ @classmethod
132
+ def from_config(cls, *, uri: str, database: str) -> MongoDocumentStore:
133
+ """Build a pinged, retry-configured MongoClient for ``uri`` and wrap ``database``."""
134
+ client = MongoClient(
135
+ uri,
136
+ serverSelectionTimeoutMS=30000,
137
+ connectTimeoutMS=15000,
138
+ socketTimeoutMS=30000,
139
+ retryReads=True,
140
+ retryWrites=True,
141
+ )
142
+ db = client[database]
143
+ try:
144
+ client.admin.command("ping")
145
+ except Exception as e:
146
+ raise ConnectionError(f"Failed to connect to MongoDB: {e}") from e
147
+ logger.info("Connected to MongoDB database: %s", database)
148
+ return cls(db)
149
+
150
+ @property
151
+ def database(self) -> Database:
152
+ """The underlying pymongo Database, shared with raw-pymongo callers (Config.db)."""
153
+ return self._db
154
+
155
+ def _c(self, collection: str):
156
+ return self._db[collection]
157
+
158
+ def mongo_collection(self, collection: str) -> Collection:
159
+ """Raw pymongo Collection escape hatch for consumers (a hosting service, say) that
160
+ need aggregation pipelines the abstract DocumentStore API doesn't expose."""
161
+ return self._c(collection)
162
+
163
+ def find_one(
164
+ self, collection: str, filter: Filter, sort: Optional[Sort] = None
165
+ ) -> Optional[dict]:
166
+ doc = self._c(collection).find_one(
167
+ _to_mongo_filter(filter), sort=_to_mongo_sort(sort)
168
+ )
169
+ return _strip_id(doc)
170
+
171
+ def query(
172
+ self,
173
+ collection: str,
174
+ filter: Filter,
175
+ sort: Optional[Sort] = None,
176
+ limit: Optional[int] = None,
177
+ offset: Optional[int] = None,
178
+ ) -> list[dict]:
179
+ cursor = self._c(collection).find(_to_mongo_filter(filter))
180
+ mongo_sort = _to_mongo_sort(sort)
181
+ if mongo_sort:
182
+ cursor = cursor.sort(mongo_sort)
183
+ if offset:
184
+ cursor = cursor.skip(offset)
185
+ if limit:
186
+ cursor = cursor.limit(limit)
187
+ return [_strip_id(doc) for doc in cursor]
188
+
189
+ def count(self, collection: str, filter: Filter) -> int:
190
+ return self._c(collection).count_documents(_to_mongo_filter(filter))
191
+
192
+ def insert(self, collection: str, doc: dict) -> None:
193
+ with _unique_violations():
194
+ self._c(collection).insert_one(dict(doc))
195
+
196
+ def update(
197
+ self, collection: str, filter: Filter, update: UpdateSpec, upsert: bool = False
198
+ ) -> int:
199
+ with _unique_violations():
200
+ result = self._c(collection).update_one(
201
+ _to_mongo_filter(filter), _to_mongo_update(update), upsert=upsert
202
+ )
203
+ if result.upserted_id is not None:
204
+ return 1
205
+ return result.matched_count
206
+
207
+ def update_one_and_get(
208
+ self,
209
+ collection: str,
210
+ filter: Filter,
211
+ update: UpdateSpec,
212
+ return_after: bool = True,
213
+ upsert: bool = False,
214
+ ) -> Optional[dict]:
215
+ with _unique_violations():
216
+ doc = self._c(collection).find_one_and_update(
217
+ _to_mongo_filter(filter),
218
+ _to_mongo_update(update),
219
+ return_document=ReturnDocument.AFTER if return_after else ReturnDocument.BEFORE,
220
+ upsert=upsert,
221
+ )
222
+ return _strip_id(doc)
223
+
224
+ def replace(
225
+ self, collection: str, filter: Filter, doc: dict, upsert: bool = False
226
+ ) -> int:
227
+ with _unique_violations():
228
+ result = self._c(collection).replace_one(
229
+ _to_mongo_filter(filter), dict(doc), upsert=upsert
230
+ )
231
+ if result.upserted_id is not None:
232
+ return 1
233
+ return result.matched_count
234
+
235
+ def delete(self, collection: str, filter: Filter) -> int:
236
+ return self._c(collection).delete_one(_to_mongo_filter(filter)).deleted_count
237
+
238
+ def ensure_index(
239
+ self,
240
+ collection: str,
241
+ fields: list[str],
242
+ unique: bool = False,
243
+ ttl_seconds: Optional[int] = None,
244
+ ) -> None:
245
+ kwargs: dict = {}
246
+ if ttl_seconds is not None:
247
+ kwargs["expireAfterSeconds"] = ttl_seconds
248
+ try:
249
+ self._c(collection).create_index(
250
+ [(f, ASCENDING) for f in fields],
251
+ unique=unique,
252
+ name="_".join(fields) + ("_unique" if unique else "_index"),
253
+ **kwargs,
254
+ )
255
+ except OperationFailure as e:
256
+ # 85=IndexOptionsConflict, 86=IndexKeySpecsConflict: an equivalent index
257
+ # already exists under a different name/spec (pre-refactor). Tolerate it.
258
+ if e.code not in (85, 86):
259
+ raise