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,594 @@
1
+ """Read a bundle folder into the entities it defines, without touching a store.
2
+
3
+ A bundle is a folder holding at least one kind directory (``envs/``, ``agents/``, ``artifacts/``,
4
+ ``skills/``, ``tasks/``, ``evals/``), where ``<kind>/<name>/`` is an entity of that kind named
5
+ ``<name>``; a task is ``tasks/<name>.json`` and an eval ``evals/<name>.toml``. Parsing reads the
6
+ directory listings and the small config files only. References, registered types and file
7
+ contents are checked by the steps that use them.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import json
13
+ import os
14
+ import stat
15
+ import tomllib
16
+ import unicodedata
17
+ from collections import Counter, defaultdict
18
+ from collections.abc import Iterable
19
+ from dataclasses import dataclass, field
20
+ from enum import Enum
21
+ from pathlib import Path
22
+ from typing import Any, NoReturn
23
+
24
+ from agent_env.bundle._fs import Unreadable, fold, home, on_disk, os_reason, read_regular, show
25
+ from agent_env.entity_refs import EntityKind
26
+ from agent_env.store.ids import LOCAL_PREFIX, MAX_AUTHORED_LOCAL_ID_BYTES, validate_local_id
27
+
28
+ BUNDLE_TOML = "bundle.toml"
29
+ DOCKERFILE = "Dockerfile"
30
+ SKILL_MD = "SKILL.md"
31
+
32
+ _DIR, _FILE = "dir", "file"
33
+
34
+
35
+ class BundleKind(Enum):
36
+ """The six kinds; the value is the kind's directory. A plain Enum, so a kind never equals an
37
+ ``EntityKind`` or a string."""
38
+
39
+ ENV = "envs"
40
+ AGENT = "agents"
41
+ ARTIFACT = "artifacts"
42
+ SKILL = "skills"
43
+ TASK = "tasks"
44
+ EVAL = "evals"
45
+
46
+ @property
47
+ def store(self) -> str:
48
+ """The store the kind is written to; artifacts and skills share one."""
49
+ return "artifact" if self is BundleKind.SKILL else self.value[:-1]
50
+
51
+
52
+ # The kinds whose entries a reference of each entity kind names; artifacts and skills share one store.
53
+ NAMED_BY = {
54
+ EntityKind.ENV: (BundleKind.ENV,),
55
+ EntityKind.AGENT: (BundleKind.AGENT,),
56
+ EntityKind.ARTIFACT: (BundleKind.ARTIFACT, BundleKind.SKILL),
57
+ EntityKind.TASK: (BundleKind.TASK,),
58
+ }
59
+ _ORDER = {kind: index for index, kind in enumerate(BundleKind)}
60
+ CONFIG_FILES = {BundleKind.ENV: "env.toml", BundleKind.AGENT: "agent.toml", BundleKind.ARTIFACT: "artifact.toml"}
61
+ _DEFAULT_TYPE = {BundleKind.ENV: "mcp_server", BundleKind.AGENT: "a2a_agent"}
62
+ _EVAL_KEYS = ("tasks", "type", "id")
63
+ _FILE_SUFFIX = {BundleKind.TASK: ".json", BundleKind.EVAL: ".toml"}
64
+
65
+
66
+ @dataclass(frozen=True)
67
+ class BundleEntry:
68
+ kind: BundleKind
69
+ name: str # NFC of the on-disk name: the directory, or the task or eval file's stem
70
+ id: str # the declared id, else ``<Bundle.id_root>/<name>``
71
+ path: Path # as the filesystem spells it (possibly NFD), for I/O
72
+ type: str # declared, else the kind's default; for artifacts, inferred from the directory
73
+ # The toml as written ({} when absent), a task's steps, None for skills.
74
+ config: Any = field(compare=False, repr=False)
75
+
76
+
77
+ @dataclass(frozen=True)
78
+ class Bundle:
79
+ root: Path
80
+ name: str
81
+ id_root: str
82
+ description: str | None # README.md's first line of text
83
+ entries: tuple[BundleEntry, ...]
84
+ ignored: tuple[Path, ...] # root-relative, as on disk: entries that are neither kinds nor entities
85
+
86
+
87
+ class BundleError(ValueError):
88
+ """A folder that isn't a valid bundle. ``problems`` holds every problem found, each naming its path."""
89
+
90
+ def __init__(self, problems: Iterable[str]):
91
+ self.problems = tuple(sorted(problems))
92
+ super().__init__("\n".join(self.problems))
93
+
94
+ @property
95
+ def summary(self) -> str:
96
+ """The first problem, and how many more there are."""
97
+ more = len(self.problems) - 1
98
+ return self.problems[0] + (f" (and {more} more)" if more else "")
99
+
100
+
101
+ # What the OS or Python writes into a folder on its own. In an artifact or skill folder, everything
102
+ # else is content, dot files included.
103
+ LEAVINGS = frozenset({".DS_Store", "Thumbs.db", "desktop.ini", "__pycache__"})
104
+
105
+
106
+ def is_ignored(name: str) -> bool:
107
+ """Dot entries and ``__pycache__`` (pip compiles the .py files of an installed bundle) are never
108
+ entities."""
109
+ return name.startswith(".") or name == "__pycache__"
110
+
111
+
112
+ def parse_bundle(root: Path, *, id_root: str | None = None, name: str | None = None) -> Bundle:
113
+ """Parse the bundle at ``root``. An entry-point bundle passes its ``@local/<dist>/<name>``
114
+ root and name; otherwise both come from the folder's canonical path. Raises BundleError."""
115
+ return _Parser(_canonical(Path(root)), id_root, name).parse()
116
+
117
+
118
+ class _Skip(Exception):
119
+ """The entity has a problem, already recorded; skip it."""
120
+
121
+
122
+ class _Parser:
123
+ def __init__(self, root: Path, id_root: str | None, name: str | None):
124
+ self.root = root
125
+ self.root_text = str(root)
126
+ self.name = name or unicodedata.normalize("NFC", root.name)
127
+ self.problems: list[str] = []
128
+ self.ignored: list[Path] = []
129
+ self.entry_point = id_root is not None
130
+ self.root_ok = True
131
+ if id_root is None:
132
+ self.id_root = self._derive_id_root()
133
+ return
134
+ self.id_root = id_root
135
+ try:
136
+ self._check_declared(id_root, root, what="the bundle's id root")
137
+ if _size(id_root) > MAX_AUTHORED_LOCAL_ID_BYTES - 2:
138
+ self._skip(root, "the bundle's id root leaves no room for a name; shorten it")
139
+ except _Skip:
140
+ self.root_ok = False
141
+
142
+ def parse(self) -> Bundle:
143
+ kinds, description = self._scan_root()
144
+ entries = [entry for kind, path in kinds.items() for entry in self._scan_kind(kind, path)]
145
+ self._check_unique(entries)
146
+ if self.problems:
147
+ raise BundleError(self.problems)
148
+ entries.sort(key=lambda entry: (_ORDER[entry.kind], entry.name))
149
+ return Bundle(
150
+ root=self.root,
151
+ name=self.name,
152
+ id_root=self.id_root,
153
+ description=description,
154
+ entries=tuple(entries),
155
+ ignored=tuple(sorted(self.ignored)),
156
+ )
157
+
158
+ def _derive_id_root(self) -> str:
159
+ user_home = home()
160
+ home_relative = user_home is not None and self.root.is_relative_to(user_home)
161
+ if home_relative:
162
+ parts = ["~", *self.root.relative_to(user_home).parts]
163
+ above = user_home
164
+ else:
165
+ parts = list(self.root.parts[1:])
166
+ above = Path(self.root.anchor)
167
+ if parts[0] == "~":
168
+ self._problem(above / "~", "a folder named '~' at the filesystem root would read as home; "
169
+ "move the bundle")
170
+ self.root_ok = False
171
+ for part in parts[1:] if home_relative else parts:
172
+ above = above / part
173
+ reason = _refused(part)
174
+ if reason:
175
+ self._problem(above, f"move the bundle, or rename the folder: {reason}")
176
+ self.root_ok = False
177
+ return LOCAL_PREFIX + "/".join(unicodedata.normalize("NFC", part) for part in parts)
178
+
179
+ # Walking the tree
180
+
181
+ def _scan_root(self) -> tuple[dict[BundleKind, Path], str | None]:
182
+ try:
183
+ listing = [entry for entry in self._list(self.root) if not is_ignored(entry.name)]
184
+ except _Skip:
185
+ raise BundleError(self.problems) from None
186
+ names = [entry.name for entry in listing]
187
+ by_dir = {kind.value: kind for kind in BundleKind}
188
+ misspelled = {near for kind_dir in by_dir for near in self._near_miss(self.root, names, kind_dir)}
189
+ if not misspelled and not by_dir.keys() & set(names):
190
+ raise BundleError([f"{show(self.root)}: not a bundle: it has none of "
191
+ + ", ".join(f"{kind.value}/" for kind in BundleKind)])
192
+ kinds: dict[BundleKind, Path] = {}
193
+ readmes = []
194
+ for entry in listing:
195
+ if entry.name in misspelled:
196
+ continue
197
+ if fold(entry.name) == fold(BUNDLE_TOML):
198
+ self._problem(entry.path, "reserved: a bundle takes its name from the folder and its "
199
+ "description from README.md")
200
+ elif entry.name in by_dir:
201
+ node = self._node(Path(entry.path), entry)
202
+ if node == _DIR:
203
+ kinds[by_dir[entry.name]] = Path(entry.path)
204
+ elif node == _FILE:
205
+ self._problem(entry.path, "a kind directory must be a folder")
206
+ elif fold(entry.name) == "readme.md":
207
+ readmes.append(entry)
208
+ else:
209
+ self.ignored.append(Path(entry.name))
210
+ readme = next((entry for entry in readmes if entry.name == "README.md"), readmes[0] if readmes else None)
211
+ self.ignored.extend(Path(entry.name) for entry in readmes if entry is not readme)
212
+ return kinds, self._description(Path(readme.path)) if readme else None
213
+
214
+ def _scan_kind(self, kind: BundleKind, directory: Path) -> list[BundleEntry]:
215
+ try:
216
+ listing = self._list(directory)
217
+ except _Skip:
218
+ return []
219
+ suffix = _FILE_SUFFIX.get(kind)
220
+ names = {listed.name for listed in listing}
221
+ candidates: dict[str, list[tuple[str, Path]]] = defaultdict(list)
222
+ for listed in listing:
223
+ if is_ignored(listed.name):
224
+ continue
225
+ path = Path(listed.path)
226
+ node = self._node(path, listed)
227
+ if node is None:
228
+ continue
229
+ if suffix is None and node == _FILE:
230
+ self.ignored.append(Path(kind.value, listed.name))
231
+ elif suffix is not None and node == _DIR:
232
+ self._problem(path, f"{kind.value[:-1]} folders are not supported yet; "
233
+ f"write {kind.value}/<name>{suffix}")
234
+ elif suffix is not None and not listed.name.endswith(suffix):
235
+ lowered = listed.name[: -len(suffix)] + suffix
236
+ if fold(listed.name) != fold(lowered):
237
+ self.ignored.append(Path(kind.value, listed.name))
238
+ elif lowered in names:
239
+ self._collision([directory / lowered, path])
240
+ else:
241
+ self._problem(path, f"rename to {show(lowered)}; names are case-sensitive")
242
+ else:
243
+ name = unicodedata.normalize("NFC", listed.name.removesuffix(suffix) if suffix else listed.name)
244
+ candidates[fold(name)].append((name, path))
245
+ entries = []
246
+ for group in candidates.values():
247
+ if len(group) > 1:
248
+ self._collision(path for _, path in group)
249
+ continue
250
+ try:
251
+ entries.append(self._entry(kind, *group[0]))
252
+ except _Skip:
253
+ pass
254
+ return entries
255
+
256
+ # One entity per kind
257
+
258
+ def _entry(self, kind: BundleKind, name: str, path: Path) -> BundleEntry:
259
+ if kind in (BundleKind.ARTIFACT, BundleKind.SKILL) and "__" in name:
260
+ self._skip(path, f'"__" is reserved for derived ids in artifact and skill names; rename the '
261
+ f"folder (e.g. {show(name.replace('__', '-'))})")
262
+ if kind in (BundleKind.ENV, BundleKind.AGENT):
263
+ return self._build_context(kind, name, path)
264
+ read = {BundleKind.TASK: self._task, BundleKind.EVAL: self._eval, BundleKind.SKILL: self._skill}
265
+ return read.get(kind, self._artifact)(name, path)
266
+
267
+ def _task(self, name: str, path: Path) -> BundleEntry:
268
+ steps = self._read_json(path)
269
+ if not (isinstance(steps, list) and all(isinstance(step, dict) for step in steps)):
270
+ self._skip(path, "a task file must be a JSON array of step objects")
271
+ return self._make(BundleKind.TASK, name, path, "task", steps)
272
+
273
+ def _eval(self, name: str, path: Path) -> BundleEntry:
274
+ config = self._read_toml(path)
275
+ problems = []
276
+ unknown = sorted(set(config) - set(_EVAL_KEYS))
277
+ if unknown:
278
+ problems.append(f"unknown key{'s' * (len(unknown) > 1)} {', '.join(map(repr, unknown))}; an eval takes "
279
+ f"{', '.join(_EVAL_KEYS[:-1])} and {_EVAL_KEYS[-1]}")
280
+ declared = config.get("type", "eval")
281
+ if not (isinstance(declared, str) and declared):
282
+ problems.append("type must be a non-empty string")
283
+ tasks = config.get("tasks")
284
+ if tasks is None or tasks == []:
285
+ problems.append("an eval needs at least one task in tasks = [...]")
286
+ elif not isinstance(tasks, list):
287
+ problems.append(f"tasks must be a list, not {tasks!r}")
288
+ for problem in problems:
289
+ self._problem(path, problem)
290
+ if problems:
291
+ raise _Skip
292
+ return self._make(BundleKind.EVAL, name, path, declared, config, config.get("id"), path)
293
+
294
+ def _skill(self, name: str, path: Path) -> BundleEntry:
295
+ children = self._children(path)
296
+ if self._near_miss(path, children, SKILL_MD):
297
+ raise _Skip
298
+ if SKILL_MD not in children:
299
+ self._skip(path, f"a skill needs {SKILL_MD}")
300
+ self._marker(path / SKILL_MD, children[SKILL_MD])
301
+ return self._make(BundleKind.SKILL, name, path, "skill", None)
302
+
303
+ def _artifact(self, name: str, path: Path) -> BundleEntry:
304
+ children = self._children(path)
305
+ config, config_path, declared = self._config(BundleKind.ARTIFACT, path, children)
306
+ if declared == "skill" or any(fold(child) == fold(SKILL_MD) for child in children):
307
+ self._skip(path, "this looks like a skill: skills live in skills/<name>/, not artifacts/")
308
+ # A lone Dockerfile spelled another way decides nothing once a type is declared: then it's content.
309
+ if (declared is None or DOCKERFILE in children) and self._near_miss(path, children, DOCKERFILE):
310
+ raise _Skip
311
+ entity_type = declared or self._inferred_type(path, children)
312
+ return self._make(BundleKind.ARTIFACT, name, path, entity_type, config, config.get("id"), config_path)
313
+
314
+ def _build_context(self, kind: BundleKind, name: str, path: Path) -> BundleEntry:
315
+ """An env or agent: a Docker build context, so only its Dockerfile and toml are checked."""
316
+ names = {entry.name for entry in self._list(path)}
317
+ config, config_path, declared = self._config(kind, path, names)
318
+ if DOCKERFILE in names or config_path.name not in names:
319
+ if self._near_miss(path, names, DOCKERFILE):
320
+ raise _Skip
321
+ if DOCKERFILE in names:
322
+ self._marker(path / DOCKERFILE)
323
+ elif config_path.name not in names:
324
+ self._skip(path, f"needs a {DOCKERFILE} or an {config_path.name}")
325
+ entity_type = declared or _DEFAULT_TYPE[kind]
326
+ return self._make(kind, name, path, entity_type, config, config.get("id"), config_path)
327
+
328
+ def _inferred_type(self, path: Path, children: dict[str, str]) -> str:
329
+ if DOCKERFILE in children:
330
+ self._marker(path / DOCKERFILE, children[DOCKERFILE])
331
+ return "docker_image"
332
+ content = [child for child in children if child != CONFIG_FILES[BundleKind.ARTIFACT]]
333
+ if not content:
334
+ self._skip(path, f"an artifact folder has nothing in it ({', '.join(sorted(LEAVINGS))} don't count)")
335
+ return "file" if len(content) == 1 and children[content[0]] == _FILE else "file_artifact_universe"
336
+
337
+ # Parts of an entity
338
+
339
+ def _children(self, path: Path) -> dict[str, str]:
340
+ """The folder's entries less what the OS or Python leaves, each checked to be a file or a folder:
341
+ agent-env uploads these files itself (an env or agent folder is left to Docker's rules instead)."""
342
+ children = {entry.name: self._node(Path(entry.path), entry) for entry in self._list(path)
343
+ if entry.name not in LEAVINGS}
344
+ if None in children.values():
345
+ raise _Skip
346
+ return children
347
+
348
+ def _config(self, kind: BundleKind, path: Path, names: Iterable[str]) -> tuple[dict, Path, str | None]:
349
+ """The entity's toml ({} when absent), where it lives, and the type it declares."""
350
+ config_path = path / CONFIG_FILES[kind]
351
+ if self._near_miss(path, names, config_path.name):
352
+ raise _Skip
353
+ if config_path.name not in names:
354
+ return {}, config_path, None
355
+ config = self._read_toml(config_path)
356
+ declared = config.get("type")
357
+ if declared is not None and not (isinstance(declared, str) and declared):
358
+ self._skip(config_path, "type must be a non-empty string")
359
+ return config, config_path, declared
360
+
361
+ def _marker(self, path: Path, node: str | None = None) -> None:
362
+ """Skip the entity unless the file that marks it (a Dockerfile, SKILL.md) is a file."""
363
+ node = node or self._node(path)
364
+ if node == _DIR:
365
+ self._problem(path, "must be a file, not a folder")
366
+ if node != _FILE:
367
+ raise _Skip
368
+
369
+ def _make(
370
+ self,
371
+ kind: BundleKind,
372
+ name: str,
373
+ path: Path,
374
+ entity_type: str,
375
+ config: Any,
376
+ declared: Any = None,
377
+ declared_in: Path | None = None,
378
+ ) -> BundleEntry:
379
+ entity_id = self._entity_id(kind, name, path, declared, declared_in)
380
+ return BundleEntry(kind=kind, name=name, id=entity_id, path=path, type=entity_type, config=config)
381
+
382
+ def _entity_id(self, kind: BundleKind, name: str, path: Path, declared: Any, declared_in: Path | None) -> str:
383
+ if declared is not None:
384
+ self._check_declared(declared, declared_in or path, artifact=kind.store == "artifact")
385
+ return declared
386
+ reason = _refused(name)
387
+ if reason:
388
+ self._skip(path, f"rename it: {reason}")
389
+ # The root and the name are each validated, so only the length is left to check.
390
+ entity_id = f"{self.id_root}/{name}"
391
+ size = _size(entity_id)
392
+ if self.root_ok and size > MAX_AUTHORED_LOCAL_ID_BYTES:
393
+ remedy = "move the bundle to a shorter path, or shorten the name"
394
+ if self.entry_point:
395
+ remedy = "shorten the name"
396
+ self._skip(path, f"id is {size} bytes, over the {MAX_AUTHORED_LOCAL_ID_BYTES}-byte limit; {remedy}")
397
+ return entity_id
398
+
399
+ def _check_declared(self, entity_id: Any, where: Path, *, what: str = "id", artifact: bool = False) -> None:
400
+ if not isinstance(entity_id, str) or not entity_id.startswith(LOCAL_PREFIX):
401
+ self._skip(where, f"{what} {_brief(entity_id)}: ids declared in a bundle must start with "
402
+ f"{LOCAL_PREFIX!r}, since a bare id names an entity in a shared store")
403
+ size = _size(entity_id)
404
+ if size > MAX_AUTHORED_LOCAL_ID_BYTES:
405
+ limit = MAX_AUTHORED_LOCAL_ID_BYTES
406
+ self._skip(where, f"{what} is {size} bytes, over the {limit}-byte limit; shorten it")
407
+ try:
408
+ validate_local_id(entity_id)
409
+ except ValueError as e:
410
+ self._skip(where, f"{what}: {e}")
411
+ if entity_id != unicodedata.normalize("NFC", entity_id):
412
+ self._skip(where, f"{what} {_brief(entity_id)} must be NFC-normalized")
413
+ if artifact and "__" in entity_id.rsplit("/", 1)[1]:
414
+ self._skip(where, f'{what} {_brief(entity_id)}: "__" is reserved for derived artifact ids')
415
+
416
+ # Across entities
417
+
418
+ def _check_unique(self, entries: list[BundleEntry]) -> None:
419
+ by_name: dict[str, list[BundleEntry]] = defaultdict(list)
420
+ by_id: dict[tuple[str, str], list[BundleEntry]] = defaultdict(list)
421
+ for entry in entries:
422
+ by_id[(entry.kind.store, entry.id)].append(entry)
423
+ if entry.kind.store == "artifact":
424
+ by_name[fold(entry.name)].append(entry)
425
+ # A bare artifact ref looks in artifacts/ and skills/ alike, so a name may live in only one.
426
+ clashing: set[BundleEntry] = set()
427
+ for holders in by_name.values():
428
+ if len(holders) > 1:
429
+ clashing.update(holders)
430
+ self.problems.append(f"{self._paths(h.path for h in holders)} share a name; artifacts and "
431
+ "skills share one store, so rename one")
432
+ for (_, entity_id), holders in by_id.items():
433
+ if len(holders) > 1 and not clashing.issuperset(holders):
434
+ self.problems.append(f"{self._paths(h.path for h in holders)} have the same id {_brief(entity_id)}")
435
+
436
+ # Files
437
+
438
+ def _description(self, readme: Path) -> str | None:
439
+ """README's first line of text, skipping front matter, badges and HTML. The description is
440
+ optional, so an unreadable README has none."""
441
+ try:
442
+ lines = read_regular(readme).decode("utf-8-sig", errors="replace").splitlines()
443
+ except Unreadable:
444
+ return None
445
+ if lines and lines[0].strip() == "---":
446
+ closing = next((index for index, line in enumerate(lines[1:], 1) if line.strip() == "---"), 0)
447
+ lines = lines[closing + 1:]
448
+ for line in lines:
449
+ text = line.strip().lstrip("#").strip()
450
+ if text and not text.startswith(("<", "[![", "![")):
451
+ return show(text)
452
+ return None
453
+
454
+ def _read_toml(self, path: Path) -> dict:
455
+ data = self._read(path)
456
+ try:
457
+ return tomllib.loads(data.decode("utf-8-sig"))
458
+ except RecursionError:
459
+ self._skip(path, "not valid TOML: nested too deeply")
460
+ except ValueError as e:
461
+ self._skip(path, f"not valid TOML: {e}")
462
+
463
+ def _read_json(self, path: Path) -> Any:
464
+ data = self._read(path)
465
+ try:
466
+ return json.loads(data, object_pairs_hook=_no_duplicate_keys, parse_constant=_no_constant)
467
+ except RecursionError:
468
+ self._skip(path, "not valid JSON: nested too deeply")
469
+ except ValueError as e:
470
+ self._skip(path, f"not valid JSON: {e}")
471
+
472
+ def _read(self, path: Path) -> bytes:
473
+ try:
474
+ return read_regular(path)
475
+ except Unreadable as e:
476
+ self._skip(path, str(e))
477
+
478
+ # Listings and problems
479
+
480
+ def _list(self, directory: Path) -> list[os.DirEntry]:
481
+ try:
482
+ with os.scandir(directory) as listing:
483
+ return sorted(listing, key=lambda entry: entry.name)
484
+ except OSError as e:
485
+ self._skip(directory, os_reason(e))
486
+
487
+ def _node(self, path: Path, listed: os.DirEntry | None = None) -> str | None:
488
+ """``_DIR`` or ``_FILE``, following links; anything else is recorded as a problem (and None
489
+ returned, so a caller can go on to the next entry). A listed entry that isn't a link is
490
+ classified from the listing, without a stat."""
491
+ try:
492
+ if listed is not None and not listed.is_symlink():
493
+ is_dir, is_file = listed.is_dir(follow_symlinks=False), listed.is_file(follow_symlinks=False)
494
+ else:
495
+ mode = os.stat(path).st_mode
496
+ is_dir, is_file = stat.S_ISDIR(mode), stat.S_ISREG(mode)
497
+ except OSError as e:
498
+ self._problem(path, "a broken symlink" if isinstance(e, FileNotFoundError) else os_reason(e))
499
+ return None
500
+ if is_dir:
501
+ return _DIR
502
+ if is_file:
503
+ return _FILE
504
+ self._problem(path, "neither a regular file nor a folder")
505
+ return None
506
+
507
+ def _near_miss(self, parent: Path, names: Iterable[str], spelling: str) -> list[str]:
508
+ """The entries of ``names`` that are ``spelling`` in another case, each recorded as a problem:
509
+ alone, a variant is a typo; beside the exact spelling, the two collide on a case-insensitive
510
+ disk (a clone on macOS keeps only one), so the bundle would mean something else there."""
511
+ names = list(names)
512
+ near = sorted(name for name in names if name != spelling and fold(name) == fold(spelling))
513
+ for name in near:
514
+ if spelling in names:
515
+ self._collision([parent / spelling, parent / name])
516
+ else:
517
+ self._problem(parent / name, f"rename to {spelling}; names are case-sensitive" + _spelled_as(name))
518
+ return near
519
+
520
+ def _collision(self, paths: Iterable[Path]) -> None:
521
+ self.problems.append(f"{self._paths(paths)} differ only in case or Unicode form; rename one so the bundle "
522
+ "means the same on every filesystem")
523
+
524
+ def _skip(self, path, message: str) -> NoReturn:
525
+ self._problem(path, message)
526
+ raise _Skip
527
+
528
+ def _problem(self, path, message: str) -> None:
529
+ self.problems.append(f"{self._rel(path)}: {message}")
530
+
531
+ def _paths(self, paths: Iterable[Path]) -> str:
532
+ return " and ".join(sorted(self._rel(path) for path in paths))
533
+
534
+ def _rel(self, path) -> str:
535
+ """``path`` relative to the root for a message; the root itself, and anything outside it,
536
+ stay absolute."""
537
+ text = str(path)
538
+ if text.startswith(self.root_text + os.sep):
539
+ text = text[len(self.root_text) + 1:]
540
+ return show(text)
541
+
542
+
543
+ def _canonical(root: Path) -> Path:
544
+ try:
545
+ resolved = root.expanduser().resolve(strict=True)
546
+ except FileNotFoundError:
547
+ raise BundleError([f"{show(root)}: no such folder"]) from None
548
+ except (OSError, RuntimeError, ValueError) as e:
549
+ raise BundleError([f"{show(root)}: {e}"]) from None
550
+ if not resolved.is_dir():
551
+ raise BundleError([f"{show(root)}: not a folder"])
552
+ if resolved == Path(resolved.anchor):
553
+ raise BundleError(["a bundle cannot be the filesystem root"])
554
+ return on_disk(resolved)
555
+
556
+
557
+ def _refused(segment: str) -> str | None:
558
+ """Why ``segment`` can't be one segment of an id, or None; the reason names the segment."""
559
+ try:
560
+ segment.encode("utf-8")
561
+ except UnicodeEncodeError:
562
+ return "the name is not valid UTF-8"
563
+ as_id = LOCAL_PREFIX + unicodedata.normalize("NFC", segment)
564
+ try:
565
+ validate_local_id(as_id)
566
+ except ValueError as e:
567
+ return str(e).replace(f"local id {as_id!r}", repr(as_id.removeprefix(LOCAL_PREFIX)), 1)
568
+ return None
569
+
570
+
571
+ def _size(entity_id: str) -> int:
572
+ return len(entity_id.encode("utf-8", "surrogatepass"))
573
+
574
+
575
+ def _spelled_as(name: str) -> str:
576
+ """For a near miss that may look right on screen: how it is really spelled, if not plain ASCII."""
577
+ return "" if name.isascii() else f" (it is spelled {ascii(name)})"
578
+
579
+
580
+ def _brief(value: Any) -> str:
581
+ text = repr(value)
582
+ return text if len(text) <= 80 else text[:77] + "..."
583
+
584
+
585
+ def _no_duplicate_keys(pairs: list[tuple[str, Any]]) -> dict:
586
+ result = dict(pairs)
587
+ if len(result) < len(pairs):
588
+ duplicates = sorted(key for key, count in Counter(key for key, _ in pairs).items() if count > 1)
589
+ raise ValueError(f"duplicate keys {duplicates}")
590
+ return result
591
+
592
+
593
+ def _no_constant(name: str) -> Any:
594
+ raise ValueError(f"{name} is not valid JSON")