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.
- agent_env/__init__.py +0 -0
- agent_env/a2a_agent/__init__.py +23 -0
- agent_env/a2a_agent/a2a_agent.py +600 -0
- agent_env/a2a_agent/conversation_store.py +356 -0
- agent_env/a2a_agent/object_transfer.py +609 -0
- agent_env/a2a_agent/protocol.py +238 -0
- agent_env/a2a_agent/store.py +201 -0
- agent_env/a2a_agent/validator.py +901 -0
- agent_env/artifact/__init__.py +48 -0
- agent_env/artifact/artifact.py +74 -0
- agent_env/artifact/artifacts/__init__.py +0 -0
- agent_env/artifact/artifacts/cli.py +83 -0
- agent_env/artifact/artifacts/docker_image.py +457 -0
- agent_env/artifact/artifacts/environment.py +89 -0
- agent_env/artifact/artifacts/environment_universe.py +156 -0
- agent_env/artifact/artifacts/file.py +214 -0
- agent_env/artifact/artifacts/file_artifact_universe.py +206 -0
- agent_env/artifact/artifacts/skill.py +206 -0
- agent_env/artifact/artifacts/vm_image.py +95 -0
- agent_env/artifact/ref.py +15 -0
- agent_env/artifact/registry.py +251 -0
- agent_env/artifact/store.py +295 -0
- agent_env/artifact/universe.py +38 -0
- agent_env/attribution.py +41 -0
- agent_env/bundle/__init__.py +4 -0
- agent_env/bundle/_fs.py +128 -0
- agent_env/bundle/authoring.py +239 -0
- agent_env/bundle/installed.py +175 -0
- agent_env/bundle/ledger.py +269 -0
- agent_env/bundle/materialize.py +204 -0
- agent_env/bundle/parse.py +594 -0
- agent_env/bundle/plan.py +414 -0
- agent_env/bundle/resolve.py +404 -0
- agent_env/bundle/run.py +361 -0
- agent_env/cli/__init__.py +69 -0
- agent_env/cli/__main__.py +10 -0
- agent_env/cli/_installers.py +576 -0
- agent_env/cli/_plugin_changes.py +947 -0
- agent_env/cli/a2a_agent/__init__.py +22 -0
- agent_env/cli/a2a_agent/add_skill.py +97 -0
- agent_env/cli/a2a_agent/deploy.py +60 -0
- agent_env/cli/a2a_agent/get.py +15 -0
- agent_env/cli/a2a_agent/get_instance.py +26 -0
- agent_env/cli/a2a_agent/put.py +78 -0
- agent_env/cli/a2a_agent/validate.py +56 -0
- agent_env/cli/artifact/__init__.py +20 -0
- agent_env/cli/artifact/cli.py +83 -0
- agent_env/cli/artifact/environment.py +44 -0
- agent_env/cli/artifact/environment_universe.py +163 -0
- agent_env/cli/artifact/file_artifact_universe.py +281 -0
- agent_env/cli/artifact/skill.py +128 -0
- agent_env/cli/banner.py +25 -0
- agent_env/cli/config.py +263 -0
- agent_env/cli/env/__init__.py +31 -0
- agent_env/cli/env/deploy.py +112 -0
- agent_env/cli/env/gateway.py +57 -0
- agent_env/cli/env/get_instance.py +40 -0
- agent_env/cli/env/mcp_server.py +410 -0
- agent_env/cli/env/multi.py +282 -0
- agent_env/cli/env/service_db.py +99 -0
- agent_env/cli/env/snapshot.py +35 -0
- agent_env/cli/env/state/__init__.py +6 -0
- agent_env/cli/env/state/init.py +108 -0
- agent_env/cli/env/state/teardown.py +44 -0
- agent_env/cli/env/website.py +216 -0
- agent_env/cli/env/website_browser.py +67 -0
- agent_env/cli/eval/__init__.py +16 -0
- agent_env/cli/eval/add_tasks.py +63 -0
- agent_env/cli/eval/create.py +49 -0
- agent_env/cli/eval/run.py +194 -0
- agent_env/cli/identity/__init__.py +5 -0
- agent_env/cli/identity/client_identity.py +37 -0
- agent_env/cli/plugin.py +438 -0
- agent_env/cli/run.py +285 -0
- agent_env/cli/task/__init__.py +21 -0
- agent_env/cli/task/create.py +109 -0
- agent_env/cli/task/get.py +17 -0
- agent_env/cli/task/get_instance.py +34 -0
- agent_env/cli/task/run.py +615 -0
- agent_env/cli/task/validate.py +31 -0
- agent_env/cli/up.py +123 -0
- agent_env/cli/utils.py +183 -0
- agent_env/config/__init__.py +50 -0
- agent_env/config/describe.py +1067 -0
- agent_env/config/errors.py +13 -0
- agent_env/config/loader.py +245 -0
- agent_env/config/model.py +154 -0
- agent_env/config/paths.py +25 -0
- agent_env/config/plugin_tables.py +101 -0
- agent_env/config/provenance.py +134 -0
- agent_env/config/runtime.py +1064 -0
- agent_env/config/snapshot.py +81 -0
- agent_env/entity_refs.py +186 -0
- agent_env/env/__init__.py +49 -0
- agent_env/env/env.py +433 -0
- agent_env/env/env_artifact_store.py +87 -0
- agent_env/env/envs/__init__.py +7 -0
- agent_env/env/envs/_deployment.py +281 -0
- agent_env/env/envs/gateway_server.py +32 -0
- agent_env/env/envs/mcp_server.py +387 -0
- agent_env/env/envs/multi_env.py +780 -0
- agent_env/env/envs/service_db/Dockerfile +20 -0
- agent_env/env/envs/service_db/Dockerfile.db-mcp +42 -0
- agent_env/env/envs/service_db/Dockerfile.db-web +8 -0
- agent_env/env/envs/service_db.py +92 -0
- agent_env/env/envs/website.py +294 -0
- agent_env/env/envs/website_browser/Dockerfile +40 -0
- agent_env/env/envs/website_browser/__init__.py +17 -0
- agent_env/env/envs/website_browser/entrypoint.sh +13 -0
- agent_env/env/gateway/Dockerfile +14 -0
- agent_env/env/gateway/__init__.py +37 -0
- agent_env/env/gateway/clock.py +184 -0
- agent_env/env/gateway/constants.py +190 -0
- agent_env/env/gateway/entrypoint.py +156 -0
- agent_env/env/gateway/gateway.py +1095 -0
- agent_env/env/gateway/get_time.py +60 -0
- agent_env/env/gateway/requirements.txt +4 -0
- agent_env/env/gateway/triggers.py +1193 -0
- agent_env/env/legacy_protocol.py +146 -0
- agent_env/env/registry.py +93 -0
- agent_env/env/snapshot_store.py +372 -0
- agent_env/env/store.py +411 -0
- agent_env/eval/__init__.py +14 -0
- agent_env/eval/eval.py +68 -0
- agent_env/eval/store.py +116 -0
- agent_env/examples/hello/README.md +9 -0
- agent_env/examples/hello/artifacts/greeting/check.sh +1 -0
- agent_env/examples/hello/artifacts/greeting/hello.txt +1 -0
- agent_env/examples/hello/tasks/hello.json +10 -0
- agent_env/explorer/__init__.py +12 -0
- agent_env/explorer/app.py +277 -0
- agent_env/explorer/openapi_docs.py +242 -0
- agent_env/explorer/plugin.py +95 -0
- agent_env/explorer/routers/__init__.py +1 -0
- agent_env/explorer/routers/common.py +174 -0
- agent_env/explorer/routers/conversations.py +25 -0
- agent_env/explorer/routers/objects.py +112 -0
- agent_env/explorer/routers/runs.py +475 -0
- agent_env/plugins/__init__.py +59 -0
- agent_env/plugins/_cli.py +244 -0
- agent_env/plugins/_discovery.py +97 -0
- agent_env/plugins/_inventory.py +262 -0
- agent_env/plugins/_registration.py +268 -0
- agent_env/plugins/_report.py +47 -0
- agent_env/plugins/_requirements.py +55 -0
- agent_env/providers/__init__.py +37 -0
- agent_env/providers/env_providers/__init__.py +12 -0
- agent_env/providers/env_providers/constants.py +13 -0
- agent_env/providers/env_providers/env_gateway_provider.py +1354 -0
- agent_env/providers/env_providers/env_provider.py +237 -0
- agent_env/providers/env_providers/env_server_provider.py +133 -0
- agent_env/providers/env_state/__init__.py +49 -0
- agent_env/providers/env_state/env_state_provider.py +554 -0
- agent_env/providers/env_state/local_postgres.py +390 -0
- agent_env/providers/env_state/store.py +112 -0
- agent_env/providers/sandbox_providers/__init__.py +29 -0
- agent_env/providers/sandbox_providers/chained_sandbox_provider.py +93 -0
- agent_env/providers/sandbox_providers/e2b/__init__.py +6 -0
- agent_env/providers/sandbox_providers/e2b/provider.py +376 -0
- agent_env/providers/sandbox_providers/e2b/sandbox.py +342 -0
- agent_env/providers/sandbox_providers/e2b/template.py +158 -0
- agent_env/providers/sandbox_providers/local_sandbox.py +408 -0
- agent_env/providers/sandbox_providers/modal_sandbox.py +500 -0
- agent_env/providers/sandbox_providers/modal_vm_sandbox.py +466 -0
- agent_env/providers/sandbox_providers/sandbox.py +387 -0
- agent_env/providers/sandbox_providers/sandbox_provider.py +614 -0
- agent_env/py.typed +0 -0
- agent_env/runner/__init__.py +16 -0
- agent_env/runner/local_runner.py +190 -0
- agent_env/runner/runner.py +127 -0
- agent_env/runner/store.py +94 -0
- agent_env/store/__init__.py +126 -0
- agent_env/store/_google.py +68 -0
- agent_env/store/base.py +33 -0
- agent_env/store/document_store/__init__.py +60 -0
- agent_env/store/document_store/document_store.py +519 -0
- agent_env/store/document_store/dynamodb_document_store.py +306 -0
- agent_env/store/document_store/evaluation.py +199 -0
- agent_env/store/document_store/firestore_mongo_document_store.py +242 -0
- agent_env/store/document_store/mongo_document_store.py +259 -0
- agent_env/store/document_store/sqlite_document_store.py +314 -0
- agent_env/store/ids.py +123 -0
- agent_env/store/image_store/__init__.py +34 -0
- agent_env/store/image_store/ecr_image_store.py +131 -0
- agent_env/store/image_store/google_credentials.py +113 -0
- agent_env/store/image_store/image_store.py +113 -0
- agent_env/store/image_store/local_registry_image_store.py +106 -0
- agent_env/store/image_store/oci_registry_credentials.py +196 -0
- agent_env/store/local_state.py +27 -0
- agent_env/store/object_store/__init__.py +24 -0
- agent_env/store/object_store/gcs_object_store.py +415 -0
- agent_env/store/object_store/local_object_store.py +143 -0
- agent_env/store/object_store/object_store.py +198 -0
- agent_env/store/object_store/s3_object_store.py +354 -0
- agent_env/store/query.py +112 -0
- agent_env/store/routing.py +609 -0
- agent_env/store/secret_store/__init__.py +19 -0
- agent_env/store/secret_store/aws_secrets_manager_secret_store.py +293 -0
- agent_env/store/secret_store/gcp_secret_manager_secret_store.py +319 -0
- agent_env/store/secret_store/local_secret_store.py +47 -0
- agent_env/store/secret_store/secret_store.py +19 -0
- agent_env/task/__init__.py +27 -0
- agent_env/task/interrupts.py +109 -0
- agent_env/task/registry.py +27 -0
- agent_env/task/step_journal.py +99 -0
- agent_env/task/store.py +940 -0
- agent_env/task/task.py +815 -0
- agent_env/task/teardown.py +142 -0
- agent_env/task_step/__init__.py +47 -0
- agent_env/task_step/context.py +195 -0
- agent_env/task_step/context_ops.py +224 -0
- agent_env/task_step/registry.py +182 -0
- agent_env/task_step/review_store.py +118 -0
- agent_env/task_step/snapshot_utils/__init__.py +2 -0
- agent_env/task_step/snapshot_utils/agent_state_capture.py +261 -0
- agent_env/task_step/snapshot_utils/snapshot_series.py +631 -0
- agent_env/task_step/store.py +129 -0
- agent_env/task_step/task_step.py +173 -0
- agent_env/task_step/task_steps/__init__.py +27 -0
- agent_env/task_step/task_steps/a2a_agent_validator/__init__.py +31 -0
- agent_env/task_step/task_steps/a2a_agent_validator/fixtures/README.md +158 -0
- agent_env/task_step/task_steps/a2a_agent_validator/fixtures/clip.m4a +0 -0
- agent_env/task_step/task_steps/a2a_agent_validator/fixtures/clip.mp3 +0 -0
- agent_env/task_step/task_steps/a2a_agent_validator/fixtures/clip.mp4 +0 -0
- agent_env/task_step/task_steps/a2a_agent_validator/fixtures/clip.ogg +0 -0
- agent_env/task_step/task_steps/a2a_agent_validator/fixtures/clip.wav +0 -0
- agent_env/task_step/task_steps/a2a_agent_validator/fixtures/document.pdf +0 -0
- agent_env/task_step/task_steps/a2a_agent_validator/fixtures/red.gif +0 -0
- agent_env/task_step/task_steps/a2a_agent_validator/fixtures/red.jpg +0 -0
- agent_env/task_step/task_steps/a2a_agent_validator/fixtures/red.png +0 -0
- agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_agent_card.py +103 -0
- agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_agent_config_identity.py +69 -0
- agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_agent_mcp.py +178 -0
- agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_core_protocol.py +67 -0
- agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_install.py +115 -0
- agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_litellm_attribution.py +124 -0
- agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_litellm_attribution_runtime.py +173 -0
- agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_modalities.py +270 -0
- agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_peer_agents.py +102 -0
- agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_role.py +151 -0
- agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_skill_config.py +194 -0
- agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_snapshot.py +111 -0
- agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_system_prompt.py +215 -0
- agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_trajectory.py +164 -0
- agent_env/task_step/task_steps/add_skills.py +240 -0
- agent_env/task_step/task_steps/apply_server_config.py +288 -0
- agent_env/task_step/task_steps/collect_artifacts.py +940 -0
- agent_env/task_step/task_steps/deploy_agent.py +626 -0
- agent_env/task_step/task_steps/deploy_env.py +197 -0
- agent_env/task_step/task_steps/deploy_human_agent.py +100 -0
- agent_env/task_step/task_steps/deploy_sandbox.py +170 -0
- agent_env/task_step/task_steps/env_card_validator/__init__.py +4 -0
- agent_env/task_step/task_steps/env_card_validator/verify_env_card.py +109 -0
- agent_env/task_step/task_steps/env_card_validator/verify_env_core_protocol.py +108 -0
- agent_env/task_step/task_steps/install_agent.py +376 -0
- agent_env/task_step/task_steps/load_artifact.py +775 -0
- agent_env/task_step/task_steps/mcp_cli_builder/__init__.py +4 -0
- agent_env/task_step/task_steps/mcp_cli_builder/build_mcp_cli.py +201 -0
- agent_env/task_step/task_steps/mcp_cli_builder/codegen.py +627 -0
- agent_env/task_step/task_steps/mcp_env_validator/__init__.py +44 -0
- agent_env/task_step/task_steps/mcp_env_validator/validation_gate_aggregator.py +102 -0
- agent_env/task_step/task_steps/mcp_env_validator/verify_mcp_env_assessment.py +78 -0
- agent_env/task_step/task_steps/mcp_env_validator/verify_mcp_tool_schema.py +152 -0
- agent_env/task_step/task_steps/mcp_env_validator/verify_spec_conformance.py +486 -0
- agent_env/task_step/task_steps/modify_env_tool_access.py +80 -0
- agent_env/task_step/task_steps/multienv_validator/__init__.py +3 -0
- agent_env/task_step/task_steps/multienv_validator/combine_universe_verdicts.py +107 -0
- agent_env/task_step/task_steps/multienv_validator/universe_comparison.py +253 -0
- agent_env/task_step/task_steps/multienv_validator/verify_universe_agent_judge.py +180 -0
- agent_env/task_step/task_steps/multienv_validator/verify_universe_roundtrip.py +241 -0
- agent_env/task_step/task_steps/peer_agents.py +92 -0
- agent_env/task_step/task_steps/prompt_agent.py +900 -0
- agent_env/task_step/task_steps/register_agent_triggers.py +113 -0
- agent_env/task_step/task_steps/register_env_triggers.py +97 -0
- agent_env/task_step/task_steps/reset_env.py +71 -0
- agent_env/task_step/task_steps/review.py +152 -0
- agent_env/task_step/task_steps/run_code.py +461 -0
- agent_env/task_step/task_steps/run_code_runner.py +52 -0
- agent_env/task_step/task_steps/run_docker_container.py +380 -0
- agent_env/task_step/task_steps/sandbox_utils/__init__.py +0 -0
- agent_env/task_step/task_steps/sandbox_utils/sandbox_utils.py +79 -0
- agent_env/task_step/task_steps/snapshot_agent_state.py +205 -0
- agent_env/task_step/task_steps/snapshot_env.py +637 -0
- agent_env/task_step/task_steps/sync_env_clock.py +132 -0
- agent_env/task_step/task_steps/teardown_sandboxes.py +170 -0
- agent_env/task_step/task_steps/verifiers/__init__.py +23 -0
- agent_env/task_step/task_steps/verifiers/agent_prompt_response_verifier.py +166 -0
- agent_env/task_step/task_steps/verifiers/aggregate_verifiers.py +90 -0
- agent_env/task_step/task_steps/verifiers/env_outcome_verifier.py +127 -0
- agent_env/task_step/task_steps/verifiers/judge_utils/__init__.py +2 -0
- agent_env/task_step/task_steps/verifiers/judge_utils/frame_selection.py +377 -0
- agent_env/task_step/task_steps/verifiers/judge_utils/judge_output_format.py +1293 -0
- agent_env/task_step/task_steps/verifiers/judge_utils/trajectory_filter.py +514 -0
- agent_env/task_step/task_steps/verifiers/rubrics_verifier.py +1318 -0
- agent_env/task_step/task_steps/verifiers/run_container_unit_tests_verifier.py +434 -0
- agent_env/task_step/task_steps/verifiers/scoring.py +40 -0
- agent_env/task_step/task_steps/verifiers/verify_sandbox.py +308 -0
- agent_env/task_step/thread_work.py +61 -0
- agent_env/utils/__init__.py +0 -0
- agent_env/utils/card_naming.py +108 -0
- agent_env/utils/deprecation.py +109 -0
- agent_env/utils/docker_build.py +29 -0
- agent_env/utils/exec_retry.py +77 -0
- agent_env/utils/litellm_attribution.py +59 -0
- agent_env/utils/paths.py +20 -0
- agentenv_framework-0.9.1254.dist-info/METADATA +394 -0
- agentenv_framework-0.9.1254.dist-info/RECORD +312 -0
- agentenv_framework-0.9.1254.dist-info/WHEEL +4 -0
- agentenv_framework-0.9.1254.dist-info/entry_points.txt +5 -0
- agentenv_framework-0.9.1254.dist-info/licenses/LICENSE +202 -0
- agentenv_framework-0.9.1254.dist-info/licenses/NOTICE +4 -0
- 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")
|