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,306 @@
1
+ """DynamoDB DocumentStore: one on-demand table per collection, one JSON blob per item. The sort key's
2
+ name records the collection's unique index (``sk`` when it has none), so the table's own key schema fixes
3
+ how every process keys items. Filters run in Python (``evaluation``); writes are conditional on the blob read."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import json
8
+ import logging
9
+ import random
10
+ import time
11
+ import uuid
12
+ from datetime import datetime
13
+ from typing import Any, Callable, Optional
14
+
15
+ import boto3
16
+
17
+ from agent_env.store.base import ConcurrentModificationError
18
+ from agent_env.store.document_store import evaluation
19
+ from agent_env.store.document_store.document_store import (
20
+ DocumentStore,
21
+ DuplicateKeyError,
22
+ Eq,
23
+ Filter,
24
+ Sort,
25
+ UpdateSpec,
26
+ )
27
+
28
+ logger = logging.getLogger(__name__)
29
+
30
+ _CAS_ATTEMPTS = 64
31
+ _CAS_BACKOFF_SECONDS = 0.005
32
+ _CAS_MAX_BACKOFF_SECONDS = 0.25
33
+ _TABLE_POLL_SECONDS = 1
34
+ _TABLE_POLL_ATTEMPTS = 120
35
+ _UNINDEXED_SORT_KEY = "sk"
36
+
37
+
38
+ def _json_default(o):
39
+ if isinstance(o, datetime):
40
+ return o.isoformat()
41
+ raise TypeError(f"Object of type {type(o).__name__} is not JSON-serializable")
42
+
43
+
44
+ def _dumps(value) -> str:
45
+ return json.dumps(value, default=_json_default)
46
+
47
+
48
+ def _unchanged(blob: str) -> dict:
49
+ return {
50
+ "ConditionExpression": "#d = :old",
51
+ "ExpressionAttributeNames": {"#d": "doc"},
52
+ "ExpressionAttributeValues": {":old": {"S": blob}},
53
+ }
54
+
55
+
56
+ class DynamoDbDocumentStore(DocumentStore):
57
+ """DocumentStore backed by DynamoDB tables named ``{table_prefix}{collection}``."""
58
+
59
+ def __init__(self, table_prefix: str = "", region: Optional[str] = None) -> None:
60
+ self._table_prefix = table_prefix
61
+ self._client = boto3.client("dynamodb", region_name=region)
62
+ self._sort_keys: dict[str, str] = {}
63
+
64
+ def _table_name(self, collection: str) -> str:
65
+ return f"{self._table_prefix}{collection}"
66
+
67
+ def _key_fields(self, collection: str) -> Optional[list[str]]:
68
+ sort_key = self._sort_keys[collection]
69
+ return None if sort_key == _UNINDEXED_SORT_KEY else json.loads(sort_key)
70
+
71
+ def _wait(self, name: str) -> None:
72
+ self._client.get_waiter("table_exists").wait(
73
+ TableName=name, WaiterConfig={"Delay": _TABLE_POLL_SECONDS, "MaxAttempts": _TABLE_POLL_ATTEMPTS}
74
+ )
75
+
76
+ def _table_exists(self, collection: str) -> bool:
77
+ """Whether the table exists; the first time, waits out its creation and learns its sort key."""
78
+ if collection in self._sort_keys:
79
+ return True
80
+ name = self._table_name(collection)
81
+ try:
82
+ table = self._client.describe_table(TableName=name)["Table"]
83
+ except self._client.exceptions.ResourceNotFoundException:
84
+ return False
85
+ if table["TableStatus"] == "CREATING":
86
+ self._wait(name)
87
+ self._sort_keys[collection] = next(k["AttributeName"] for k in table["KeySchema"] if k["KeyType"] == "RANGE")
88
+ return True
89
+
90
+ def _table(self, collection: str, key_fields: Optional[list[str]] = None) -> str:
91
+ """The collection's table name, creating the table on first use with a sort key named for ``key_fields``."""
92
+ name = self._table_name(collection)
93
+ if not self._table_exists(collection):
94
+ sort_key = json.dumps(key_fields) if key_fields else _UNINDEXED_SORT_KEY
95
+ try:
96
+ self._client.create_table(
97
+ TableName=name,
98
+ KeySchema=[
99
+ {"AttributeName": "pk", "KeyType": "HASH"},
100
+ {"AttributeName": sort_key, "KeyType": "RANGE"},
101
+ ],
102
+ AttributeDefinitions=[
103
+ {"AttributeName": "pk", "AttributeType": "S"},
104
+ {"AttributeName": sort_key, "AttributeType": "S"},
105
+ ],
106
+ BillingMode="PAY_PER_REQUEST",
107
+ )
108
+ except self._client.exceptions.ResourceInUseException:
109
+ pass
110
+ self._wait(name)
111
+ self._table_exists(collection)
112
+ return name
113
+
114
+ def _key(self, collection: str, doc: dict, current: Optional[dict] = None) -> dict:
115
+ """``doc``'s item key: its unique-index values, else ``current`` or a generated one."""
116
+ sort_key = self._sort_keys[collection]
117
+ fields = self._key_fields(collection)
118
+ if fields is None:
119
+ return current or {"pk": {"S": uuid.uuid4().hex}, sort_key: {"S": "[]"}}
120
+ values = [doc.get(f) for f in fields]
121
+ return {"pk": {"S": _dumps(values[0])}, sort_key: {"S": _dumps(values[1:])}}
122
+
123
+ def _candidates(self, collection: str, filter: Filter) -> list[tuple[dict, str, dict]]:
124
+ """``(key, stored blob, decoded doc)`` for every item that might match ``filter``: a GetItem when it
125
+ pins every key field, a Query when it pins the first, else a Scan."""
126
+ if not self._table_exists(collection):
127
+ return []
128
+ sort_key = self._sort_keys[collection]
129
+ fields = self._key_fields(collection) or []
130
+ pinned = {
131
+ f: eq[0] for f in fields if (eq := [p.value for p in filter.conditions.get(f, []) if isinstance(p, Eq)])
132
+ }
133
+ kwargs: dict = {"TableName": self._table_name(collection), "ConsistentRead": True}
134
+ if fields and len(pinned) == len(fields):
135
+ item = self._client.get_item(Key=self._key(collection, pinned), **kwargs).get("Item")
136
+ items = [item] if item else []
137
+ else:
138
+ if fields and fields[0] in pinned:
139
+ kwargs["KeyConditionExpression"] = "pk = :pk"
140
+ kwargs["ExpressionAttributeValues"] = {":pk": {"S": _dumps(pinned[fields[0]])}}
141
+ op = "query" if "KeyConditionExpression" in kwargs else "scan"
142
+ items = (it for page in self._client.get_paginator(op).paginate(**kwargs) for it in page["Items"])
143
+ return [({"pk": it["pk"], sort_key: it[sort_key]}, it["doc"]["S"], json.loads(it["doc"]["S"])) for it in items]
144
+
145
+ def _matching(self, collection: str, filter: Filter) -> list[dict]:
146
+ return [doc for _, _, doc in self._candidates(collection, filter) if evaluation.matches(doc, filter)]
147
+
148
+ def _put_new(self, collection: str, doc: dict) -> None:
149
+ name = self._table(collection)
150
+ key = self._key(collection, doc)
151
+ try:
152
+ self._client.put_item(
153
+ TableName=name,
154
+ Item={**key, "doc": {"S": _dumps(doc)}},
155
+ ConditionExpression="attribute_not_exists(pk)",
156
+ )
157
+ except self._client.exceptions.ConditionalCheckFailedException as e:
158
+ raise DuplicateKeyError(f"duplicate key in {collection!r}: {[v['S'] for v in key.values()]}") from e
159
+
160
+ def _store(self, collection: str, key: dict, blob: str, doc: dict) -> None:
161
+ """Write ``doc`` over the item read as ``(key, blob)``."""
162
+ if self._key(collection, doc, current=key) != key:
163
+ raise NotImplementedError(
164
+ f"DynamoDbDocumentStore cannot change a unique-index field of a stored {collection!r} document"
165
+ )
166
+ self._client.put_item(
167
+ TableName=self._table_name(collection), Item={**key, "doc": {"S": _dumps(doc)}}, **_unchanged(blob)
168
+ )
169
+
170
+ def _cas(self, collection: str, filter: Filter, write: Callable[[dict, str, dict], Any]) -> Any:
171
+ """``write(key, blob, doc)`` on the first match, re-read after a jittered backoff when a concurrent
172
+ writer changed it first; None when nothing matches. A conflict means another write landed."""
173
+ for attempt in range(_CAS_ATTEMPTS):
174
+ match = next(
175
+ (c for c in self._candidates(collection, filter) if evaluation.matches(c[2], filter)), None
176
+ )
177
+ if match is None:
178
+ return None
179
+ try:
180
+ return write(*match)
181
+ except self._client.exceptions.ConditionalCheckFailedException:
182
+ time.sleep(random.uniform(0, min(_CAS_MAX_BACKOFF_SECONDS, _CAS_BACKOFF_SECONDS * 2**attempt)))
183
+ raise ConcurrentModificationError(
184
+ f"{collection!r}: the matched document changed on each of {_CAS_ATTEMPTS} attempts"
185
+ )
186
+
187
+ def _insert_or_write(self, collection: str, filter: Filter, doc: dict, write: Callable[[dict, str, dict], Any]) -> Any:
188
+ """Insert ``doc``, or, when a concurrent upsert inserted it first, ``write`` the winner; None when
189
+ inserted. A key still holding a document ``filter`` doesn't match stays a ``DuplicateKeyError``;
190
+ a winner deleted before the re-read frees the key, so the insert runs again."""
191
+ for _ in range(_CAS_ATTEMPTS):
192
+ try:
193
+ self._put_new(collection, doc)
194
+ return None
195
+ except DuplicateKeyError:
196
+ result = self._cas(collection, filter, write)
197
+ if result is not None:
198
+ return result
199
+ held = self._client.get_item(
200
+ TableName=self._table_name(collection), Key=self._key(collection, doc), ConsistentRead=True
201
+ )
202
+ if "Item" in held:
203
+ raise
204
+ raise ConcurrentModificationError(
205
+ f"{collection!r}: the upserted key was taken and freed on each of {_CAS_ATTEMPTS} attempts"
206
+ )
207
+
208
+ def find_one(self, collection: str, filter: Filter, sort: Optional[Sort] = None) -> Optional[dict]:
209
+ docs = evaluation.sort_docs(self._matching(collection, filter), sort)
210
+ return docs[0] if docs else None
211
+
212
+ def query(
213
+ self,
214
+ collection: str,
215
+ filter: Filter,
216
+ sort: Optional[Sort] = None,
217
+ limit: Optional[int] = None,
218
+ offset: Optional[int] = None,
219
+ ) -> list[dict]:
220
+ docs = evaluation.sort_docs(self._matching(collection, filter), sort)
221
+ if offset:
222
+ docs = docs[offset:]
223
+ if limit:
224
+ docs = docs[:limit]
225
+ return docs
226
+
227
+ def count(self, collection: str, filter: Filter) -> int:
228
+ return len(self._matching(collection, filter))
229
+
230
+ def insert(self, collection: str, doc: dict) -> None:
231
+ self._put_new(collection, dict(doc))
232
+
233
+ def update(self, collection: str, filter: Filter, update: UpdateSpec, upsert: bool = False) -> int:
234
+ return int(self.update_one_and_get(collection, filter, update, return_after=True, upsert=upsert) is not None)
235
+
236
+ def update_one_and_get(
237
+ self,
238
+ collection: str,
239
+ filter: Filter,
240
+ update: UpdateSpec,
241
+ return_after: bool = True,
242
+ upsert: bool = False,
243
+ ) -> Optional[dict]:
244
+ update.validate()
245
+
246
+ def write(key: dict, blob: str, doc: dict) -> dict:
247
+ evaluation.apply_update(doc, update)
248
+ self._store(collection, key, blob, doc)
249
+ return doc if return_after else json.loads(blob)
250
+
251
+ result = self._cas(collection, filter, write)
252
+ if result is not None:
253
+ return result
254
+ if upsert:
255
+ new_doc = evaluation.synthesize(filter, update)
256
+ raced = self._insert_or_write(collection, filter, new_doc, write)
257
+ if raced is not None:
258
+ return raced
259
+ return new_doc if return_after else None
260
+ return None
261
+
262
+ def replace(self, collection: str, filter: Filter, doc: dict, upsert: bool = False) -> int:
263
+ new_doc = dict(doc)
264
+
265
+ def write(key: dict, blob: str, _old: dict) -> int:
266
+ self._store(collection, key, blob, new_doc)
267
+ return 1
268
+
269
+ if self._cas(collection, filter, write):
270
+ return 1
271
+ if upsert:
272
+ self._insert_or_write(collection, filter, new_doc, write)
273
+ return 1
274
+ return 0
275
+
276
+ def delete(self, collection: str, filter: Filter) -> int:
277
+ def write(key: dict, blob: str, _doc: dict) -> int:
278
+ self._client.delete_item(TableName=self._table_name(collection), Key=key, **_unchanged(blob))
279
+ return 1
280
+
281
+ return self._cas(collection, filter, write) or 0
282
+
283
+ def ensure_index(
284
+ self,
285
+ collection: str,
286
+ fields: list[str],
287
+ unique: bool = False,
288
+ ttl_seconds: Optional[int] = None,
289
+ ) -> None:
290
+ """A unique index becomes the collection's item key; other indexes are not built."""
291
+ if ttl_seconds is not None:
292
+ logger.warning("DynamoDbDocumentStore ignores ttl_seconds=%s on %s%s", ttl_seconds, collection, fields)
293
+ if not unique:
294
+ return
295
+ self._table(collection, key_fields=list(fields))
296
+ keyed_by = self._key_fields(collection)
297
+ if keyed_by is None:
298
+ raise NotImplementedError(
299
+ f"DynamoDbDocumentStore cannot add the unique index {list(fields)!r} to {collection!r}: "
300
+ "its table was created by a write before any unique index"
301
+ )
302
+ if keyed_by != list(fields):
303
+ raise NotImplementedError(
304
+ f"DynamoDbDocumentStore keys {collection!r} by {keyed_by!r}; "
305
+ f"a second unique index {list(fields)!r} is unsupported"
306
+ )
@@ -0,0 +1,199 @@
1
+ """In-Python evaluation of the Filter, Sort and UpdateSpec algebra with Mongo semantics,
2
+ for backends with no native query language to push it down to."""
3
+
4
+ from __future__ import annotations
5
+
6
+ from typing import Optional
7
+
8
+ from agent_env.store.document_store.document_store import (
9
+ AbsentOrNull,
10
+ Eq,
11
+ Exists,
12
+ Filter,
13
+ Gte,
14
+ In,
15
+ Lte,
16
+ LteOrAbsent,
17
+ Ne,
18
+ Predicate,
19
+ Sort,
20
+ UpdateSpec,
21
+ )
22
+
23
+
24
+ def _resolve(doc: dict, path: str) -> tuple[bool, list]:
25
+ """Resolve a dotted path to (present, values): a numeric segment indexes an
26
+ array; a non-numeric segment into an array traverses its elements."""
27
+ cursors = [doc]
28
+ for seg in path.split("."):
29
+ nxt = []
30
+ for cur in cursors:
31
+ if isinstance(cur, dict):
32
+ if seg in cur:
33
+ nxt.append(cur[seg])
34
+ elif isinstance(cur, list):
35
+ if seg.isdigit():
36
+ idx = int(seg)
37
+ if 0 <= idx < len(cur):
38
+ nxt.append(cur[idx])
39
+ else:
40
+ for el in cur:
41
+ if isinstance(el, dict) and seg in el:
42
+ nxt.append(el[seg])
43
+ cursors = nxt
44
+ if not cursors:
45
+ return False, []
46
+ return True, cursors
47
+
48
+
49
+ def _eq(rv, value) -> bool:
50
+ return rv == value or (isinstance(rv, list) and value in rv)
51
+
52
+
53
+ def _cmp(rv, value, op: str) -> bool:
54
+ try:
55
+ return rv >= value if op == "ge" else rv <= value
56
+ except TypeError:
57
+ return False
58
+
59
+
60
+ def _pred_matches(doc: dict, field: str, pred: Predicate) -> bool:
61
+ present, values = _resolve(doc, field)
62
+ if isinstance(pred, Eq):
63
+ return any(_eq(rv, pred.value) for rv in values) if present else pred.value is None
64
+ if isinstance(pred, Ne):
65
+ return present and not any(_eq(rv, pred.value) for rv in values)
66
+ if isinstance(pred, In):
67
+ return present and any(
68
+ rv in pred.values or (isinstance(rv, list) and any(e in pred.values for e in rv))
69
+ for rv in values
70
+ )
71
+ if isinstance(pred, Gte):
72
+ return any(_cmp(rv, pred.value, "ge") for rv in values)
73
+ if isinstance(pred, Lte):
74
+ return any(_cmp(rv, pred.value, "le") for rv in values)
75
+ if isinstance(pred, Exists):
76
+ return present == pred.present
77
+ if isinstance(pred, LteOrAbsent):
78
+ if not present:
79
+ return True
80
+ return any(rv is None for rv in values) or any(
81
+ _cmp(rv, pred.value, "le") for rv in values
82
+ )
83
+ if isinstance(pred, AbsentOrNull):
84
+ return (not present) or any(rv is None for rv in values)
85
+ raise TypeError(f"Unsupported predicate: {pred!r}")
86
+
87
+
88
+ def matches(doc: dict, filter: Filter) -> bool:
89
+ return all(
90
+ _pred_matches(doc, field, pred)
91
+ for field, preds in filter.conditions.items()
92
+ for pred in preds
93
+ )
94
+
95
+
96
+ def _sort_key(doc: dict, field: str):
97
+ present, values = _resolve(doc, field)
98
+ if not present or values[0] is None:
99
+ return (0,)
100
+ return (1, values[0])
101
+
102
+
103
+ def sort_docs(docs: list[dict], sort: Optional[Sort]) -> list[dict]:
104
+ if sort is None or not sort.keys:
105
+ return docs
106
+ for key in reversed(sort.keys):
107
+ docs = sorted(docs, key=lambda d, k=key: _sort_key(d, k.field), reverse=key.descending)
108
+ return docs
109
+
110
+
111
+ def _get_child(container, seg: str):
112
+ if isinstance(container, dict):
113
+ return container.get(seg)
114
+ if isinstance(container, list) and seg.isdigit() and 0 <= int(seg) < len(container):
115
+ return container[int(seg)]
116
+ return None
117
+
118
+
119
+ def _step_write(container, seg: str):
120
+ if isinstance(container, list):
121
+ return container[int(seg)]
122
+ child = container.get(seg)
123
+ if not isinstance(child, (dict, list)):
124
+ child = {}
125
+ container[seg] = child
126
+ return child
127
+
128
+
129
+ def _assign(container, seg: str, value) -> None:
130
+ if isinstance(container, list):
131
+ container[int(seg)] = value
132
+ else:
133
+ container[seg] = value
134
+
135
+
136
+ def _set_path(doc: dict, path: str, value) -> None:
137
+ segs = path.split(".")
138
+ cur = doc
139
+ for seg in segs[:-1]:
140
+ cur = _step_write(cur, seg)
141
+ _assign(cur, segs[-1], value)
142
+
143
+
144
+ def _unset_path(doc: dict, path: str) -> None:
145
+ segs = path.split(".")
146
+ cur = doc
147
+ for seg in segs[:-1]:
148
+ cur = _get_child(cur, seg)
149
+ if cur is None:
150
+ return
151
+ last = segs[-1]
152
+ if isinstance(cur, dict):
153
+ cur.pop(last, None)
154
+ elif isinstance(cur, list) and last.isdigit() and 0 <= int(last) < len(cur):
155
+ cur[int(last)] = None
156
+
157
+
158
+ def _ensure_list(doc: dict, path: str) -> list:
159
+ segs = path.split(".")
160
+ cur = doc
161
+ for seg in segs[:-1]:
162
+ cur = _step_write(cur, seg)
163
+ existing = _get_child(cur, segs[-1])
164
+ if not isinstance(existing, list):
165
+ existing = []
166
+ _assign(cur, segs[-1], existing)
167
+ return existing
168
+
169
+
170
+ def apply_update(doc: dict, spec: UpdateSpec) -> None:
171
+ spec.validate()
172
+ for path, value in spec.set.items():
173
+ _set_path(doc, path, value)
174
+ for path in spec.unset:
175
+ _unset_path(doc, path)
176
+ for path, delta in spec.inc.items():
177
+ segs = path.split(".")
178
+ cur = doc
179
+ for seg in segs[:-1]:
180
+ cur = _step_write(cur, seg)
181
+ current = _get_child(cur, segs[-1])
182
+ _assign(cur, segs[-1], (current or 0) + delta)
183
+ for path, items in spec.add_to_set.items():
184
+ lst = _ensure_list(doc, path)
185
+ for it in items:
186
+ if it not in lst:
187
+ lst.append(it)
188
+ for path, items in spec.push.items():
189
+ _ensure_list(doc, path).extend(items)
190
+
191
+
192
+ def synthesize(filter: Filter, spec: UpdateSpec) -> dict:
193
+ doc: dict = {}
194
+ for field, preds in filter.conditions.items():
195
+ for pred in preds:
196
+ if isinstance(pred, Eq):
197
+ _set_path(doc, field, pred.value)
198
+ apply_update(doc, spec)
199
+ return doc