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,239 @@
1
+ """What an entity's ``from_toml`` builds itself from: its bundle entry, and what its toml names."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import stat
7
+ import unicodedata
8
+ from dataclasses import dataclass
9
+ from pathlib import Path
10
+ from typing import Any, NoReturn, TypeVar, overload
11
+
12
+ from agent_env.artifact.artifact import Artifact
13
+ from agent_env.entity_refs import EntityKind, parse_toml_ref
14
+ from agent_env.env.env import Env
15
+
16
+ from ._fs import os_reason, relative, show, with_article
17
+ from .parse import CONFIG_FILES, LEAVINGS, NAMED_BY, Bundle, BundleEntry, BundleError
18
+
19
+ A = TypeVar("A", bound=Artifact)
20
+ E = TypeVar("E", bound=Env)
21
+
22
+ _BRING_IT_IN = "copy what it points to into the bundle, or put it in a store and refer to it by id"
23
+ _TOML_TYPES = {str: "a string", dict: "a table"}
24
+
25
+
26
+ @dataclass(frozen=True)
27
+ class AuthoringContext:
28
+ """One bundle entry being authored. ``env`` and ``artifact`` load what a resolved ref names: an
29
+ id, or a table ``{ env = "<id>", version = <n> }`` (``artifact =`` for an artifact), at that
30
+ version or, without one, at its latest."""
31
+
32
+ bundle: Bundle
33
+ entry: BundleEntry
34
+
35
+ @property
36
+ def id(self) -> str:
37
+ return self.entry.id
38
+
39
+ @property
40
+ def name(self) -> str:
41
+ return self.entry.name
42
+
43
+ @property
44
+ def dir(self) -> Path:
45
+ return self.entry.path
46
+
47
+ def files(self) -> dict[str, Path]:
48
+ return entry_files(self.bundle, self.entry)
49
+
50
+ def file(self) -> tuple[str, Path]:
51
+ return entry_file(self.bundle, self.entry)
52
+
53
+ def accept(self, data: dict, /, **takes: type) -> dict:
54
+ """The keys of ``data`` a type takes, each checked against the type given; any other key but
55
+ ``type`` and ``id`` is refused."""
56
+ fields, problems = self.accepted(data, **takes)
57
+ if problems:
58
+ self.refuse(problems)
59
+ return fields
60
+
61
+ def accepted(self, data: dict, /, **takes: type) -> tuple[dict, list[str]]:
62
+ """``accept`` without refusing: the keys of ``data`` a type takes and of the type given, and the
63
+ problems with the rest, for a type that checks more before it refuses."""
64
+ config = CONFIG_FILES[self.entry.kind]
65
+ problems = []
66
+ unknown = sorted(set(data) - {"type", "id", *takes})
67
+ if unknown:
68
+ names = [*takes, "type", "id"]
69
+ problems.append(f"{config}: unknown key{'s' * (len(unknown) > 1)} {', '.join(map(repr, unknown))}; "
70
+ f"{with_article(f'{self.entry.type} {self.entry.kind.store}')} takes "
71
+ f"{', '.join(names[:-1])} and {names[-1]}")
72
+ for key, kind in takes.items():
73
+ if key in data and not isinstance(data[key], kind):
74
+ problems.append(f"{config}: {key} must be {_TOML_TYPES.get(kind, kind.__name__)}, not {data[key]!r}")
75
+ fields = {key: data[key] for key, kind in takes.items() if key in data and isinstance(data[key], kind)}
76
+ return fields, problems
77
+
78
+ def refuse(self, problems: list[str]) -> NoReturn:
79
+ """Raise BundleError with ``problems``, each named by the entry's folder."""
80
+ where = relative(self.bundle.root, self.entry.path)
81
+ raise BundleError([f"{where}: {problem}" for problem in problems])
82
+
83
+ @overload
84
+ def env(self, ref: str | dict[str, Any]) -> Env: ...
85
+ @overload
86
+ def env(self, ref: str | dict[str, Any], expect: type[E]) -> E: ...
87
+ def env(self, ref: str | dict[str, Any], expect: type[Env] = Env) -> Env:
88
+ return self._load(Env, EntityKind.ENV, ref, expect)
89
+
90
+ @overload
91
+ def artifact(self, ref: str | dict[str, Any]) -> Artifact: ...
92
+ @overload
93
+ def artifact(self, ref: str | dict[str, Any], expect: type[A]) -> A: ...
94
+ def artifact(self, ref: str | dict[str, Any], expect: type[Artifact] = Artifact) -> Artifact:
95
+ return self._load(Artifact, EntityKind.ARTIFACT, ref, expect)
96
+
97
+ def _load(self, base: type, kind: EntityKind, ref: Any, expect: type) -> Any:
98
+ entity_id, version = self._parse(kind, ref)
99
+ named = next((entry for entry in self.bundle.entries
100
+ if entry.kind in NAMED_BY[kind] and entry.name.casefold() == entity_id.casefold()), None)
101
+ if named is not None:
102
+ self._fail(f"{entity_id!r} matches this bundle's {kind.value} {named.name!r} but wasn't resolved; "
103
+ "declare its key in toml_refs")
104
+ loaded = base.get(entity_id, version)
105
+ if not isinstance(loaded, expect):
106
+ self._fail(f"{entity_id} is a {loaded.type} {kind.value}, not a {expect.__name__}")
107
+ return loaded
108
+
109
+ def _parse(self, kind: EntityKind, ref: Any) -> tuple[str, int | None]:
110
+ try:
111
+ return parse_toml_ref(kind, ref)
112
+ except ValueError as e:
113
+ self._fail(str(e))
114
+
115
+ def _fail(self, message: str) -> NoReturn:
116
+ self.refuse([message])
117
+
118
+
119
+ def entry_files(bundle: Bundle, entry: BundleEntry) -> dict[str, Path]:
120
+ """The files in an entry's folder, keyed by POSIX path in NFC and sorted: regular files, dot files
121
+ included, through links that stay inside the bundle, less what the OS or Python leaves behind and
122
+ the entry's own toml. Raises BundleError listing every problem found."""
123
+ return _Walk(bundle, entry).files()
124
+
125
+
126
+ def entry_file(bundle: Bundle, entry: BundleEntry) -> tuple[str, Path]:
127
+ """The one file in an entry's folder, as ``(name, path)``. Raises BundleError otherwise."""
128
+ files = entry_files(bundle, entry)
129
+ if len(files) != 1:
130
+ listed = ", ".join(repr(name) for name in files)
131
+ raise BundleError([f"{relative(bundle.root, entry.path)}: a {entry.type} {entry.kind.store} holds one file, "
132
+ f"and this folder has {len(files)} ({listed}); leave out its declared type to write the "
133
+ "folder as a file_artifact_universe"])
134
+ key, path = next(iter(files.items()))
135
+ return key.rsplit("/", 1)[-1], path
136
+
137
+
138
+ class _Walk:
139
+ """Lists an entry's folder, following a link only when its target is inside the bundle."""
140
+
141
+ def __init__(self, bundle: Bundle, entry: BundleEntry):
142
+ self.bundle = bundle
143
+ self.entry = entry
144
+ self.root = _identity(bundle.root)
145
+ self.problems: list[str] = []
146
+ self.found: dict[str, Path] = {}
147
+
148
+ def files(self) -> dict[str, Path]:
149
+ top = self.entry.path
150
+ if not self._inside(top):
151
+ how = "links to" if top.is_symlink() else "resolves to"
152
+ self._problem(top, f"{how} {show(os.path.realpath(top))}, outside the bundle; {_BRING_IT_IN}")
153
+ else:
154
+ self._walk(top)
155
+ if not self.found and not self.problems:
156
+ self._problem(top, f"has no files to write ({', '.join(sorted(LEAVINGS))} don't count)")
157
+ if self.problems:
158
+ raise BundleError(self.problems)
159
+ return dict(sorted(self.found.items()))
160
+
161
+ def _walk(self, top: Path) -> None:
162
+ config = CONFIG_FILES.get(self.entry.kind)
163
+ # The folders holding the entry's up to the bundle root count too, so a link up to one loops.
164
+ depth = len(top.relative_to(self.bundle.root).parts)
165
+ pending = [(top, (), frozenset(_identity(folder) for folder in (top, *list(top.parents)[:depth])))]
166
+ while pending:
167
+ folder, parts, holders = pending.pop()
168
+ try:
169
+ with os.scandir(folder) as listing:
170
+ children = sorted(listing, key=lambda child: child.name)
171
+ except OSError as e:
172
+ self._problem(folder, os_reason(e))
173
+ continue
174
+ for child in children:
175
+ if child.name in LEAVINGS or (not parts and child.name == config):
176
+ continue
177
+ path = folder / child.name
178
+ if child.is_symlink():
179
+ kind = self._linked(path)
180
+ elif child.is_dir(follow_symlinks=False):
181
+ kind = stat.S_IFDIR
182
+ elif child.is_file(follow_symlinks=False):
183
+ kind = stat.S_IFREG
184
+ else:
185
+ kind = None
186
+ self._problem(path, "neither a regular file nor a folder")
187
+ if kind == stat.S_IFDIR:
188
+ identity = _identity(path)
189
+ if identity in holders:
190
+ self._problem(path, "links back to a folder that holds it")
191
+ else:
192
+ pending.append((path, (*parts, child.name), holders | {identity}))
193
+ elif kind == stat.S_IFREG:
194
+ if os.access(path, os.R_OK):
195
+ self._found((*parts, child.name), path)
196
+ else:
197
+ self._problem(path, "permission denied")
198
+
199
+ def _linked(self, path: Path) -> int | None:
200
+ """The kind a link resolves to, or None after recording why it can't be followed."""
201
+ try:
202
+ mode = os.stat(path).st_mode
203
+ except OSError as e:
204
+ self._problem(path, "a broken symlink" if isinstance(e, FileNotFoundError) else os_reason(e))
205
+ return None
206
+ if not self._inside(path):
207
+ self._problem(path, f"links to {show(os.path.realpath(path))}, outside the bundle; {_BRING_IT_IN}")
208
+ return None
209
+ if stat.S_ISDIR(mode) or stat.S_ISREG(mode):
210
+ return stat.S_IFMT(mode)
211
+ self._problem(path, "links to something that is neither a regular file nor a folder")
212
+ return None
213
+
214
+ def _inside(self, path: Path) -> bool:
215
+ """Whether ``path`` resolves to somewhere under the bundle root, compared by device and inode
216
+ so a differently cased or normalized spelling of the root still counts."""
217
+ resolved = Path(os.path.realpath(path))
218
+ return any(_identity(candidate) == self.root for candidate in (resolved, *resolved.parents))
219
+
220
+ def _found(self, parts: tuple[str, ...], path: Path) -> None:
221
+ key = "/".join(unicodedata.normalize("NFC", part) for part in parts)
222
+ if key in self.found:
223
+ self._problem(path, f"has the same name as {relative(self.bundle.root, self.found[key])} once normalized "
224
+ "to NFC; rename one")
225
+ else:
226
+ self.found[key] = path
227
+
228
+ def _problem(self, path: Path, message: str) -> None:
229
+ self.problems.append(f"{relative(self.bundle.root, path)}: {message}")
230
+
231
+
232
+ def _identity(path: Path) -> tuple[int, int] | None:
233
+ try:
234
+ status = os.stat(path)
235
+ except OSError:
236
+ return None
237
+ return (status.st_dev, status.st_ino)
238
+
239
+
@@ -0,0 +1,175 @@
1
+ """Bundles installed with a package, found through the ``agent_env.bundles`` entry points.
2
+
3
+ A distribution registers ``<name> = "<package>"`` and ships the bundle folder at ``<package>/<name>/``. The folder is
4
+ found without importing any package code: only the top-level package is located, and the rest of the path is walked
5
+ as folders. An installed bundle's ids are rooted at its distribution, ``@local/<dist>/<name>``. A name several
6
+ distributions install is run as ``<dist>/<name>``, except that agent-env's own bundles keep their bare names.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import difflib
12
+ import importlib.util
13
+ import os
14
+ from collections import Counter
15
+ from dataclasses import dataclass
16
+ from importlib.metadata import EntryPoint
17
+ from pathlib import Path
18
+
19
+ from packaging.utils import canonicalize_name
20
+
21
+ from agent_env.plugins._discovery import Plugin, claims, identity
22
+ from agent_env.plugins._report import INCOMPATIBLE_CORE, INVALID_PLUGIN, NAME_CONFLICT
23
+ from agent_env.plugins._requirements import incompatibility
24
+ from agent_env.store.ids import LOCAL_PREFIX
25
+
26
+ from ._fs import os_reason
27
+ from .parse import Bundle, BundleError, parse_bundle
28
+ from .plan import check_bundle
29
+ from .resolve import resolve_bundle
30
+
31
+ BUNDLES = "agent_env.bundles"
32
+ CORE = "agentenv-framework"
33
+
34
+
35
+ @dataclass(frozen=True)
36
+ class InstalledBundle:
37
+ """A bundle an installed distribution registers: its folder, or why it can't run."""
38
+
39
+ name: str
40
+ package: str # the distribution, as its metadata spells it
41
+ version: str
42
+ value: str # the package the entry point names
43
+ root: Path | None
44
+ code: str | None # the plugin report's code for ``problem``
45
+ problem: str | None
46
+
47
+ @property
48
+ def dist(self) -> str:
49
+ return canonicalize_name(self.package)
50
+
51
+ @property
52
+ def qualified(self) -> str:
53
+ return f"{self.dist}/{self.name}"
54
+
55
+ @property
56
+ def id_root(self) -> str:
57
+ return f"{LOCAL_PREFIX}{self.dist}/{self.name}"
58
+
59
+
60
+ class _Unresolved(Exception):
61
+ pass
62
+
63
+
64
+ def installed_bundles() -> tuple[InstalledBundle, ...]:
65
+ """Every bundle installed distributions register, in name order, each resolved to its folder or with the
66
+ reason it can't run. Raises what reading the installed metadata raises."""
67
+ found = []
68
+ for name, registrations in claims(BUNDLES).items():
69
+ per_package = Counter(plugin.dist for plugin, _ in registrations)
70
+ for plugin, ep in registrations:
71
+ found.append(_installed(name, plugin, ep, repeated=per_package[plugin.dist] > 1))
72
+ return tuple(found)
73
+
74
+
75
+ def find_bundle(text: str, bundles: tuple[InstalledBundle, ...] | None = None) -> InstalledBundle:
76
+ """The installed bundle ``text`` names, as ``<name>`` or ``<dist>/<name>``. Raises BundleError."""
77
+ bundles = installed_bundles() if bundles is None else bundles
78
+ dist, _, name = text.rpartition("/")
79
+ matches = [bundle for bundle in bundles if bundle.name == name and (not dist or bundle.dist == canonicalize_name(dist))]
80
+ if not dist and len({bundle.dist for bundle in matches}) > 1:
81
+ matches = [bundle for bundle in matches if bundle.dist == CORE]
82
+ if not matches:
83
+ names = ", ".join(sorted(repr(bundle.qualified) for bundle in bundles if bundle.name == name))
84
+ raise BundleError([f"{text!r}: several packages install a bundle of that name; run one of {names}"])
85
+ if not matches:
86
+ raise BundleError([_unknown(text, bundles)])
87
+ bundle = matches[0]
88
+ if bundle.problem:
89
+ raise BundleError([f"{bundle.qualified}: {bundle.problem}"])
90
+ return bundle
91
+
92
+
93
+ def run_name(bundle: InstalledBundle, bundles: tuple[InstalledBundle, ...]) -> str:
94
+ """The name ``bundle`` runs by: bare, unless another distribution installs that name and ``bundle`` isn't
95
+ agent-env's own."""
96
+ shared = any(other.name == bundle.name and other.dist != bundle.dist for other in bundles)
97
+ return bundle.qualified if shared and bundle.dist != CORE else bundle.name
98
+
99
+
100
+ def checked(bundle: InstalledBundle, *, load: bool = True) -> Bundle:
101
+ """``bundle``'s folder, parsed and, with ``load``, checked as ``agent-env run`` checks it before it reads a
102
+ store. Raises BundleError."""
103
+ parsed = parse_bundle(bundle.root, id_root=bundle.id_root)
104
+ if load:
105
+ check_bundle(resolve_bundle(parsed))
106
+ return parsed
107
+
108
+
109
+ def _installed(name: str, plugin: Plugin, ep: EntryPoint, *, repeated: bool) -> InstalledBundle:
110
+ package, version = identity(ep)
111
+
112
+ def installed(root: Path | None = None, code: str | None = None, problem: str | None = None) -> InstalledBundle:
113
+ return InstalledBundle(name, package, version, plugin.value, root, code, problem)
114
+
115
+ if not plugin.dist:
116
+ return installed(code=INVALID_PLUGIN, problem="its distribution's metadata can't be read")
117
+ if repeated:
118
+ return installed(code=NAME_CONFLICT, problem=f"{package} registers the bundle {name!r} more than once")
119
+ if unmet := incompatibility(getattr(ep, "dist", None)):
120
+ return installed(code=INCOMPATIBLE_CORE, problem=f"{package} {unmet}")
121
+ try:
122
+ return installed(root=_folder(ep, name))
123
+ except _Unresolved as e:
124
+ return installed(code=INVALID_PLUGIN, problem=str(e))
125
+
126
+
127
+ def _folder(ep: EntryPoint, name: str) -> Path:
128
+ """The folder ``<package>/<name>`` the entry point names, found without importing the package."""
129
+ try:
130
+ package, attr = ep.module, ep.attr
131
+ except AttributeError:
132
+ package, attr = None, None
133
+ if package is None or attr:
134
+ raise _Unresolved(f"the entry point's value {ep.value!r} isn't a package name; name the package that holds "
135
+ f"the {name!r} folder")
136
+ if "/" in name:
137
+ raise _Unresolved(f"the bundle name {name!r} contains '/'")
138
+ top, *rest = package.split(".")
139
+ try:
140
+ spec = importlib.util.find_spec(top)
141
+ except (ImportError, ValueError):
142
+ spec = None
143
+ if spec is None or not spec.submodule_search_locations:
144
+ raise _Unresolved(f"{top!r} isn't an installed package")
145
+ # A namespace package can have several locations, and an editable install can add ones that aren't folders.
146
+ locations = [Path(location) for location in spec.submodule_search_locations if os.path.isdir(location)]
147
+ if not locations:
148
+ raise _Unresolved(f"the package {top!r} isn't unpacked on disk; reinstall it unpacked")
149
+ for location in locations:
150
+ if (folder := _spelled(location, (*rest, name))) is not None:
151
+ return folder
152
+ raise _Unresolved(f"the package {package!r} has no folder {name!r}")
153
+
154
+
155
+ def _spelled(location: Path, parts: tuple[str, ...]) -> Path | None:
156
+ """``location/parts`` when each part is a folder spelled exactly so, following links without resolving them,
157
+ so a case-insensitive filesystem and a linked folder are judged as they are elsewhere."""
158
+ folder = location
159
+ for part in parts:
160
+ try:
161
+ if part not in os.listdir(folder) or not os.path.isdir(folder / part):
162
+ return None
163
+ except OSError as e:
164
+ raise _Unresolved(f"the folder {folder} can't be read: {os_reason(e)}") from None
165
+ folder /= part
166
+ return folder
167
+
168
+
169
+ def _unknown(text: str, bundles: tuple[InstalledBundle, ...]) -> str:
170
+ if not bundles:
171
+ return f"{text!r} is neither a folder nor an installed bundle, and no bundles are installed"
172
+ names = sorted({run_name(bundle, bundles) for bundle in bundles})
173
+ close = difflib.get_close_matches(text, names, n=3)
174
+ hint = f"; did you mean {' or '.join(repr(name) for name in close)}?" if close else ""
175
+ return f"{text!r} is neither a folder nor an installed bundle{hint} (agent-env run lists the installed bundles)"
@@ -0,0 +1,269 @@
1
+ """The bundle ledger: what each version a bundle wrote was made from, so a re-run writes only what changed.
2
+
3
+ A row per written version records a digest of the write's inputs and one digest per input, so a new
4
+ version can say why it was written ("files changed: server.py"). The ledger lives in the ``@local``
5
+ namespace's own store, beside the entities it describes, and is never read through the router, so it
6
+ never reaches a configured store. Reading it never creates the store.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import hashlib
12
+ import json
13
+ import os
14
+ from collections.abc import Callable, Iterator, Mapping
15
+ from contextlib import contextmanager
16
+ from dataclasses import dataclass
17
+ from datetime import date, datetime, time, timezone
18
+ from pathlib import Path
19
+ from typing import Any
20
+
21
+ from agent_env.a2a_agent.store import A2A_AGENTS_COLLECTION
22
+ from agent_env.artifact.registry import canonical_type, get_artifact_registry
23
+ from agent_env.artifact.store import ARTIFACTS_COLLECTION
24
+ from agent_env.config import get_config
25
+ from agent_env.config.paths import state_root
26
+ from agent_env.env.env import Env
27
+ from agent_env.env.registry import get_env_registry
28
+ from agent_env.env.store import ENVS_COLLECTION
29
+ from agent_env.eval.store import EVALS_COLLECTION
30
+ from agent_env.store import Filter, Sort
31
+ from agent_env.store.document_store import LocalSqliteDocumentStore
32
+ from agent_env.store.local_state import ensure_state_dir
33
+ from agent_env.task.store import TASKS_COLLECTION
34
+
35
+ from .authoring import entry_files
36
+ from .parse import Bundle, BundleKind
37
+ from .plan import Plan, Write, folder_walk, keeps_base_from_toml
38
+ from .resolve import BuiltImage
39
+
40
+ try:
41
+ import fcntl
42
+ except ImportError: # Windows: runs of one bundle aren't serialized
43
+ fcntl = None
44
+
45
+ LEDGER_COLLECTION = "bundle_ledger"
46
+ # Bumped by hand when what a digest covers changes, or a writer's output changes enough that every
47
+ # version it wrote should be written again.
48
+ SCHEME = 1
49
+
50
+ _COLLECTIONS = {"env": ENVS_COLLECTION, "agent": A2A_AGENTS_COLLECTION, "artifact": ARTIFACTS_COLLECTION,
51
+ "task": TASKS_COLLECTION, "eval": EVALS_COLLECTION}
52
+ _LISTED = 5
53
+
54
+
55
+ @dataclass(frozen=True)
56
+ class Digest:
57
+ value: str
58
+ inputs: dict[str, Any] # type, config, files {key: sha256}, needs and store_refs {"<kind> <id>": version}
59
+
60
+
61
+ @dataclass(frozen=True)
62
+ class Check:
63
+ """Whether a write can reuse the version the bundle last wrote, and if not, why not."""
64
+
65
+ write: Write
66
+ digest: Digest | None # None when the write's inputs aren't tracked, so it is always written
67
+ version: int | None # the version to reuse; None when the write needs a new one
68
+ reasons: tuple[str, ...]
69
+
70
+ @property
71
+ def unchanged(self) -> bool:
72
+ return self.version is not None
73
+
74
+
75
+ class Ledger:
76
+ """One plan's rows in the ``@local`` namespace's store."""
77
+
78
+ def __init__(self, store: LocalSqliteDocumentStore, plan: Plan):
79
+ self._store = store
80
+ self._plan = plan
81
+ self._bundle = plan.bundle.bundle.id_root
82
+
83
+ @classmethod
84
+ def for_plan(cls, plan: Plan) -> Ledger:
85
+ return cls(get_config().local_namespace_document_store(), plan)
86
+
87
+ def check(self, write: Write) -> Check:
88
+ """Compare ``write`` with the latest version the ledger records for it. Checks run in the plan's
89
+ order, after each earlier write is recorded, so the versions a dependent records are current."""
90
+ digest = self.digest(write)
91
+ if digest is None:
92
+ return Check(write, None, None, ("its inputs aren't tracked yet, so it is written every run",))
93
+ row = self._latest(write.kind.store, write.id)
94
+ recorded = row["version"] if row else None
95
+ stored = self._stored_version(write)
96
+ reasons = []
97
+ if row is not None and row["bundle"] != self._bundle:
98
+ reasons.append(f"last written by the bundle {row['bundle']}")
99
+ if stored is None:
100
+ reasons.append("new" if row is None else f"its v{recorded} is not in the store")
101
+ elif stored != recorded:
102
+ reasons.append(f"the store's latest, v{stored}, wasn't recorded by this bundle")
103
+ if row is not None:
104
+ reasons.extend(_changes(row, digest))
105
+ return Check(write, digest, None if reasons else recorded, tuple(reasons))
106
+
107
+ def digest(self, write: Write) -> Digest | None:
108
+ """What ``write`` is made from, or None when the ledger can't tell it all, so it is written every run."""
109
+ if not _tracked(write):
110
+ return None
111
+ inputs = {"type": _type(write), "config": _sha256(_canonical(write.source.config)),
112
+ "files": {}, "needs": {}, "store_refs": {}}
113
+ if write.kind is BundleKind.ARTIFACT:
114
+ for key, path in entry_files(self._plan.bundle.bundle, write.source.entry).items():
115
+ inputs["files"][key] = _file_sha256(path)
116
+ elif write.kind in (BundleKind.ENV, BundleKind.AGENT):
117
+ # An env's or agent's document records the versions of what it references, so one written anew, or
118
+ # a store entity it names without a version getting a new one, means it must be written again. A
119
+ # task or eval names its references without a version.
120
+ for store, id in write.needs:
121
+ row = self._latest(store, id)
122
+ inputs["needs"][f"{store} {id}"] = str(row["version"]) if row else "unwritten"
123
+ for ref in write.source.references:
124
+ if ref.local is None and ref.version is None:
125
+ inputs["store_refs"][f"{ref.kind} {ref.id}"] = str(self._plan.store_latest[ref.kind, ref.id])
126
+ value = _sha256(_canonical({"scheme": SCHEME, "store": write.kind.store, "id": write.id, "inputs": inputs}))
127
+ return Digest(value, inputs)
128
+
129
+ def record(self, check: Check, write: Callable[[], int]) -> int:
130
+ """Write ``check``'s entity with ``write``, which returns the version it wrote, and record it.
131
+ A pending row marks the attempt until it's done; one a crash of this bundle left is dropped here."""
132
+ key = {"store": check.write.kind.store, "id": check.write.id, "bundle": self._bundle}
133
+ self._store.ensure_index(LEDGER_COLLECTION, ["store", "id", "status"])
134
+ while self._store.delete(LEDGER_COLLECTION, Filter.of(**key, status="pending")):
135
+ pass
136
+ pending = {**key, "status": "pending", "scheme": SCHEME,
137
+ "digest": check.digest.value if check.digest else None,
138
+ "inputs": check.digest.inputs if check.digest else None, "at": _now()}
139
+ self._store.insert(LEDGER_COLLECTION, pending)
140
+ version = write()
141
+ done = {**pending, "status": "done", "version": version, "at": _now()}
142
+ if check.digest is not None and self.digest(check.write) != check.digest:
143
+ # A file changed during the write, so what the version holds is unknown: the next run writes it again.
144
+ done.update(digest=None, inputs=None)
145
+ self._store.replace(LEDGER_COLLECTION, Filter.of(**key, status="pending"), done, upsert=True)
146
+ return version
147
+
148
+ def _latest(self, store: str, id: str) -> dict | None:
149
+ return self._find(LEDGER_COLLECTION, Filter.of(store=store, id=id, status="done"))
150
+
151
+ def _stored_version(self, write: Write) -> int | None:
152
+ doc = self._find(_COLLECTIONS[write.kind.store], Filter.of(id=write.id))
153
+ return doc["version"] if doc else None
154
+
155
+ def _find(self, collection: str, filter: Filter) -> dict | None:
156
+ """The highest version matching ``filter``, read without creating the store."""
157
+ if not self._store.path.exists():
158
+ return None
159
+ return self._store.find_one(collection, filter, sort=Sort.by("version"))
160
+
161
+
162
+ @contextmanager
163
+ def materializing(bundle: Bundle, on_wait: Callable[[], None] | None = None) -> Iterator[None]:
164
+ """Hold a lock on every id the bundle's entries write while its entities are written. Another run that
165
+ writes any of those ids, of this bundle or another, waits here, calling ``on_wait`` first. The locks are
166
+ taken in one order, so two runs can't each hold one the other waits for. Task runs don't hold them."""
167
+ if fcntl is None:
168
+ yield
169
+ return
170
+ ensure_state_dir(state_root() / "locks")
171
+ fds, waited = [], False
172
+ try:
173
+ for path in sorted({_lock_path(entry.id) for entry in bundle.entries}):
174
+ fds.append(os.open(path, os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW, 0o600))
175
+ try:
176
+ fcntl.flock(fds[-1], fcntl.LOCK_EX | fcntl.LOCK_NB)
177
+ except BlockingIOError:
178
+ if on_wait is not None and not waited:
179
+ on_wait()
180
+ waited = True
181
+ fcntl.flock(fds[-1], fcntl.LOCK_EX)
182
+ yield
183
+ finally:
184
+ for fd in fds:
185
+ os.close(fd)
186
+
187
+
188
+ def _lock_path(id: str) -> Path:
189
+ return state_root() / "locks" / f"entity-{hashlib.sha256(id.encode()).hexdigest()[:16]}.lock"
190
+
191
+
192
+ def _tracked(write: Write) -> bool:
193
+ """Whether the ledger can list everything ``write`` is made from. Not yet for a built image or a skill,
194
+ nor for a type with a ``from_toml`` of its own, which may read its folder in ways it can't see. An agent
195
+ is made from its agent.toml alone: its image is a reference."""
196
+ if isinstance(write.source, BuiltImage) or write.kind is BundleKind.SKILL:
197
+ return False
198
+ if write.kind is BundleKind.ARTIFACT:
199
+ return folder_walk(get_artifact_registry().get(_type(write))) is not None
200
+ if write.kind is BundleKind.ENV:
201
+ cls = get_env_registry().get(_type(write))
202
+ return cls is not None and keeps_base_from_toml(cls, Env)
203
+ return True
204
+
205
+
206
+ def _type(write: Write) -> str:
207
+ type_ = write.source.entry.type
208
+ return canonical_type(type_) if write.kind is BundleKind.ARTIFACT else type_
209
+
210
+
211
+ def _changes(row: Mapping[str, Any], digest: Digest) -> list[str]:
212
+ """Why ``digest`` differs from the one ``row`` recorded, input by input when the two can be compared."""
213
+ if row["digest"] == digest.value:
214
+ return []
215
+ if row["inputs"] is None:
216
+ return ["the ledger doesn't know what its last version was made from"]
217
+ if row["scheme"] != SCHEME:
218
+ return ["the ledger's digest scheme changed"]
219
+ before, after = row["inputs"], digest.inputs
220
+ reasons = []
221
+ if before["type"] != after["type"]:
222
+ reasons.append(f"type changed: {before['type']} → {after['type']}")
223
+ if before.get("config") != after["config"]:
224
+ reasons.append("config changed")
225
+ for label, names in zip(("files added", "files removed", "files changed"), _diff(before["files"], after["files"])):
226
+ if names:
227
+ shown = ", ".join(names[:_LISTED]) + (f" and {len(names) - _LISTED} more" if len(names) > _LISTED else "")
228
+ reasons.append(f"{label}: {shown}")
229
+ needs_before, needs_after = before["needs"], after["needs"]
230
+ added, removed, changed = _diff(needs_before, needs_after)
231
+ reasons.extend(f"{name} was written anew (v{needs_before[name]} → v{needs_after[name]})" for name in changed)
232
+ reasons.extend(f"now needs {name}" for name in added)
233
+ reasons.extend(f"no longer needs {name}" for name in removed)
234
+ refs_before, refs_after = before["store_refs"], after["store_refs"]
235
+ reasons.extend(f"{name} has a new version in the store (v{refs_before[name]} → v{refs_after[name]})"
236
+ for name in _diff(refs_before, refs_after)[2])
237
+ return reasons or ["its inputs changed"]
238
+
239
+
240
+ def _diff(before: Mapping[str, str], after: Mapping[str, str]) -> tuple[list[str], list[str], list[str]]:
241
+ """The keys only ``after`` has, only ``before`` has, and both have with different values, each sorted."""
242
+ return (sorted(after.keys() - before.keys()), sorted(before.keys() - after.keys()),
243
+ sorted(key for key in after.keys() & before.keys() if after[key] != before[key]))
244
+
245
+
246
+ def _canonical(value: Any) -> bytes:
247
+ return json.dumps(value, sort_keys=True, separators=(",", ":"), default=_scalar).encode()
248
+
249
+
250
+ def _scalar(value: Any) -> str:
251
+ if isinstance(value, (datetime, date, time)):
252
+ return value.isoformat()
253
+ raise TypeError(f"{type(value).__name__} is not part of a bundle's config")
254
+
255
+
256
+ def _sha256(data: bytes) -> str:
257
+ return "sha256:" + hashlib.sha256(data).hexdigest()
258
+
259
+
260
+ def _file_sha256(path: Path) -> str:
261
+ digest = hashlib.sha256()
262
+ with open(path, "rb") as file:
263
+ for chunk in iter(lambda: file.read(1 << 20), b""):
264
+ digest.update(chunk)
265
+ return "sha256:" + digest.hexdigest()
266
+
267
+
268
+ def _now() -> str:
269
+ return datetime.now(timezone.utc).isoformat()